Blame view

src/core/pyros_django/user_mgmt/views.py 18.7 KB
eefbbbd2   Etienne Pallier   Model splitting g...
1
2
3
4
5
# Standard imports
import os
#import sys

# Django imports
1ba49504   Alexis Koralewski   fixing CSS and JS...
6
from django.shortcuts import render, redirect
e419a2f6   Alexis Koralewski   Add new version f...
7
8
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
02d94ed3   Alexis Koralewski   Reworking UI of w...
9
from django.contrib import messages
e419a2f6   Alexis Koralewski   Add new version f...
10
from django.shortcuts import get_object_or_404
e419a2f6   Alexis Koralewski   Add new version f...
11
from django.core.mail import send_mail
e419a2f6   Alexis Koralewski   Add new version f...
12
from django.urls import reverse
1ba49504   Alexis Koralewski   fixing CSS and JS...
13
14
from django.http import HttpResponseRedirect, HttpResponse
from django.conf import settings
ad3b297c   Alexis Koralewski   add pagination to...
15
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
eefbbbd2   Etienne Pallier   Model splitting g...
16
17

# Project imports
b95a693f   Alexis Koralewski   restructuration d...
18
19
from user_mgmt.models import PyrosUser, UserLevel, ScientificProgram, SP_Period, SP_Period_User
#scp_mgmt.models import ScientificProgram, SP_Period, SP_Period_User
eefbbbd2   Etienne Pallier   Model splitting g...
20
from dashboard.decorator import level_required
43d8ca44   Etienne Pallier   moved dashboard.U...
21
22
#from dashboard.forms import UserForm
from .forms import UserForm, PyrosUserCreationForm, UserPasswordResetForm
41bdf9a6   Alexis Koralewski   Adding SP on user...
23
from src.pyros_logger import log
b95a693f   Alexis Koralewski   restructuration d...
24
from src.core.pyros_django.obs_config.obsconfig_class import OBSConfig
e419a2f6   Alexis Koralewski   Add new version f...
25
26
27

LOGGED_PAGE = "../../dashboard/templates/dashboard/index.html"

1ba49504   Alexis Koralewski   fixing CSS and JS...
28

e419a2f6   Alexis Koralewski   Add new version f...
29
30
31
32
33
def home(request):
    '''
        Initial login view when coming on the website
    '''
    if request.user.is_authenticated:
1ba49504   Alexis Koralewski   fixing CSS and JS...
34
35
36
        return(render(request, LOGGED_PAGE, {'USER_LEVEL': request.user.get_priority(), 'base_template': "base.html", 'weather_img': "normal"}))
    return(render(request, LOGGED_PAGE, {"USER_LEVEL": "Visitor", 'base_template': 'base.html', 'weather_img': "red"}))

e419a2f6   Alexis Koralewski   Add new version f...
37
38

def roles_description(request):
b95a693f   Alexis Koralewski   restructuration d...
39
    return (render(request, "user_mgmt/roles_description.html"))
1ba49504   Alexis Koralewski   fixing CSS and JS...
40
41


e419a2f6   Alexis Koralewski   Add new version f...
42
43
44
45
46
47
48
49
50
def create_user(request):
    '''
        View called to open the user creation form
    '''
    """
    if request.user.is_authenticated:
        return(render(request, LOGGED_PAGE, {'USER_LEVEL': request.user.get_priority(), 'base_template' : "base.html", 'weather_img': "normal"}))
    """
    form = PyrosUserCreationForm()
b95a693f   Alexis Koralewski   restructuration d...
51
    return (render(request, "user_mgmt/home_user_creation.html", locals()))
e419a2f6   Alexis Koralewski   Add new version f...
52

1ba49504   Alexis Koralewski   fixing CSS and JS...
53

81d77f22   Alexis Koralewski   Adding 'forgotten...
54
55
def forgotten_password(request):
    form = UserPasswordResetForm()
