Blame view

src/core/pyros_django/user_manager/views.py 17.5 KB
e419a2f6   Alexis Koralewski   Add new version f...
1
2
3
from django.shortcuts import render,redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
02d94ed3   Alexis Koralewski   Reworking UI of w...
4
from django.contrib import messages
e419a2f6   Alexis Koralewski   Add new version f...
5
6
7
from dashboard.decorator import level_required
from django.shortcuts import get_object_or_404
from dashboard.forms import UserForm
81d77f22   Alexis Koralewski   Adding 'forgotten...
8
from .forms import PyrosUserCreationForm,UserPasswordResetForm
e419a2f6   Alexis Koralewski   Add new version f...
9
10
11
12
from django.core.mail import send_mail
from common.models import ScientificProgram, PyrosUser,UserLevel, SP_Period, SP_Period_User
from django.urls import reverse
from django.http import HttpResponseRedirect,HttpResponse
81d77f22   Alexis Koralewski   Adding 'forgotten...
13
14
from obsconfig.configpyros import ConfigPyros
from django.conf import settings as pyros_settings
f7093a35   Alexis Koralewski   use environment v...
15
import os
41bdf9a6   Alexis Koralewski   Adding SP on user...
16
from src.pyros_logger import log
e419a2f6   Alexis Koralewski   Add new version f...
17
18
19
20
21
22
23
24
25

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

def home(request):
    '''
        Initial login view when coming on the website
    '''
    if request.user.is_authenticated:
        return(render(request, LOGGED_PAGE, {'USER_LEVEL': request.user.get_priority(), 'base_template' : "base.html", 'weather_img': "normal"}))
02d94ed3   Alexis Koralewski   Reworking UI of w...
26
    return(render(request, LOGGED_PAGE, {"USER_LEVEL" : "Visitor", 'base_template' : 'base.html', 'weather_img': "red"}))
e419a2f6   Alexis Koralewski   Add new version f...
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

def roles_description(request):
    return (render(request,"user_manager/roles_description.html"))
    
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()
    return (render(request, "user_manager/home_user_creation.html", locals()))

81d77f22   Alexis Koralewski   Adding 'forgotten...
42
43
44
def forgotten_password(request):
    form = UserPasswordResetForm()
    message=""
dc5e48b6   Alexis Koralewski   Fixing who can ed...
45
    user = None
81d77f22   Alexis Koralewski   Adding 'forgotten...
46
47
    if request.POST:
        password = PyrosUser.objects.make_random_password()
dc5e48b6   Alexis Koralewski   Fixing who can ed...
48
49
50
51
        try:
            user = PyrosUser.objects.get(email=request.POST["email"])
        except PyrosUser.DoesNotExist:
            message = "The email adress is invalid"
81d77f22   Alexis Koralewski   Adding 'forgotten...
52
53
54
55
56
        if user != None:
            user.set_password(password)
            user.save()
            send_mail(
                '[PyROS CC] Registration',
dc5e48b6   Alexis Koralewski   Fixing who can ed...
57
                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...
58
59
60
61
62
                '',
                [request.POST['email']],
                fail_silently=False,
            )
            message="The email has been send !"
dc5e48b6   Alexis Koralewski   Fixing who can ed...
63
64
        else:
            return render(request, 'user_manager/forgotten_password.html',{"form":form,"message":message})        
81d77f22   Alexis Koralewski   Adding 'forgotten...
65
66
    return render(request, 'user_manager/forgotten_password.html',{"form":form,"message":message})

e419a2f6   Alexis Koralewski   Add new version f...
67
68
69
70
71
72
73
74
75
76
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 ...
77
78
79
        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...
80
        else:
35daee3f   Alexis Koralewski   Add bot security ...
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
            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:
                        
                        if request.POST.get("next"):
                            return redirect(request.POST.get('next'))
                        else:
                            return redirect(reverse("users"))
                    else:
                        return(render(request, "user_manager/home_login.html", locals()))
                else:
                    message = "One or more fields contain errors. Please try again"
                    form_errors = form.errors
e419a2f6   Alexis Koralewski   Add new version f...
100
101
102
103
104
105
106
107
108
109
110
    else:
        message = "The system encountered an error. Please try again"

    error = True
    return (render(request, "user_manager/home_user_creation.html", locals()))

def login_validation(request):
    '''
        View called when the user log in (form submitted)
    '''
    if request.user.is_authenticated:
4290c2cf   Alexis Koralewski   adding unit choic...
111
        config = ConfigPyros(os.environ["PATH_TO_OBSCONF_FILE"],os.environ["unit_name"])
81d77f22   Alexis Koralewski   Adding 'forgotten...
112
113
114
        observatory_name = config.get_obs_name()
        first_unit_name = config.get_units_name()[0]
        request.session["obsname"] = observatory_name+" "+first_unit_name
