aboutsummaryrefslogtreecommitdiffstats
path: root/accounts/views.py
blob: 145fa9ee42e7725122fa7b01a6cfcb86848d114a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
import datetime
from django.shortcuts import render
from django.urls import reverse
from django.conf import settings
from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm, SetPasswordForm, UserCreationForm
from django.contrib.auth.models import User
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.views import LoginView
from django.http import FileResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.debug import sensitive_variables
from django.http import HttpResponseRedirect
from django.core.exceptions import ValidationError

from client.models import UserCode, MedicalData

from authlib.integrations.django_client import OAuth

import json
import dateparser
import os
import requests
from random import randint
from io import BytesIO
from PIL import Image, UnidentifiedImageError
from pdf2image import convert_from_bytes
from pdf2image.exceptions import (
    PDFPageCountError,
    PDFSyntaxError
)

# suppress warning about dateparser deprecated dependencies
import warnings
warnings.filterwarnings(
    "ignore",
    message="The localize method is no longer necessary, as this time zone supports the fold attribute",
)

oauth = OAuth()
hitobito = oauth.register(name="hitobito")
api_url = settings.AUTHLIB_OAUTH_CLIENTS["hitobito"]["api_url"]
MIDATA_ENABLED = settings.OAUTH_ENABLED

# override to remove help text
class RegisterForm(UserCreationForm):
    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)

        for fieldname in ['username', 'password1', 'password2']:
            self.fields[fieldname].help_text = None

class AuthForm(AuthenticationForm):
    error_messages = {
        'invalid_login': ("Password errata e/o utente inesistente"),
        'inactive': ("Utente disattivato"),
        'midata_user': ("Utilizza il login con MiData collegato all'utente"),
    }
    def confirm_login_allowed(self, user):
        usercode = UserCode.objects.filter(user=user)

        if len(usercode) > 0:
            if usercode[0].midata_id > 0:
                raise ValidationError(
                    self.error_messages['midata_user'],
                    code='midata_user',
                )

        if not user.is_active:
            raise ValidationError(
                self.error_messages['inactive'],
                code='inactive',
            )

# request data from user account
def get_oauth_data(token):
    headers = {
        "Authorization" : "Bearer " + token,
        "X-Scope": "with_roles",
    }

    return requests.get(api_url, headers=headers)

def copy_from_midata(request, usercode):
    resp = get_oauth_data(usercode.midata_token)

    if resp.status_code != 200:
        logout(request)
        return False

    resp_data = resp.json()

    request.user.first_name = resp_data["first_name"]
    request.user.last_name = resp_data["last_name"]
    request.user.email = resp_data["email"]
    request.user.save()

    usercode.via = resp_data["address"]
    usercode.cap = resp_data["zip_code"]
    usercode.country = resp_data["town"]
    usercode.born_date = dateparser.parse(resp_data["birthday"])
    usercode.save()

    return True

### Views ###

class CustomLoginView(LoginView):
    form_class = AuthForm
    extra_context = {'midata_enabled': MIDATA_ENABLED}

    def get(self, request, *args, **kwargs):
        # check auto-login is enabled
        if "autologin" not in request.COOKIES:
            return super(CustomLoginView, self).get(request, *args, **kwargs)

        if request.COOKIES.get("autologin") != "true":
            return super(CustomLoginView, self).get(request, *args, **kwargs)

        # check if user has a cookie saved
        response = HttpResponseRedirect("/")

        # no cookie
        if "user_switcher" not in request.COOKIES:
            return super(CustomLoginView, self).get(request, *args, **kwargs)

        sessions = json.loads(request.COOKIES.get("user_switcher"))

        # empty cookie
        if len(sessions) == 0: 
            return super(CustomLoginView, self).get(request, *args, **kwargs)

        # pick the first username to login to
        username = list(sessions.keys())[0]

        set_session_cookie(response, sessions[username][0], sessions[username][1])
        del sessions[username]

        set_switch_cookie(response, sessions)

        # disable autologin
        response.set_cookie("autologin", "false")

        return response

# send to hitobito request to get token
def oauth_login(request):
    if not MIDATA_ENABLED:
        return None

    redirect_uri = request.build_absolute_uri(reverse('auth'))

    # forward next page requested by user
    if not request.GET["next"]:
        redirect_uri += "?next=/"
    else:
        redirect_uri += "?next=" + request.GET["next"]

    return hitobito.authorize_redirect(request, redirect_uri)

# callback after acquiring token
def auth(request):
    if not MIDATA_ENABLED:
        return None

    token = hitobito.authorize_access_token(request)

    # request data from user account
    resp_data = get_oauth_data(token["access_token"]).json()

    # find user with that id
    usercode = UserCode.objects.filter(midata_id=resp_data["id"])
    
    if len(usercode) > 0:
        # user exist
        login(request, usercode[0].user)

        usercode[0].midata_token = token["access_token"]
        usercode[0].save()

        copy_from_midata(request, usercode[0])

        return HttpResponseRedirect(request.GET["next"])

    # create new user
    user = User.objects.create_user(resp_data["email"], resp_data["email"])

    # create new usercode
    while (True):
        code = randint(100000, 999999)
        if len(UserCode.objects.filter(code=code)) == 0:
            break

    medic = MedicalData()
    medic.save()
    usercode = UserCode(user=user, code=code, medic=medic, midata_id=resp_data["id"], midata_token=token["access_token"])

    login(request, user)

    copy_from_midata(request, usercode)

    return HttpResponseRedirect(request.GET["next"])