1ba49504   Alexis Koralewski   fixing CSS and JS...
56
    message = ""
dc5e48b6   Alexis Koralewski   Fixing who can ed...
57
    user = None
81d77f22   Alexis Koralewski   Adding 'forgotten...
58
59
    if request.POST:
        password = PyrosUser.objects.make_random_password()
dc5e48b6   Alexis Koralewski   Fixing who can ed...
60
61
62
63
        try:
            user = PyrosUser.objects.get(email=request.POST["email"])
        except PyrosUser.DoesNotExist:
            message = "The email adress is invalid"
81d77f22   Alexis Koralewski   Adding 'forgotten...
64
65
66
67
68
        if user != None:
            user.set_password(password)
            user.save()
            send_mail(
                '[PyROS CC] Registration',
dc5e48b6   Alexis Koralewski   Fixing who can ed...
69
                f"Hello,\nYou recently took steps to reset the password for your PyROS account. A temporary password has been assigned, please log in with the following password: '{password}'. \n\nCordially,\n\nPyROS Control Center",
81d77f22   Alexis Koralewski   Adding 'forgotten...
70
71
72
73
                '',
                [request.POST['email']],
                fail_silently=False,
            )
1ba49504   Alexis Koralewski   fixing CSS and JS...
74
            message = "The email has been send !"
dc5e48b6   Alexis Koralewski   Fixing who can ed...
75
        else:
b95a693f   Alexis Koralewski   restructuration d...
76
77
            return render(request, 'user_mgmt/forgotten_password.html', {"form": form, "message": message})
    return render(request, 'user_mgmt/forgotten_password.html', {"form": form, "message": message})
1ba49504   Alexis Koralewski   fixing CSS and JS...
78

81d77f22   Alexis Koralewski   Adding 'forgotten...
79

e419a2f6   Alexis Koralewski   Add new version f...
80
81
82
83
84
85
86
87
88
89
def user_signup_validation(request):
    '''
        View called to validate the user creation (form submitted)
    '''
    """
    if request.user.is_authenticated:
        return(render(request, LOGGED_PAGE, {'USER_LEVEL': request.user.get_priority(), 'base_template' : "base.html", 'weather_img': "normal"}))
    """
    form = PyrosUserCreationForm(request.POST)
    if request.POST:
35daee3f   Alexis Koralewski   Add bot security ...
90
91
92
        if int(request.POST.get("timer")) < 10:
            error = True
            message = "(Bot prevention) You were too quick to fill the form, please take at least 10 seconds to send the form"
e419a2f6   Alexis Koralewski   Add new version f...
93
        else:
35daee3f   Alexis Koralewski   Add bot security ...
94
95
96
97
98
99
100
101
102
            if "six" != request.POST.get("question").strip():
                error = True
                message = "Wrong answer to the question (Write the answer in letter and lowercase"
            else:
                if form.is_valid() and len(request.POST.get("iambot")) <= 0:
                    form.save()
                    message = "Account creation successful ! Login to continue"
                    success = True
                    if request.user.is_authenticated:
1ba49504   Alexis Koralewski   fixing CSS and JS...
103

35daee3f   Alexis Koralewski   Add bot security ...
104
105
106
107
108
                        if request.POST.get("next"):
                            return redirect(request.POST.get('next'))
                        else:
                            return redirect(reverse("users"))
                    else:
b95a693f   Alexis Koralewski   restructuration d...
109
                        return(render(request, "user_mgmt/home_login.html", locals()))
35daee3f   Alexis Koralewski   Add bot security ...
110
111
112
                else:
                    message = "One or more fields contain errors. Please try again"
                    form_errors = form.errors
e419a2f6   Alexis Koralewski   Add new version f...
113
114
115
116
    else:
        message = "The system encountered an error. Please try again"

    error = True
b95a693f   Alexis Koralewski   restructuration d...
117
    return (render(request, "user_mgmt/home_user_creation.html", locals()))