e419a2f6   Alexis Koralewski   Add new version f...
115
116
117
118
119
        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
        request.session["role"] = str(UserLevel.objects.get(priority=request.user.get_priority()))
02d94ed3   Alexis Koralewski   Reworking UI of w...
120
        return redirect(reverse("index"))
e419a2f6   Alexis Koralewski   Add new version f...
121
122
123
124
    username = password = ''
    if request.POST:
        email = request.POST.get('email')
        password = request.POST.get('password')
81d77f22   Alexis Koralewski   Adding 'forgotten...
125
126
127
128
        try:
            is_user_active = PyrosUser.objects.get(username=email).is_active
        except:
            is_user_active = None
e419a2f6   Alexis Koralewski   Add new version f...
129
130
131
132
133
134
135
136
137
138
139
        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
                request.session["role"] = str(UserLevel.objects.get(priority=request.user.get_priority()))
41bdf9a6   Alexis Koralewski   Adding SP on user...
140
                log.info(f"User {user} did action login")
e419a2f6   Alexis Koralewski   Add new version f...
141
142
                if request.POST.get("next"):
                    return redirect(request.POST.get('next'))
02d94ed3   Alexis Koralewski   Reworking UI of w...
143
                return redirect(reverse("index"))
e419a2f6   Alexis Koralewski   Add new version f...
144
            else:
81d77f22   Alexis Koralewski   Adding 'forgotten...
145
                message = "Your account is not active, please contact the Unit-PI."
e419a2f6   Alexis Koralewski   Add new version f...
146
        else:
81d77f22   Alexis Koralewski   Adding 'forgotten...
147
148
149
150
151
            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."
            
e419a2f6   Alexis Koralewski   Add new version f...
152
153
154
155
156
    else:
        message = "An unexpected error has occurred"
    error = True
    return(render(request, "user_manager/home_login.html", locals()))

e419a2f6   Alexis Koralewski   Add new version f...
157
158
159
160
161
162
163
164
165
166
167
168

@login_required
def superoperator_return(request):
    current_user = request.user
    return(render(request, "user_manager/user_detail.html", {'user': current_user, 'admin': 0}))

@login_required
def user_logout(request):
    '''
        View called to log out. Redirects on login page.
    '''

41bdf9a6   Alexis Koralewski   Adding SP on user...
169
    log.info(f"User {request.user} did action logout")
e419a2f6   Alexis Koralewski   Add new version f...
170
    logout(request)
4290c2cf   Alexis Koralewski   adding unit choic...
171
    config = ConfigPyros(os.environ["PATH_TO_OBSCONF_FILE"],os.environ["unit_name"])
81d77f22   Alexis Koralewski   Adding 'forgotten...
172
173
174
    observatory_name = config.get_obs_name()
    first_unit_name = config.get_units_name()[0]
    request.session["obsname"] = observatory_name+" "+first_unit_name
02d94ed3   Alexis Koralewski   Reworking UI of w...
175
    return(render(request, LOGGED_PAGE, {'USER_LEVEL' :  "Visitor", 'base_template' : 'base.html', 'weather_img': "red"}))
e419a2f6   Alexis Koralewski   Add new version f...
176
177
178
179
180
181

def user_signin(request):
    return(render(request, "user_manager/home_login.html",{"next": request.GET.get("next")}))


@login_required
81d77f22   Alexis Koralewski   Adding 'forgotten...
182
@level_required("Admin","Unit-PI")
e419a2f6   Alexis Koralewski   Add new version f...
183
184
def delete_user(request,pk):
    user_to_be_deleted = get_object_or_404(PyrosUser,pk=pk)
81d77f22   Alexis Koralewski   Adding 'forgotten...
185
    if request.user != user_to_be_deleted and request.method == "POST":
e419a2f6   Alexis Koralewski   Add new version f...
186
187
        user_to_be_deleted.delete()
        return HttpResponseRedirect(reverse('users'))
81d77f22   Alexis Koralewski   Adding 'forgotten...
188
189
    else:
        return HttpResponseRedirect(reverse("user_detail",kwargs={"pk":pk}))
e419a2f6   Alexis Koralewski   Add new version f...
190
191
192
193
194
195
196


@login_required
@level_required("Admin","Observer","Management","Operator","Unit-PI","TAC","Unit board")
def users(request):
    current_user = request.user
    pyros_users_with_roles = []
dc5e48b6   Alexis Koralewski   Fixing who can ed...
197
    admin_and_unit_users = []
02d94ed3   Alexis Koralewski   Reworking UI of w...
198
    inactive_pyros_users = None
81d77f22   Alexis Koralewski   Adding 'forgotten...
199
    common_scientific_programs = None