# send to hitobito request to get token
@login_required
def oauth_connect(request):
    if not MIDATA_ENABLED:
        return None

    redirect_uri = request.build_absolute_uri(reverse('auth_connect'))
    return hitobito.authorize_redirect(request, redirect_uri)

# clear token only if user has another way to login
@login_required
def oauth_disconnect(request):
    if not request.user.has_usable_password():
        return personal_wrapper(request, ["Il tuo utente non ha una password impostata, impostare una password prima di scollegarlo da MiData"])

    usercode = UserCode.objects.filter(user=request.user)[0]
    usercode.midata_id = 0
    usercode.midata_token = ""
    usercode.save()

    return HttpResponseRedirect(reverse("personal") + "#settings")

# callback after acquiring token
@login_required
def auth_connect(request):
    if not MIDATA_ENABLED:
        return None

    token = hitobito.authorize_access_token(request)

    # request data from user account
    resp_data = get_oauth_data(token["access_token"]).json()

    # check that account is not linked to another
    existing_codes = UserCode.objects.filter(midata_id=resp_data["id"])
    if len(existing_codes) > 0:
        return personal_wrapper(request, ["Questo utente è già collegato ad un altro"])

    # save id to user
    usercode = UserCode.objects.filter(user=request.user)[0]
    usercode.midata_id = resp_data["id"]
    usercode.midata_token = token["access_token"]
    usercode.save()

    return HttpResponseRedirect(reverse("personal") + "#settings")

@sensitive_variables("sessionid")
def set_session_cookie(response, sessionid, expires):
    expires_date = datetime.datetime.fromtimestamp(int(expires))
    max_age = (expires_date - datetime.datetime.utcnow()).total_seconds()
    response.set_cookie(
        "sessionid",
        sessionid,
        max_age=max_age,
        expires=expires,
        domain=settings.SESSION_COOKIE_DOMAIN,
        secure=settings.SESSION_COOKIE_SECURE,
        httponly=settings.SESSION_COOKIE_HTTPONLY,
        samesite=settings.SESSION_COOKIE_SAMESITE,
    )

@sensitive_variables("data")
def set_switch_cookie(response, data):

    max_age = 30 * 60 * 60 * 24
    expires = datetime.datetime.strftime(
        datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age),
        "%a, %d-%b-%Y %H:%M:%S GMT",
    )
    response.set_cookie(
        "user_switcher",
        json.dumps(data),
        max_age=max_age,
        expires=expires,
        domain=settings.SESSION_COOKIE_DOMAIN,
        secure=settings.SESSION_COOKIE_SECURE,
        httponly=settings.SESSION_COOKIE_HTTPONLY,
        samesite=settings.SESSION_COOKIE_SAMESITE,
    )

@sensitive_variables("sessions")
def user_switcher(request):
    if request.method == 'POST':
        if request.POST["metadata"] == 'new':
            response = HttpResponseRedirect('/accounts/login')

            sessions = dict()
            if "user_switcher" in request.COOKIES:
                sessions = json.loads(request.COOKIES.get("user_switcher"))

            sessions[request.user.username] = (request.session.session_key, request.session.get_expiry_date().timestamp())
            set_switch_cookie(response, sessions)

            response.set_cookie("sessionid", "")
            response.set_cookie("autologin", "false")

            return response

        elif request.POST["metadata"][0] == 's':
            response = HttpResponseRedirect("/")
            username = request.POST["metadata"][1:]

            sessions = dict()
            if "user_switcher" in request.COOKIES:
                sessions = json.loads(request.COOKIES.get("user_switcher"))

            sessions[request.user.username] = (request.session.session_key, request.session.get_expiry_date().timestamp())

            if username in sessions:
                set_session_cookie(response, sessions[username][0], sessions[username][1])
                del sessions[username]
            else:
                set_session_cookie(response, "", 0)

            set_switch_cookie(response, sessions)

            response.set_cookie("autologin", "false")

            return response
        elif request.POST["metadata"] == "logout":
            # send user to logout page
            # on the login page we check if we have a cookie set
            response = HttpResponseRedirect("/accounts/logout")
            response.set_cookie("autologin", "true")

            return response

    
    return HttpResponseRedirect("/")