e419a2f6   Alexis Koralewski   Add new version f...
118

1ba49504   Alexis Koralewski   fixing CSS and JS...
119

e419a2f6   Alexis Koralewski   Add new version f...
120
121
122
123
def login_validation(request):
    '''
        View called when the user log in (form submitted)
    '''
1ba49504   Alexis Koralewski   fixing CSS and JS...
124
125
    config = OBSConfig(
        os.environ["PATH_TO_OBSCONF_FILE"], os.environ["unit_name"])
ad3b297c   Alexis Koralewski   add pagination to...
126
127
128
129
    observatory_name = config.get_obs_name()
    first_unit_name = config.get_units_name()[0]
    request.session["obsname"] = observatory_name+" "+first_unit_name
    request.session["pyros_config"] = settings.CONFIG_PYROS
e419a2f6   Alexis Koralewski   Add new version f...
130
    if request.user.is_authenticated:
e419a2f6   Alexis Koralewski   Add new version f...
131
132
133
134
        if request.POST.get("next"):
            return redirect(request.POST.get('next'))
        # initiate variable session for telling which role the user is using if this user has multiple roles
        # default role is the role with maximum priority
1ba49504   Alexis Koralewski   fixing CSS and JS...
135
136
        request.session["role"] = str(UserLevel.objects.get(
            priority=request.user.get_priority()))
02d94ed3   Alexis Koralewski   Reworking UI of w...
137
        return redirect(reverse("index"))
e419a2f6   Alexis Koralewski   Add new version f...
138
139
140
141
    username = password = ''
    if request.POST:
        email = request.POST.get('email')
        password = request.POST.get('password')
81d77f22   Alexis Koralewski   Adding 'forgotten...
142
143
144
145
        try:
            is_user_active = PyrosUser.objects.get(username=email).is_active
        except:
            is_user_active = None
e419a2f6   Alexis Koralewski   Add new version f...
146
147
148
149
150
151
152
153
154
155
        user = authenticate(username=email, password=password)
        if user is not None:
            success = False
            if user.is_active:
                login(request, user)
                request.session['user'] = email
                message = "Oui"
                success = True
                # initiate variable session for telling which role the user is using if this user has multiple roles
                # default role is the role with maximum priority
1ba49504   Alexis Koralewski   fixing CSS and JS...
156
157
                request.session["role"] = str(UserLevel.objects.get(
                    priority=request.user.get_priority()))
41bdf9a6   Alexis Koralewski   Adding SP on user...
158
                log.info(f"User {user} did action login")
e419a2f6   Alexis Koralewski   Add new version f...
159
160
                if request.POST.get("next"):
                    return redirect(request.POST.get('next'))
02d94ed3   Alexis Koralewski   Reworking UI of w...
161
                return redirect(reverse("index"))
e419a2f6   Alexis Koralewski   Add new version f...
162
            else:
81d77f22   Alexis Koralewski   Adding 'forgotten...
163
                message = "Your account is not active, please contact the Unit-PI."
e419a2f6   Alexis Koralewski   Add new version f...
164
        else:
81d77f22   Alexis Koralewski   Adding 'forgotten...
165
166
167
168
            if is_user_active != None and not is_user_active:
                message = "Your account is not active, please contact the Unit-PI."
            elif is_user_active or is_user_active == None:
                message = "Your email and/or password were incorrect."
1ba49504   Alexis Koralewski   fixing CSS and JS...
169

e419a2f6   Alexis Koralewski   Add new version f...
170
171
172
    else:
        message = "An unexpected error has occurred"
    error = True
b95a693f   Alexis Koralewski   restructuration d...
173
    return(render(request, "user_mgmt/home_login.html", locals()))
e419a2f6   Alexis Koralewski   Add new version f...
174

e419a2f6   Alexis Koralewski   Add new version f...
175
176
177
178

@login_required
def superoperator_return(request):
    current_user = request.user