e419a2f6   Alexis Koralewski   Add new version f...
200
201
202
203
    if request.session.get("role"):
        role = request.session.get("role")
    else:
        role = current_user.get_priority()
e419a2f6   Alexis Koralewski   Add new version f...
204
    if role in "Admin,Unit-PI,Unit board":
02d94ed3   Alexis Koralewski   Reworking UI of w...
205
206
        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...
207
208
    else:
        sp_of_current_user = SP_Period_User.objects.filter(user=current_user)
81d77f22   Alexis Koralewski   Adding 'forgotten...
209
        common_scientific_programs = sp_of_current_user
e419a2f6   Alexis Koralewski   Add new version f...
210
211
212
        for sp in sp_of_current_user:
            for user in SP_Period_User.objects.filter(SP_Period=sp.SP_Period).exclude(user=current_user).values_list("user",flat=True):
                pyros_users_with_roles.append(PyrosUser.objects.get(id=user))
dc5e48b6   Alexis Koralewski   Fixing who can ed...
213
214
            pyros_users_with_roles.append(sp.SP_Period.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...
215
    nb_of_scientific_program = ScientificProgram.objects.count()
cc15cb36   Alexis Koralewski   improving user ac...
216
    CAN_ADD_USER = request.session.get("role") in ("Admin,Unit-PI,Unit board")
e419a2f6   Alexis Koralewski   Add new version f...
217
218
    # need the negative to calculate in the template for adjusting correctly the information display
    negative_nb_scientific_program = -nb_of_scientific_program
cc15cb36   Alexis Koralewski   improving user ac...
219
220
221
222
223
224
    return render(request, 'user_manager/users_management.html', {
        'pyros_users_with_roles': pyros_users_with_roles,
        "inactive_pyros_users":inactive_pyros_users,
        "nb_of_scientific_program": nb_of_scientific_program,
        "negative_nb_scientific_program":negative_nb_scientific_program,
        "common_scientific_programs":common_scientific_programs,
dc5e48b6   Alexis Koralewski   Fixing who can ed...
225
        "admin_and_unit_users": admin_and_unit_users,
cc15cb36   Alexis Koralewski   improving user ac...
226
227
        "CAN_ADD_USER": CAN_ADD_USER
    })                     
e419a2f6   Alexis Koralewski   Add new version f...
228
229
230
231

@login_required
@level_required("Admin","Unit-PI","Unit board")
def change_activate(request, pk, current_user_id):
02d94ed3   Alexis Koralewski   Reworking UI of w...
232
233
234
235
236
237
    role = None
    if request.session.get("role") != None:
        role = request.session.get("role")
    else:
        role = UserLevel.objects.get(priority=request.user.get_priority()).name
    if role in ["Admin","Unit-PI","Unit board"]:
81d77f22   Alexis Koralewski   Adding 'forgotten...
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
        try :
            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"
                user.validator = get_object_or_404(PyrosUser,pk=current_user_id)
                send_mail(text_object, text_mail, '', [user.email], fail_silently=False,)

            # We're not sending an email if the account has been desactivated or re-activated 
            # 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"
            
            user.save()
            
            return redirect('user_detail', pk=pk)
        except PyrosUser.DoesNotExist:
            return redirect('user_detail', pk=pk)
    else:
        return redirect("user_detail",pk=pk)
e419a2f6   Alexis Koralewski   Add new version f...
265
@login_required
02d94ed3   Alexis Koralewski   Reworking UI of w...
266
#@level_required("Admin","Observer","Management","Operator","Unit-PI","TAC","Unit board")
e419a2f6   Alexis Koralewski   Add new version f...
267
268
269
def user_detail_view(request,pk):
    try:
        is_last_user = PyrosUser.objects.count() == 1
cc15cb36   Alexis Koralewski   improving user ac...
270
        user=PyrosUser.objects.get(pk=pk)
e419a2f6   Alexis Koralewski   Add new version f...
271
272
        current_user = request.user
        roles = current_user.get_list_of_roles()
cc15cb36   Alexis Koralewski   improving user ac...
273
274
        sp_periods = SP_Period_User.objects.filter(user=user)
        CAN_VIEW_VALIDATOR = request.user.id == pk or request.session.get("role") in ("Admin","Unit-PI","Unit-board")
dc5e48b6   Alexis Koralewski   Fixing who can ed...
275
276
        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
cc15cb36   Alexis Koralewski   improving user ac...
277
        CAN_EDIT_USER = request.user.id == pk or request.session.get("role") in ("Admin","Unit-PI","Unit-board")
67a50452   Alexis Koralewski   Add variable to c...
278
        CAN_VIEW_MOTIVE_OF_REGISTRATION =  request.session.get("role") in ("Admin","Unit-PI","Unit-board") and len(user.motive_of_registration) > 0 
41bdf9a6   Alexis Koralewski   Adding SP on user...
279
        scientific_programs = user.get_scientific_program()
e419a2f6   Alexis Koralewski   Add new version f...
280
281
    except PyrosUser.DoesNotExist:
        raise Http404("User does not exist")
cc15cb36   Alexis Koralewski   improving user ac...
282
283
284
285
286
287
288
289
290
    return render(request, 'user_manager/user_detail.html', context={
        'user' : user,
        'current_user' : current_user,
        'is_last_user' : is_last_user,
        "roles" : roles,
        "scientific_programs":scientific_programs,
        "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...
291
292
        "CAN_EDIT_USER": CAN_EDIT_USER,
        "CAN_VIEW_MOTIVE_OF_REGISTRATION":CAN_VIEW_MOTIVE_OF_REGISTRATION
cc15cb36   Alexis Koralewski   improving user ac...
293
    })
e419a2f6   Alexis Koralewski   Add new version f...
294
295
296
297
298
299
300
301
302
303
304
305

@login_required
@level_required()
def user_detail_edit(request,pk):
    if request.session.get("role"):
        role = request.session.get("role")
    else:
        role = request.user.get_priority()
    # 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") ):
        return HttpResponseRedirect(reverse('index'))
    edit = get_object_or_404(PyrosUser, pk=pk)
02d94ed3   Alexis Koralewski   Reworking UI of w...
306
    is_sp_pi = ScientificProgram.objects.filter(sp_pi=edit).count() > 0
e419a2f6   Alexis Koralewski   Add new version f...
307
    form = UserForm(request.POST or None, instance=edit)
cc15cb36   Alexis Koralewski   improving user ac...
308
    CAN_EDIT_ROLE = request.session.get("role") in ("Admin","Unit-PI","Unit-board")
dc5e48b6   Alexis Koralewski   Fixing who can ed...
309
    CAN_EDIT_INSTITUTE = request.session.get("role") in ("Admin","Unit-PI","Unit-board")
077d5a23   Alexis Koralewski   adding science th...
310
    CAN_EDIT_REFEREE_THEME = request.session.get("role") != "Visitor"
e419a2f6   Alexis Koralewski   Add new version f...
311
312
    # creating list of roles for the formular excluding visitor of the list
    roles = UserLevel.objects.exclude(name="Visitor")
077d5a23   Alexis Koralewski   adding science th...
313
    if request.POST and form.is_valid():
e419a2f6   Alexis Koralewski   Add new version f...
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
        obj = form.save(commit=False)
        if(len(request.POST.getlist("roles"))>0):
            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:
                # just in case (for example, if user was previously an admin and has been downgraded) we're removing those authorisations 
                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")])
077d5a23   Alexis Koralewski   adding science th...
329
330
331
332
        if(len(request.POST.getlist("referee_themes"))>0):
            obj.referee_themes.set(request.POST.getlist("referee_themes"))
        else:
            obj.referee_themes.set([])
e419a2f6   Alexis Koralewski   Add new version f...
333
        obj.save()
dc5e48b6   Alexis Koralewski   Fixing who can ed...
334
335
        if request.user == obj:
            request.session["role"] = UserLevel.objects.get(priority=request.user.get_priority()).name
077d5a23   Alexis Koralewski   adding science th...
336

e419a2f6   Alexis Koralewski   Add new version f...
337
        return redirect('user_detail', pk=pk)
cc15cb36   Alexis Koralewski   improving user ac...
338
339
340
341
342
343
    return render(request, 'user_manager/user_detail_edit.html', {
        'form': form,
        "roles":roles,
        "pk":pk,
        "user_edit":edit,
        "is_sp_pi":is_sp_pi,
dc5e48b6   Alexis Koralewski   Fixing who can ed...
344
        "CAN_EDIT_ROLE": CAN_EDIT_ROLE,
077d5a23   Alexis Koralewski   adding science th...
345
346
        "CAN_EDIT_INSTITUTE": CAN_EDIT_INSTITUTE,
        "CAN_EDIT_REFEREE_THEME": CAN_EDIT_REFEREE_THEME
cc15cb36   Alexis Koralewski   improving user ac...
347
    })
e419a2f6   Alexis Koralewski   Add new version f...
348
349
350
351
352
353
354
355


def set_active_role(request):
    previous_active_role = request.session.get("role")
    if request.user.is_authenticated:
        if request.POST.get("role"):
            request.session["role"] = str(UserLevel.objects.get(name=request.POST.get("role")))
            if(previous_active_role is not None and previous_active_role != request.session.get("role")):
02d94ed3   Alexis Koralewski   Reworking UI of w...
356
357
358
359
                messages.success(request,f"Role changed from {previous_active_role} to {request.session.get('role')}")
                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>'
                return HttpResponse(text_reponse)