@sensitive_variables("raw_passsword")
def signup(request):
    out_errors = []
    # signup form with terms
    if request.method == 'POST':
        # get form object
        form = RegisterForm(request.POST)

        # check if terms are accepted
        if "terms_accept" not in request.POST:
            out_errors.append("Accettare i termini e condizioni prego")

        # if form is valid and terms were accepted save user
        if form.is_valid() and len(out_errors) == 0:
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return HttpResponseRedirect('/')
        else:
            # get errors from form and add toasts
            errors = form.errors.as_data()
            errors_list = [x for xs in errors.values() for x in xs]
            errors_text = list(map(lambda x: x.message, errors_list))
            out_errors += errors_text

    else:
        # create empty form to be filled
        form = RegisterForm()

    context = {
        "form": form,
        "errors": out_errors,
    }
    return render(request, 'accounts/signup.html', context)

# create wrapper to send custom error from other views (oauth connect/disconnect)
@login_required
def personal(request):
    return personal_wrapper(request, [])

@login_required
def personal_wrapper(request, errors):
    context = {}
    ok_message = ""
    personal_active = "active"
    medic_active = ""
    settings_active = ""
    # additional user information
    usercode = UserCode.objects.filter(user=request.user)[0]
    # medical info
    medic = usercode.medic
    # values for multiple choice box
    # TODO remove multiple choice
    branca_default = ""
    branca_castorini = ""
    branca_lupetti = ""
    branca_esploratori = ""
    branca_pionieri = ""
    branca_rover = ""

    # variables for validation
    validation_dic = {}
    required_fields = ["first_name", "last_name", "email", "parent_name", "via", "cap", "country", "nationality", "phone", "avs_number", "emer_name", "emer_relative", "cell_phone", "address", "health_care", "injuries", "rc", "medic_name", "medic_phone", "medic_address"]
    personal_fields = ["first_name", "last_name", "email", "parent_name", "via", "cap", "country", "nationality", "phone", "avs_number"]
    medic_fields = ["emer_name", "emer_relative", "cell_phone", "address", "health_care", "injuries", "rc", "medic_name", "medic_phone", "medic_address"]

    if request.method == "POST":
        # requested download
        if request.POST['action'] == "download_vac":
            if medic.vac_certificate != None:
                filename = os.path.basename(medic.vac_certificate.name)
                filename = filename[filename.find("_")+1:]
                if filename.rfind('.') != -1:
                    filename = filename[:filename.rfind('.')]
                filename = filename + ".jpg"

                # encode in JPEG
                im = Image.open(medic.vac_certificate.file)
                im_io = BytesIO()
                im.save(im_io, 'JPEG', quality=90)
                im_io.seek(0)
                return FileResponse(im_io, as_attachment=True, filename=filename)

        elif request.POST['action'] == "download_health":
            if medic.health_care_certificate != None:
                filename = os.path.basename(medic.health_care_certificate.name)
                filename = filename[filename.find("_")+1:]
                if filename.rfind('.') != -1:
                    filename = filename[:filename.rfind('.')]
                filename = filename + ".jpg"

                # encode in JPEG
                im = Image.open(medic.health_care_certificate.file)
                im_io = BytesIO()
                im.save(im_io, 'JPEG', quality=90)
                im_io.seek(0)
                return FileResponse(im_io, as_attachment=True, filename=filename)

        elif request.POST['action'] == "password":
            # get form object
            if request.user.has_usable_password():
                form2 = PasswordChangeForm(data=request.POST, user=request.user)
            else:
                form2 = SetPasswordForm(data=request.POST, user=request.user)

            # if form is valid and terms were accepted save user
            if form2.is_valid():
                form2.save()
                ok_message = "Password modificata con successo"
                personal_active = ""
                settings_active = "active"
            else:
                personal_active = ""
                settings_active = "active"
                for field in form2.errors.as_data().values():
                    for err in field:
                        if err.code == "password_mismatch":
                            errors.append("Le due password non sono uguali")
                        elif err.code == "password_too_similar":
                            errors.append("La password è troppo simile all'username")
                        elif err.code == "password_too_short":
                            errors.append("La password è troppo corta")
                        elif err.code == "password_too_common":
                            errors.append("La password è troppo comune")
                        elif err.code == "password_entirely_numeric":
                            errors.append("La password deve contenere lettere")
                        elif err.code == "password_incorrect":
                            errors.append("La password attuale è incorretta")

        else:
            # set all attributes
            request.user.first_name = request.POST["first_name"]
            request.user.last_name = request.POST["last_name"]
            request.user.email = request.POST["email"]
            request.user.save()
            usercode.parent_name = request.POST["parent_name"]
            usercode.via = request.POST["via"]
            usercode.cap = request.POST["cap"]
            usercode.country = request.POST["country"]
            usercode.nationality = request.POST["nationality"]
            usercode.born_date = dateparser.parse(request.POST["birth_date"])
            usercode.home_phone = request.POST["home_phone"]
            usercode.phone = request.POST["phone"]
            usercode.school = request.POST["school"]
            usercode.avs_number = request.POST["avs_number"]

            if request.POST["year"].isdigit():
                usercode.year = request.POST["year"]
            else:
                errors.append("L'anno scolastico deve essere un numero")

            usercode.save()

            medic.emer_name = request.POST["emer_name"]
            medic.emer_relative = request.POST["emer_relative"]
            medic.cell_phone = request.POST["cell_phone"]
            medic.address = request.POST["address"]
            medic.emer_phone = request.POST["emer_phone"]
            medic.health_care = request.POST["health_care"]
            medic.injuries = request.POST["injuries"]
            medic.rc = request.POST["rc"]
            medic.rega = "rega" in request.POST
            medic.medic_name = request.POST["medic_name"]
            medic.medic_phone = request.POST["medic_phone"]
            medic.medic_address = request.POST["medic_address"]
            medic.sickness = request.POST["sickness"]
            medic.vaccine = request.POST["vaccine"]
            medic.tetanus_date = dateparser.parse(request.POST["tetanus_date"])
            medic.allergy = request.POST["allergy"]
            medic.drugs_bool = "drugs_bool" in request.POST
            medic.drugs = request.POST["drugs"]
            medic.misc_bool = "misc_bool" in request.POST
            medic.misc = request.POST["misc"]
            medic.save()

            missing_fields = False
            missing_personal_field = False

            if request.POST["birth_date"] == "" or request.POST["birth_date"] == "01 Gennaio 1970" or request.POST["birth_date"] == "None":
                validation_dic["birth_date"] = 'class="datepicker validate invalid" required="" aria-required="true"'
                missing_fields = True
                missing_personal_field = True
            else:
                validation_dic["birth_date"] = 'class="datepicker validate" required="" aria-required="true"'

            for i in required_fields:
                if request.POST[i] == "":
                    missing_fields = True
                    if i in personal_fields:
                        missing_personal_field = True
                    validation_dic[i] = 'class="validate invalid" required="" aria-required="true"'
                else:
                    validation_dic[i] = 'class="validate" required="" aria-required="true"'

            if missing_fields:
                errors.append("Alcuni campi richiesti non sono stati compilati")
                if not missing_personal_field:
                    personal_active = ""
                    medic_active = "active"

            # if "branca" in request.POST:
            #    if request.POST["branca"] != "":
            #        request.user.groups.clear()
            #        request.user.groups.add(
            #            Group.objects.get(name=request.POST["branca"]))

            # check if user uploaded a file
            if "vac_certificate" in request.FILES:
                files = request.FILES.getlist('vac_certificate')
                name = files[0].name
                try:
                    # if multiple files concatenate pictures
                    im = Image.new("RGB", (0, 0), (255, 255, 255))
                    for f in files:
                        if f.name.endswith(".pdf") or f.name.endswith(".PDF"):
                            images = convert_from_bytes(f.read())
                            for i in images:
                                dst = Image.new('RGB', (max(im.width, i.width), im.height + i.height), (255, 255, 255))
                                dst.paste(im, (0, 0))
                                dst.paste(i, (0, im.height))
                                im = dst
                        else:
                            i = Image.open(f)
                            dst = Image.new('RGB', (max(im.width, i.width), im.height + i.height), (255, 255, 255))
                            dst.paste(im, (0, 0))
                            dst.paste(i, (0, im.height))
                            im = dst

                    im_io = BytesIO()
                    # resize image if larger than max value
                    if im.height > 16383:
                        im = im.resize((round(im.width/im.height*16383), 16383))
                    # compress image in WEBP
                    im.save(im_io, 'WEBP', quality=50, method=4)
                    medic.vac_certificate.save(
                        request.user.username+"_"+name, im_io)
                    medic.save()
                except UnidentifiedImageError:
                    errors.append("Il certificato delle vaccinazioni non è un immagine valida")
                except PDFPageCountError:
                    errors.append("Il certificato delle vaccinazioni non è un pdf valido")
                except PDFSyntaxError:
                    errors.append("Il certificato delle vaccinazioni non è un pdf valido")
                except IOError:
                    errors.append("Il certificato delle vaccinazioni è un immagine troppo grande")

            if "health_care_certificate" in request.FILES:
                files = request.FILES.getlist('health_care_certificate')
                name = files[0].name
                try:
                    # if multiple files concatenate pictures
                    im = Image.new("RGB", (0, 0), (255, 255, 255))
                    for f in files:
                        if f.name.endswith(".pdf") or f.name.endswith(".PDF"):
                            images = convert_from_bytes(f.read())
                            for i in images:
                                dst = Image.new('RGB', (max(im.width, i.width), im.height + i.height), (255, 255, 255))
                                dst.paste(im, (0, 0))
                                dst.paste(i, (0, im.height))
                                im = dst
                        else:
                            i = Image.open(f)
                            dst = Image.new('RGB', (max(im.width, i.width), im.height + i.height), (255, 255, 255))
                            dst.paste(im, (0, 0))
                            dst.paste(i, (0, im.height))
                            im = dst

                    im_io = BytesIO()
                    # resize image if larger than max value
                    if im.height > 16383:
                        im = im.resize((round(im.width/im.height*16383), 16383))
                    # compress image in WEBP
                    im.save(im_io, 'WEBP', quality=50, method=4)
                    medic.health_care_certificate.save(
                        request.user.username+"_"+name, im_io)
                    medic.save()
                except UnidentifiedImageError:
                    errors.append("La tessera della cassa malati non è un immagine valida")
                except PDFPageCountError:
                    errors.append("La tessera della cassa malati non è un pdf valido")
                except PDFSyntaxError:
                    errors.append("La tessera della cassa malati non è un pdf valido")
                except IOError:
                    errors.append("La tessera della cassa malati è un immagine troppo grande")

            # user requested file delete
            if request.POST["delete_vac"] == 'vac':
                medic.vac_certificate = None
                medic.save()

            if request.POST["delete_health"] == 'health':
                medic.health_care_certificate = None
                medic.save()

            # if there wasn't any error redirect to clear POST
            if len(errors) == 0:
                return HttpResponseRedirect(request.get_full_path())

    else:
        # no post, create empty validation
        validation_dic["birth_date"] = 'class="datepicker validate" required="" aria-required="true"'
        for i in required_fields:
            validation_dic[i] = 'class="validate" required="" aria-required="true"'

    # check if user is in a group and set multiple choice to that
    if len(request.user.groups.values_list('name', flat=True)) == 0:
        branca_default = "selected"
    else:
        parent_group = request.user.groups.values_list('name', flat=True)[0]
        if parent_group == "diga":
            branca_castorini = "selected"
        elif parent_group == "muta":
            branca_lupetti = "selected"
        elif parent_group == "reparto":
            branca_esploratori = "selected"
        elif parent_group == "posto":
            branca_pionieri = "selected"
        elif parent_group == "clan":
            branca_rover = "selected"
        else:
            branca_default = "selected"

    # set checkbox status
    rega = ""
    if medic.rega:
        rega = "checked='checked'"
    drugs = ""
    if medic.drugs_bool:
        drugs = "checked='checked'"
    misc = ""
    if medic.misc_bool:
        misc = "checked='checked'"

    # set file name for uploaded files
    if (medic.vac_certificate != None):
        vac_name = os.path.basename(medic.vac_certificate.name)
        vac_name = vac_name[vac_name.find("_")+1:]
    else:
        vac_name = ''

    if (medic.health_care_certificate != None):
        card_name = os.path.basename(medic.health_care_certificate.name)
        card_name = card_name[card_name.find("_")+1:]
    else:
        card_name = ''

    # check if user is connected with midata
    midata_user = (usercode.midata_id > 0)
    midata_disable = ""

    # get user info from midata
    if midata_user:
        midata_disable = " readonly disabled"
        if not copy_from_midata(request, usercode):
            return HttpResponseRedirect(request.get_full_path())

    usable_password = request.user.has_usable_password()

    # check if user has saved the form
    home_tooltip = False
    if "saved" in request.GET:
        # show tooltip only if user is not approved and there are no errors
        home_tooltip = (not request.user.has_perm("client.approved")) and (len(errors) == 0)

    # fill context
    context = {
        'validation_dic': validation_dic,
        'first_name': request.user.first_name,
        'last_name': request.user.last_name,
        'email': request.user.email,
        'parent_name': usercode.parent_name,
        'via': usercode.via,
        'cap': usercode.cap,
        'country': usercode.country,
        'nationality': usercode.nationality,
        'birth_date': usercode.born_date,
        'home_phone': usercode.home_phone,
        'phone': usercode.phone,
        'school': usercode.school,
        'year': usercode.year,
        'avs_number': usercode.avs_number,
        'branca_default': branca_default,
        'branca_castorini': branca_castorini,
        'branca_lupetti': branca_lupetti,
        'branca_esploratori': branca_esploratori,
        'branca_pionieri': branca_pionieri,
        'branca_rover': branca_rover,
        'emer_name': medic.emer_name,
        'emer_relative': medic.emer_relative,
        'cell_phone': medic.cell_phone,
        'address': medic.address,
        'emer_phone': medic.emer_phone,
        'health_care': medic.health_care,
        'injuries': medic.injuries,
        'rc': medic.rc,
        'rega_check': rega,
        'medic_name': medic.medic_name,
        'medic_phone': medic.medic_phone,
        'medic_address': medic.medic_address,
        'sickness': medic.sickness,
        'vaccine': medic.vaccine,
        'tetanus_date': medic.tetanus_date,
        'allergy': medic.allergy,
        'drugs_check': drugs,
        'drugs': medic.drugs,
        'misc_check': misc,
        'misc': medic.misc,
        'health_care_certificate': card_name,
        'vac_certificate': vac_name,
        'errors': errors,
        'ok_message': ok_message,
        'midata_user': midata_user,
        'midata_disable': midata_disable,
        'usable_password': usable_password,
        'personal_active': personal_active,
        'medic_active': medic_active,
        'settings_active': settings_active,
        'midata_enabled': MIDATA_ENABLED,
        'home_tooltip': home_tooltip,
    }

    return render(request, 'accounts/index.html', context)