b95a693f   Alexis Koralewski   restructuration d...
179
    return(render(request, "user_mgmt/user_detail.html", {'user': current_user, 'admin': 0}))
e419a2f6   Alexis Koralewski   Add new version f...
180

1ba49504   Alexis Koralewski   fixing CSS and JS...
181

e419a2f6   Alexis Koralewski   Add new version f...
182
183
184
185
186
@login_required
def user_logout(request):
    '''
        View called to log out. Redirects on login page.
    '''
190c6ece   Alexis Koralewski   Fixing test with ...
187
    if request.method == "POST":
8077341c   Alexis Koralewski   Update logout for...
188
189
190
191
192
193
194
195
196
        log.info(f"User {request.user} did action logout")
        logout(request)
        config = OBSConfig(
            os.environ["PATH_TO_OBSCONF_FILE"], os.environ["unit_name"])
        observatory_name = config.get_obs_name()
        first_unit_name = config.get_units_name()[0]
        request.session["obsname"] = observatory_name+" "+first_unit_name
        return redirect(reverse("index"))
        return(render(request, LOGGED_PAGE, {'USER_LEVEL':  "Visitor", 'base_template': 'base.html', 'weather_img': "red"}))
1ba49504   Alexis Koralewski   fixing CSS and JS...
197

e419a2f6   Alexis Koralewski   Add new version f...
198
199

def user_signin(request):
b95a693f   Alexis Koralewski   restructuration d...
200
    return(render(request, "user_mgmt/home_login.html", {"next": request.GET.get("next")}))
e419a2f6   Alexis Koralewski   Add new version f...
201
202
203


@login_required
1ba49504   Alexis Koralewski   fixing CSS and JS...
204
205
206
@level_required("Admin", "Unit-PI")
def delete_user(request, pk):
    user_to_be_deleted = get_object_or_404(PyrosUser, pk=pk)
81d77f22   Alexis Koralewski   Adding 'forgotten...
207
    if request.user != user_to_be_deleted and request.method == "POST":
e419a2f6   Alexis Koralewski   Add new version f...
208
209
        user_to_be_deleted.delete()
        return HttpResponseRedirect(reverse('users'))
81d77f22   Alexis Koralewski   Adding 'forgotten...
210
    else:
1ba49504   Alexis Koralewski   fixing CSS and JS...
211
        return HttpResponseRedirect(reverse("user_detail", kwargs={"pk": pk}))
e419a2f6   Alexis Koralewski   Add new version f...
212
213
214


@login_required
a61943b5   Alexis Koralewski   Reworking Unit-bo...
215
@level_required("Admin", "Observer", "Management", "Operator", "Unit-PI", "TAC", "Unit-board")
e419a2f6   Alexis Koralewski   Add new version f...
216
217
218
def users(request):
    current_user = request.user
    pyros_users_with_roles = []
dc5e48b6   Alexis Koralewski   Fixing who can ed...
219
    admin_and_unit_users = []
02d94ed3   Alexis Koralewski   Reworking UI of w...
220
    inactive_pyros_users = None
81d77f22   Alexis Koralewski   Adding 'forgotten...
221
    common_scientific_programs = None
e419a2f6   Alexis Koralewski   Add new version f...
222
223
224
225
    if request.session.get("role"):
        role = request.session.get("role")
    else:
        role = current_user.get_priority()
a61943b5   Alexis Koralewski   Reworking Unit-bo...
226
    if role in "Admin,Unit-PI,Unit-board":
1ba49504   Alexis Koralewski   fixing CSS and JS...
227
228
229
230
        pyros_users_with_roles = PyrosUser.objects.exclude(
            is_active=False).order_by("-id")
        inactive_pyros_users = PyrosUser.objects.filter(
            is_active=False).order_by("-id")
e419a2f6   Alexis Koralewski   Add new version f...
231
    else:
d8b6bc10   Alexis Koralewski   Add schema (Md fi...
232
        sp_of_current_user = current_user.get_scientific_programs()
1ba49504   Alexis Koralewski   fixing CSS and JS...
233
234
        sp_periods_of_current_user = SP_Period.objects.filter(
            scientific_program__in=sp_of_current_user)
81d77f22   Alexis Koralewski   Adding 'forgotten...
235
        common_scientific_programs = sp_of_current_user
1ba49504   Alexis Koralewski   fixing CSS and JS...
236
237
        for sp in sp_periods_of_current_user:
            for user in SP_Period_User.objects.filter(SP_Period__in=sp_periods_of_current_user).exclude(user=current_user).values_list("user", flat=True):
e419a2f6   Alexis Koralewski   Add new version f...
238
                pyros_users_with_roles.append(PyrosUser.objects.get(id=user))
1ba49504   Alexis Koralewski   fixing CSS and JS...
239
240
241
242
            pyros_users_with_roles.append(
                sp.scientific_program.sp_pi)
        admin_and_unit_users = PyrosUser.objects.filter(
            user_level__name__in=("Unit-PI", "Unit-board", "Admin")).distinct()
e419a2f6   Alexis Koralewski   Add new version f...
243
    nb_of_scientific_program = ScientificProgram.objects.count()
a61943b5   Alexis Koralewski   Reworking Unit-bo...
244
    CAN_ADD_USER = request.session.get("role") in ("Admin,Unit-PI,Unit-board")
e419a2f6   Alexis Koralewski   Add new version f...
245
246
    # need the negative to calculate in the template for adjusting correctly the information display
    negative_nb_scientific_program = -nb_of_scientific_program
ad3b297c   Alexis Koralewski   add pagination to...
247
248

    page = request.GET.get('page', 1)
1ba49504   Alexis Koralewski   fixing CSS and JS...
249
250
    pyros_users_paginator = Paginator(
        pyros_users_with_roles, settings.NB_ELEMENT_PER_PAGE)
ad3b297c   Alexis Koralewski   add pagination to...
251
252
253
254
255
    try:
        pyros_users_with_roles = pyros_users_paginator.page(page)
    except PageNotAnInteger:
        pyros_users_with_roles = pyros_users_paginator.page(1)
    except EmptyPage:
1ba49504   Alexis Koralewski   fixing CSS and JS...
256
257
        pyros_users_with_roles = pyros_users_paginator.page(
            pyros_users_paginator.num_pages)
b95a693f   Alexis Koralewski   restructuration d...
258
    return render(request, 'user_mgmt/users_management.html', {
cc15cb36   Alexis Koralewski   improving user ac...
259
        'pyros_users_with_roles': pyros_users_with_roles,
1ba49504   Alexis Koralewski   fixing CSS and JS...
260
        "inactive_pyros_users": inactive_pyros_users,
cc15cb36   Alexis Koralewski   improving user ac...
261
        "nb_of_scientific_program": nb_of_scientific_program,
1ba49504   Alexis Koralewski   fixing CSS and JS...
262
263
        "negative_nb_scientific_program": negative_nb_scientific_program,
        "common_scientific_programs": common_scientific_programs,
dc5e48b6   Alexis Koralewski   Fixing who can ed...
264
        "admin_and_unit_users": admin_and_unit_users,
cc15cb36   Alexis Koralewski   improving user ac...
265
        "CAN_ADD_USER": CAN_ADD_USER
1ba49504   Alexis Koralewski   fixing CSS and JS...
266
267
    })

e419a2f6   Alexis Koralewski   Add new version f...
268
269

@login_required
a61943b5   Alexis Koralewski   Reworking Unit-bo...
270
@level_required("Admin", "Unit-PI", "Unit-board")
e419a2f6   Alexis Koralewski   Add new version f...
271
def change_activate(request, pk, current_user_id):
02d94ed3   Alexis Koralewski   Reworking UI of w...
272
273
274
275
276
    role = None
    if request.session.get("role") != None:
        role = request.session.get("role")
    else:
        role = UserLevel.objects.get(priority=request.user.get_priority()).name
a61943b5   Alexis Koralewski   Reworking Unit-bo...
277
    if role in ["Admin", "Unit-PI", "Unit-board"]:
1ba49504   Alexis Koralewski   fixing CSS and JS...
278
        try:
81d77f22   Alexis Koralewski   Adding 'forgotten...
279
280
281
282
283
284
285
286
            user = get_object_or_404(PyrosUser, pk=pk)
            user.is_active = not user.is_active
            text_mail = ""
            text_object = ""
            if (user.first_time == False and user.is_active == True):
                user.first_time = True
                text_mail = "Hi,\n\nCongratulations, your registration has been approved by the PI. Welcome to the PyROS Control Center.\nIn order to submit observation sequences, you need to be associated to a scientific program.\n\nCordially,\n\nPyROS Control Center"
                text_object = "[PyROS CC] Welcome"
1ba49504   Alexis Koralewski   fixing CSS and JS...
287
288
289
290
                user.validator = get_object_or_404(
                    PyrosUser, pk=current_user_id)
                send_mail(text_object, text_mail, '', [
                          user.email], fail_silently=False,)
81d77f22   Alexis Koralewski   Adding 'forgotten...
291

1ba49504   Alexis Koralewski   fixing CSS and JS...
292
            # We're not sending an email if the account has been desactivated or re-activated
81d77f22   Alexis Koralewski   Adding 'forgotten...
293
294
295
296
297
298
            # elif (user.is_active == True):
            #     text_mail = "Hi,\n\nYour account on the PyROS Control Center have been re-activated.\n\nCordially,\n\nPyROS Control Center"
            #     text_object = "[PyROS CC] Re-activation"
            # else :
            #     text_mail = "Hi,\n\nYour account on the PyROS Control Center have benn desactivated. Please contact the PI for futher information.\n\nCordially,\n\nPyROS Control Center"
            #     text_object = "[PyROS CC] Desactivation"
1ba49504   Alexis Koralewski   fixing CSS and JS...
299

81d77f22   Alexis Koralewski   Adding 'forgotten...
300
            user.save()
1ba49504   Alexis Koralewski   fixing CSS and JS...
301

81d77f22   Alexis Koralewski   Adding 'forgotten...
302
303
304
305
            return redirect('user_detail', pk=pk)
        except PyrosUser.DoesNotExist:
            return redirect('user_detail', pk=pk)
    else:
1ba49504   Alexis Koralewski   fixing CSS and JS...
306
307
308
        return redirect("user_detail", pk=pk)


e419a2f6   Alexis Koralewski   Add new version f...
309
@login_required
a61943b5   Alexis Koralewski   Reworking Unit-bo...
310
# @level_required("Admin","Observer","Management","Operator","Unit-PI","TAC","Unit-board")
1ba49504   Alexis Koralewski   fixing CSS and JS...
311
def user_detail_view(request, pk):
e419a2f6   Alexis Koralewski   Add new version f...
312
313
    try:
        is_last_user = PyrosUser.objects.count() == 1
1ba49504   Alexis Koralewski   fixing CSS and JS...
314
        user = PyrosUser.objects.get(pk=pk)
e419a2f6   Alexis Koralewski   Add new version f...
315
316
        current_user = request.user
        roles = current_user.get_list_of_roles()
cc15cb36   Alexis Koralewski   improving user ac...
317
        sp_periods = SP_Period_User.objects.filter(user=user)
1ba49504   Alexis Koralewski   fixing CSS and JS...
318
319
320
321
322
323
324
325
326
327
        CAN_VIEW_VALIDATOR = request.user.id == pk or request.session.get(
            "role") in ("Admin", "Unit-PI", "Unit-board")
        CAN_DELETE_USER = not is_last_user and request.session.get("role") in (
            "Admin", "Unit-PI", "Unit-board") and not user.is_superuser and request.user != user
        CAN_ACTIVATE_USER = not is_last_user and request.session.get("role") in (
            "Admin", "Unit-PI", "Unit-board") and not user.is_superuser and request.user != user
        CAN_EDIT_USER = request.user.id == pk or request.session.get(
            "role") in ("Admin", "Unit-PI", "Unit-board")
        CAN_VIEW_MOTIVE_OF_REGISTRATION = request.session.get("role") in (
            "Admin", "Unit-PI", "Unit-board") and len(user.motive_of_registration) > 0
d8b6bc10   Alexis Koralewski   Add schema (Md fi...
328
        scientific_programs = user.get_scientific_programs()
e419a2f6   Alexis Koralewski   Add new version f...
329
330
    except PyrosUser.DoesNotExist:
        raise Http404("User does not exist")
b95a693f   Alexis Koralewski   restructuration d...
331
    return render(request, 'user_mgmt/user_detail.html', context={
1ba49504   Alexis Koralewski   fixing CSS and JS...
332
333
334
335
336
        'user': user,
        'current_user': current_user,
        'is_last_user': is_last_user,
        "roles": roles,
        "scientific_programs": scientific_programs,
cc15cb36   Alexis Koralewski   improving user ac...
337
338
339
        "CAN_VIEW_VALIDATOR": CAN_VIEW_VALIDATOR,
        "CAN_DELETE_USER": CAN_DELETE_USER,
        "CAN_ACTIVATE_USER": CAN_ACTIVATE_USER,
67a50452   Alexis Koralewski   Add variable to c...
340
        "CAN_EDIT_USER": CAN_EDIT_USER,
1ba49504   Alexis Koralewski   fixing CSS and JS...
341
        "CAN_VIEW_MOTIVE_OF_REGISTRATION": CAN_VIEW_MOTIVE_OF_REGISTRATION
cc15cb36   Alexis Koralewski   improving user ac...
342
    })
e419a2f6   Alexis Koralewski   Add new version f...
343

1ba49504   Alexis Koralewski   fixing CSS and JS...
344

e419a2f6   Alexis Koralewski   Add new version f...
345
346
@login_required
@level_required()
1ba49504   Alexis Koralewski   fixing CSS and JS...
347
def user_detail_edit(request, pk):
e419a2f6   Alexis Koralewski   Add new version f...
348
349
350
351
    if request.session.get("role"):
        role = request.session.get("role")
    else:
        role = request.user.get_priority()
a61943b5   Alexis Koralewski   Reworking Unit-bo...
352
353
    # If its not his user profile or user isn't Unit-PI, Unit-board, Admin or SP-PI, He can't edit this user profile and he is redirected to home page
    if (request.user.id != pk and role not in ("Admin", "Unit-PI", "Unit-board")):
e419a2f6   Alexis Koralewski   Add new version f...
354
355
        return HttpResponseRedirect(reverse('index'))
    edit = get_object_or_404(PyrosUser, pk=pk)
02d94ed3   Alexis Koralewski   Reworking UI of w...
356
    is_sp_pi = ScientificProgram.objects.filter(sp_pi=edit).count() > 0
e419a2f6   Alexis Koralewski   Add new version f...
357
    form = UserForm(request.POST or None, instance=edit)
1ba49504   Alexis Koralewski   fixing CSS and JS...
358
359
360
361
    CAN_EDIT_ROLE = request.session.get("role") in (
        "Admin", "Unit-PI", "Unit-board")
    CAN_EDIT_INSTITUTE = request.session.get(
        "role") in ("Admin", "Unit-PI", "Unit-board")
077d5a23   Alexis Koralewski   adding science th...
362
    CAN_EDIT_REFEREE_THEME = request.session.get("role") != "Visitor"
e419a2f6   Alexis Koralewski   Add new version f...
363
364
    # creating list of roles for the formular excluding visitor of the list
    roles = UserLevel.objects.exclude(name="Visitor")
077d5a23   Alexis Koralewski   adding science th...
365
    if request.POST and form.is_valid():
e419a2f6   Alexis Koralewski   Add new version f...
366
        obj = form.save(commit=False)
1ba49504   Alexis Koralewski   fixing CSS and JS...
367
        if(len(request.POST.getlist("roles")) > 0):
e419a2f6   Alexis Koralewski   Add new version f...
368
369
370
371
372
373
            if("Admin" in request.POST.getlist("roles")):
                # if Admin role has been assigned, add the authorisations to access to django admin pages
                obj.is_staff = True
                obj.is_admin = True
                obj.is_superuser = True
            else:
1ba49504   Alexis Koralewski   fixing CSS and JS...
374
                # just in case (for example, if user was previously an admin and has been downgraded) we're removing those authorisations
e419a2f6   Alexis Koralewski   Add new version f...
375
376
377
378
379
380
                obj.is_staff = False
                obj.is_admin = False
            obj.user_level.set(request.POST.getlist("roles"))
        else:
            # No role has been assigned, so the user has the Visitor role
            obj.user_level.set([UserLevel.objects.get(name="Visitor")])
1ba49504   Alexis Koralewski   fixing CSS and JS...
381
        if(len(request.POST.getlist("referee_themes")) > 0):
077d5a23   Alexis Koralewski   adding science th...
382
383
384
            obj.referee_themes.set(request.POST.getlist("referee_themes"))
        else:
            obj.referee_themes.set([])
e419a2f6   Alexis Koralewski   Add new version f...
385
        obj.save()
dc5e48b6   Alexis Koralewski   Fixing who can ed...
386
        if request.user == obj:
1ba49504   Alexis Koralewski   fixing CSS and JS...
387
388
            request.session["role"] = UserLevel.objects.get(
                priority=request.user.get_priority()).name
077d5a23   Alexis Koralewski   adding science th...
389

e419a2f6   Alexis Koralewski   Add new version f...
390
        return redirect('user_detail', pk=pk)
b95a693f   Alexis Koralewski   restructuration d...
391
    return render(request, 'user_mgmt/user_detail_edit.html', {
cc15cb36   Alexis Koralewski   improving user ac...
392
        'form': form,
1ba49504   Alexis Koralewski   fixing CSS and JS...
393
394
395
396
        "roles": roles,
        "pk": pk,
        "user_edit": edit,
        "is_sp_pi": is_sp_pi,
dc5e48b6   Alexis Koralewski   Fixing who can ed...
397
        "CAN_EDIT_ROLE": CAN_EDIT_ROLE,
077d5a23   Alexis Koralewski   adding science th...
398
399
        "CAN_EDIT_INSTITUTE": CAN_EDIT_INSTITUTE,
        "CAN_EDIT_REFEREE_THEME": CAN_EDIT_REFEREE_THEME
cc15cb36   Alexis Koralewski   improving user ac...
400
    })
e419a2f6   Alexis Koralewski   Add new version f...
401
402
403
404
405
406


def set_active_role(request):
    previous_active_role = request.session.get("role")
    if request.user.is_authenticated:
        if request.POST.get("role"):
1ba49504   Alexis Koralewski   fixing CSS and JS...
407
408
            request.session["role"] = str(
                UserLevel.objects.get(name=request.POST.get("role")))
e419a2f6   Alexis Koralewski   Add new version f...
409
            if(previous_active_role is not None and previous_active_role != request.session.get("role")):
1ba49504   Alexis Koralewski   fixing CSS and JS...
410
411
                messages.success(
                    request, f"Role changed from {previous_active_role} to {request.session.get('role')}")
02d94ed3   Alexis Koralewski   Reworking UI of w...
412
413
                text_reponse = f'<div class="alert alert-info alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>\
                Role changed from {previous_active_role} to {request.session.get("role")}</div>'
1ba49504   Alexis Koralewski   fixing CSS and JS...
414
                return HttpResponse(text_reponse)