@login_required
def edit(request, code):
    errors = []
    context = {}
    ok_message = ""
    personal_active = "active"
    medic_active = ""
    settings_active = ""
    # additional user information
    if (code == 0):
        # generate code
        while (True):
            code = randint(100000, 999999)
            if len(UserCode.objects.filter(code=code)) == 0:
                break
        medic = MedicalData()
        medic.save()
        userCode = UserCode(user=request.user, code=code, medic=medic)
        userCode.save()

    usercode = UserCode.objects.filter(user=request.user, code=code)

    if (len(usercode) == 0):
        # code is not authorised for this user
        return

    usercode = usercode[0]
        
    # medical info
    medic = usercode.medic
    # values for multiple choice box
    # TODO remove multiple choice
    branca_default = ""
    branca_castorini = ""
    branca_lupetti = ""
    branca_esploratori = ""
    branca_pionieri = ""
    branca_rover = ""

    # variables for validation
    validation_dic = {}
    required_fields = ["first_name", "last_name", "parent_name", "via", "cap", "country", "nationality", "phone", "avs_number", "emer_name", "emer_relative", "cell_phone", "address", "health_care", "injuries", "rc", "medic_name", "medic_phone", "medic_address"]
    personal_fields = ["first_name", "last_name", "parent_name", "via", "cap", "country", "nationality", "phone", "avs_number"]
    medic_fields = ["emer_name", "emer_relative", "cell_phone", "address", "health_care", "injuries", "rc", "medic_name", "medic_phone", "medic_address"]

    if request.method == "POST":
        # requested download
        if request.POST['action'] == "download_vac":
            if medic.vac_certificate != None:
                filename = os.path.basename(medic.vac_certificate.name)
                filename = filename[filename.find("_")+1:]
                if filename.rfind('.') != -1:
                    filename = filename[:filename.rfind('.')]
                filename = filename + ".jpg"

                # encode in JPEG
                im = Image.open(medic.vac_certificate.file)
                im_io = BytesIO()
                im.save(im_io, 'JPEG', quality=90)
                im_io.seek(0)
                return FileResponse(im_io, as_attachment=True, filename=filename)

        elif request.POST['action'] == "download_health":
            if medic.health_care_certificate != None:
                filename = os.path.basename(medic.health_care_certificate.name)
                filename = filename[filename.find("_")+1:]
                if filename.rfind('.') != -1:
                    filename = filename[:filename.rfind('.')]
                filename = filename + ".jpg"

                # encode in JPEG
                im = Image.open(medic.health_care_certificate.file)
                im_io = BytesIO()
                im.save(im_io, 'JPEG', quality=90)
                im_io.seek(0)
                return FileResponse(im_io, as_attachment=True, filename=filename)

        elif request.POST['action'] == "password":
            # get form object
            if request.user.has_usable_password():
                form2 = PasswordChangeForm(data=request.POST, user=request.user)
            else:
                form2 = SetPasswordForm(data=request.POST, user=request.user)

            # if form is valid and terms were accepted save user
            if form2.is_valid():
                form2.save()
                ok_message = "Password modificata con successo"
                personal_active = ""
                settings_active = "active"
            else:
                personal_active = ""
                settings_active = "active"
                for field in form2.errors.as_data().values():
                    for err in field:
                        if err.code == "password_mismatch":
                            errors.append("Le due password non sono uguali")
                        elif err.code == "password_too_similar":
                            errors.append("La password è troppo simile all'username")
                        elif err.code == "password_too_short":
                            errors.append("La password è troppo corta")
                        elif err.code == "password_too_common":
                            errors.append("La password è troppo comune")
                        elif err.code == "password_entirely_numeric":
                            errors.append("La password deve contenere lettere")
                        elif err.code == "password_incorrect":
                            errors.append("La password attuale è incorretta")

        elif request.POST['action'] == "delete_uc":
            confirm_name = request.POST['del_name']
            correct_name = usercode.first_name + " " + usercode.last_name
            if (confirm_name == correct_name):
                usercode.delete()
                medic.delete()
                return HttpResponseRedirect("/")

            errors.append("Il nome inserito non corrisponde al nome salvato")

        else:
            # set all attributes
            usercode.first_name = request.POST["first_name"]
            usercode.last_name = request.POST["last_name"]
            usercode.parent_name = request.POST["parent_name"]
            usercode.via = request.POST["via"]
            usercode.cap = request.POST["cap"]
            usercode.country = request.POST["country"]
            usercode.nationality = request.POST["nationality"]
            usercode.born_date = dateparser.parse(request.POST["birth_date"])
            usercode.home_phone = request.POST["home_phone"]
            usercode.phone = request.POST["phone"]
            usercode.school = request.POST["school"]
            usercode.avs_number = request.POST["avs_number"]

            if request.POST["year"].isdigit():
                usercode.year = request.POST["year"]
            else:
                errors.append("L'anno scolastico deve essere un numero")

            usercode.save()

            medic.emer_name = request.POST["emer_name"]
            medic.emer_relative = request.POST["emer_relative"]
            medic.cell_phone = request.POST["cell_phone"]
            medic.address = request.POST["address"]
            medic.emer_phone = request.POST["emer_phone"]
            medic.health_care = request.POST["health_care"]
            medic.injuries = request.POST["injuries"]
            medic.rc = request.POST["rc"]
            medic.rega = "rega" in request.POST
            medic.medic_name = request.POST["medic_name"]
            medic.medic_phone = request.POST["medic_phone"]
            medic.medic_address = request.POST["medic_address"]
            medic.sickness = request.POST["sickness"]
            medic.vaccine = request.POST["vaccine"]
            medic.tetanus_date = dateparser.parse(request.POST["tetanus_date"])
            medic.allergy = request.POST["allergy"]
            medic.drugs_bool = "drugs_bool" in request.POST
            medic.drugs = request.POST["drugs"]
            medic.misc_bool = "misc_bool" in request.POST
            medic.misc = request.POST["misc"]
            medic.save()

            missing_fields = False
            missing_personal_field = False

            if request.POST["birth_date"] == "" or request.POST["birth_date"] == "01 Gennaio 1970" or request.POST["birth_date"] == "None":
                validation_dic["birth_date"] = 'class="datepicker validate invalid" required="" aria-required="true"'
                missing_fields = True
                missing_personal_field = True
            else:
                validation_dic["birth_date"] = 'class="datepicker validate" required="" aria-required="true"'

            for i in required_fields:
                if request.POST[i] == "":
                    missing_fields = True
                    if i in personal_fields:
                        missing_personal_field = True
                    validation_dic[i] = 'class="validate invalid" required="" aria-required="true"'
                else:
                    validation_dic[i] = 'class="validate" required="" aria-required="true"'

            if missing_fields:
                errors.append("Alcuni campi richiesti non sono stati compilati")
                if not missing_personal_field:
                    personal_active = ""
                    medic_active = "active"

            # if "branca" in request.POST:
            #    if request.POST["branca"] != "":
            #        request.user.groups.clear()
            #        request.user.groups.add(
            #            Group.objects.get(name=request.POST["branca"]))

            # check if user uploaded a file
            if "vac_certificate" in request.FILES:
                files = request.FILES.getlist('vac_certificate')
                name = files[0].name
                try:
                    # if multiple files concatenate pictures
                    im = Image.new("RGB", (0, 0), (255, 255, 255))
                    for f in files:
                        if f.name.endswith(".pdf") or f.name.endswith(".PDF"):
                            images = convert_from_bytes(f.read())
                            for i in images:
                                dst = Image.new('RGB', (max(im.width, i.width), im.height + i.height), (255, 255, 255))
                                dst.paste(im, (0, 0))
                                dst.paste(i, (0, im.height))
                                im = dst
                        else:
                            i = Image.open(f)
                            dst = Image.new('RGB', (max(im.width, i.width), im.height + i.height), (255, 255, 255))
                            dst.paste(im, (0, 0))
                            dst.paste(i, (0, im.height))
                            im = dst

                    im_io = BytesIO()
                    # resize image if larger than max value
                    if im.height > 16383:
                        im = im.resize((round(im.width/im.height*16383), 16383))
                    # compress image in WEBP
                    im.save(im_io, 'WEBP', quality=50, method=4)
                    medic.vac_certificate.save(
                        request.user.username+"_"+name, im_io)
                    medic.save()
                except UnidentifiedImageError:
                    errors.append("Il certificato delle vaccinazioni non è un immagine valida")
                except PDFPageCountError:
                    errors.append("Il certificato delle vaccinazioni non è un pdf valido")
                except PDFSyntaxError:
                    errors.append("Il certificato delle vaccinazioni non è un pdf valido")
                except IOError:
                    errors.append("Il certificato delle vaccinazioni è un immagine troppo grande")

            if "health_care_certificate" in request.FILES:
                files = request.FILES.getlist('health_care_certificate')
                name = files[0].name
                try:
                    # if multiple files concatenate pictures
                    im = Image.new("RGB", (0, 0), (255, 255, 255))
                    for f in files:
                        if f.name.endswith(".pdf") or f.name.endswith(".PDF"):
                            images = convert_from_bytes(f.read())
                            for i in images:
                                dst = Image.new('RGB', (max(im.width, i.width), im.height + i.height), (255, 255, 255))
                                dst.paste(im, (0, 0))
                                dst.paste(i, (0, im.height))
                                im = dst
                        else:
                            i = Image.open(f)
                            dst = Image.new('RGB', (max(im.width, i.width), im.height + i.height), (255, 255, 255))
                            dst.paste(im, (0, 0))
                            dst.paste(i, (0, im.height))
                            im = dst

                    im_io = BytesIO()
                    # resize image if larger than max value
                    if im.height > 16383:
                        im = im.resize((round(im.width/im.height*16383), 16383))
                    # compress image in WEBP
                    im.save(im_io, 'WEBP', quality=50, method=4)
                    medic.health_care_certificate.save(
                        request.user.username+"_"+name, im_io)
                    medic.save()
                except UnidentifiedImageError:
                    errors.append("La tessera della cassa malati non è un immagine valida")
                except PDFPageCountError:
                    errors.append("La tessera della cassa malati non è un pdf valido")
                except PDFSyntaxError:
                    errors.append("La tessera della cassa malati non è un pdf valido")
                except IOError:
                    errors.append("La tessera della cassa malati è un immagine troppo grande")

            # user requested file delete
            if request.POST["delete_vac"] == 'vac':
                medic.vac_certificate = None
                medic.save()

            if request.POST["delete_health"] == 'health':
                medic.health_care_certificate = None
                medic.save()

            # if there wasn't any error redirect to clear POST
            if len(errors) == 0:
                return HttpResponseRedirect(request.get_full_path())

    else:
        # no post, create empty validation
        validation_dic["birth_date"] = 'class="datepicker validate" required="" aria-required="true"'
        for i in required_fields:
            validation_dic[i] = 'class="validate" required="" aria-required="true"'

    # check if user is in a group and set multiple choice to that
    if len(request.user.groups.values_list('name', flat=True)) == 0:
        branca_default = "selected"
    else:
        parent_group = request.user.groups.values_list('name', flat=True)[0]
        if parent_group == "diga":
            branca_castorini = "selected"
        elif parent_group == "muta":
            branca_lupetti = "selected"
        elif parent_group == "reparto":
            branca_esploratori = "selected"
        elif parent_group == "posto":
            branca_pionieri = "selected"
        elif parent_group == "clan":
            branca_rover = "selected"
        else:
            branca_default = "selected"

    # set checkbox status
    rega = ""
    if medic.rega:
        rega = "checked='checked'"
    drugs = ""
    if medic.drugs_bool:
        drugs = "checked='checked'"
    misc = ""
    if medic.misc_bool:
        misc = "checked='checked'"

    # set file name for uploaded files
    if (medic.vac_certificate != None):
        vac_name = os.path.basename(medic.vac_certificate.name)
        vac_name = vac_name[vac_name.find("_")+1:]
    else:
        vac_name = ''

    if (medic.health_care_certificate != None):
        card_name = os.path.basename(medic.health_care_certificate.name)
        card_name = card_name[card_name.find("_")+1:]
    else:
        card_name = ''

    # check if user is connected with midata
    midata_user = (usercode.midata_id > 0)
    midata_disable = ""

    # get user info from midata
    if midata_user:
        midata_disable = " readonly disabled"
        if not copy_from_midata(request, usercode):
            return HttpResponseRedirect(request.get_full_path())

    usable_password = request.user.has_usable_password()

    # check if user has saved the form
    home_tooltip = False
    if "saved" in request.GET:
        # show tooltip only if user is not approved and there are no errors
        home_tooltip = (not request.user.has_perm("client.approved")) and (len(errors) == 0)

    # fill context
    context = {
        'ucode': code,
        'validation_dic': validation_dic,
        'first_name': usercode.first_name,
        'last_name': usercode.last_name,
        'parent_name': usercode.parent_name,
        'via': usercode.via,
        'cap': usercode.cap,
        'country': usercode.country,
        'nationality': usercode.nationality,
        'birth_date': usercode.born_date,
        'home_phone': usercode.home_phone,
        'phone': usercode.phone,
        'school': usercode.school,
        'year': usercode.year,
        'avs_number': usercode.avs_number,
        'branca_default': branca_default,
        'branca_castorini': branca_castorini,
        'branca_lupetti': branca_lupetti,
        'branca_esploratori': branca_esploratori,
        'branca_pionieri': branca_pionieri,
        'branca_rover': branca_rover,
        'emer_name': medic.emer_name,
        'emer_relative': medic.emer_relative,
        'cell_phone': medic.cell_phone,
        'address': medic.address,
        'emer_phone': medic.emer_phone,
        'health_care': medic.health_care,
        'injuries': medic.injuries,
        'rc': medic.rc,
        'rega_check': rega,
        'medic_name': medic.medic_name,
        'medic_phone': medic.medic_phone,
        'medic_address': medic.medic_address,
        'sickness': medic.sickness,
        'vaccine': medic.vaccine,
        'tetanus_date': medic.tetanus_date,
        'allergy': medic.allergy,
        'drugs_check': drugs,
        'drugs': medic.drugs,
        'misc_check': misc,
        'misc': medic.misc,
        'health_care_certificate': card_name,
        'vac_certificate': vac_name,
        'errors': errors,
        'ok_message': ok_message,
        'midata_user': midata_user,
        'midata_disable': midata_disable,
        'usable_password': usable_password,
        'personal_active': personal_active,
        'medic_active': medic_active,
        'settings_active': settings_active,
        'midata_enabled': MIDATA_ENABLED,
        'home_tooltip': home_tooltip,
    }

    return render(request, 'accounts/user_edit.html', context)

# simple terms page, only static html
def terms(request):
    context = {}
    return render(request, 'accounts/terms.html', context)