-
-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathviews.py
More file actions
1835 lines (1586 loc) · 78.5 KB
/
Copy pathviews.py
File metadata and controls
1835 lines (1586 loc) · 78.5 KB
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
import csv
from datetime import timedelta
import os
import urllib.parse
import random
from time import time
from django.shortcuts import render, redirect
from django.http import Http404, HttpResponse, HttpResponseForbidden, JsonResponse
from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _
from django.contrib import messages
from django.contrib.messages import get_messages
from django.utils.html import format_html
from django.db.models import Q
from django.contrib.auth.decorators import login_required
from django.db import transaction, IntegrityError
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User
from django.contrib.auth.forms import PasswordChangeForm
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.utils.timezone import now
from django.core.files.storage import FileSystemStorage
from django.core.paginator import Paginator
from django.views.generic.edit import CreateView
from formtools.wizard.views import SessionWizardView
from .models import Petition, Signature, Organization, PytitionUser, PetitionTemplate, Permission
from .models import SlugModel, ModerationReason, Moderation
from .forms import SignatureForm, ContentFormPetition, EmailForm, NewsletterForm, SocialNetworkForm, ContentFormTemplate
from .forms import StyleForm, PetitionCreationStep1, PetitionCreationStep2, PetitionCreationStep3, UpdateInfoForm
from .forms import DeleteAccountForm, OrgCreationForm
from .helpers import get_client_ip, get_session_user, petition_from_id
from .helpers import check_petition_is_accessible
from .helpers import send_confirmation_email, subscribe_to_newsletter, send_welcome_mail
from .helpers import get_update_form, petition_detail_meta
from .helpers import sanitize_html
from .helpers import remove_user_moderated
#------------------------------------ Views -----------------------------------
# Path : /
# Depending on the settings.INDEX_PAGE, show a list of petitions or
# redirect to an user/org profile page
def index(request):
if not hasattr(settings, 'INDEX_PAGE'):
raise Http404(_("You must set an INDEX_PAGE config in your settings"))
if settings.INDEX_PAGE == 'USER_PROFILE':
try:
user_name = settings.INDEX_PAGE_USER
except:
raise Http404(_("You must set an INDEX_PAGE_USER config in your settings"))
elif settings.INDEX_PAGE == 'ORGA_PROFILE':
try:
org_name = settings.INDEX_PAGE_ORGA
except:
raise Http404(_("You must set an INDEX_PAGE_ORGA config in your settings"))
if settings.INDEX_PAGE == 'ORGA_PROFILE':
org = Organization.objects.get(name=org_name)
return redirect("org_profile", org.slugname)
elif settings.INDEX_PAGE == 'USER_PROFILE':
return redirect("user_profile", user_name)
elif settings.INDEX_PAGE == 'LOGIN_REGISTER':
if request.user.is_authenticated:
return redirect("user_dashboard")
else:
return redirect("login")
else:
authenticated = request.user.is_authenticated
if authenticated:
user = get_session_user(request)
else:
user = request.user
sort = request.GET.get('sort', 'desc')
creation_date = '-creation_date' if sort == 'desc' else 'creation_date'
all_petitions = Petition.objects.filter(published=True, moderated=False).order_by(creation_date)
all_petitions = remove_user_moderated(all_petitions)
paginator = Paginator(all_petitions, settings.PAGINATOR_COUNT)
page = request.GET.get('page')
petitions = paginator.get_page(page)
return render(request, 'petition/index.html',
{
'user': user,
'petitions': petitions,
'sort': sort
}
)
# <int:petition_id>/show_sympa_subscribe_bloc
# Show sympa subscribe bloc to mass subscribe people to newsletter
@login_required
def show_sympa_subscribe_bloc(request, petition_id):
try:
pytitionuser = get_session_user(request)
except:
pytitionuser = None
if not pytitionuser:
return redirect('index')
petition = petition_from_id(petition_id)
if petition.owner_type == "org" and not petition.org.is_allowed_to(pytitionuser, "can_view_signatures"):
return redirect("index")
elif petition.owner_type == "user" and petition.owner != pytitionuser:
return redirect("index")
text_bloc = ""
signatures = petition.signature_set.filter(subscribed_to_mailinglist=True)
if not signatures:
return HttpResponse(_("No newsletter subscription yet!"))
for signature in signatures:
text_bloc = text_bloc + "{email} {firstname} {lastname}<br/>\n".format(email=signature.email,
firstname=signature.first_name,
lastname=signature.last_name)
return HttpResponse(sanitize_html(text_bloc))
# /search?q=QUERY
# Show results of a search query
def search(request):
q = request.GET.get('q', '')
if q != "":
petitions = Petition.objects.filter(Q(title__icontains=q) | Q(text__icontains=q)).filter(published=True,
moderated=False)[:15]
petitions = remove_user_moderated(petitions)
orgs = Organization.objects.filter(name__icontains=q)
else:
petitions = Petition.objects.filter(published=True, moderated=False).order_by('-id')
petitions = remove_user_moderated(petitions)
paginator = Paginator(petitions, settings.PAGINATOR_COUNT)
page = request.GET.get('page')
petitions = paginator.get_page(page)
orgs = []
return render(
request, 'petition/search.html',
{
'petitions': petitions,
'orgs': orgs,
'q': q
}
)
def hide_sign_form_if_user_just_signed(request, ctx):
storage = get_messages(request)
for message in storage:
if message.level == messages.SUCCESS:
just_confirmed = request.session.get('just_confirmed', False)
if just_confirmed:
ctx.update({'signature_is_confirmed': True})
request.session['just_confirmed'] = False
else:
ctx.update({'petition_is_signed': True})
# /<int:petition_id>/
# Show information on a petition
def detail(request, petition_id):
petition = petition_from_id(petition_id)
check_petition_is_accessible(request, petition)
try:
pytitionuser = get_session_user(request)
except:
pytitionuser = None
reasons = ModerationReason.objects.all()
sign_form = SignatureForm(petition=petition)
ctx = {"user": pytitionuser, 'petition': petition, 'form': sign_form,
'meta': petition_detail_meta(request, petition_id),
'moderation_reasons': reasons,
'og_image_absolute_url': request.build_absolute_uri(petition.twitter_image)}
# If we've just signed successfully the petition, do not show the sign form
hide_sign_form_if_user_just_signed(request, ctx)
if "application/json" in request.META.get('HTTP_ACCEPT', []):
response = JsonResponse(petition.to_json)
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Methods"] = "GET, OPTIONS"
return response
else:
return render(request, 'petition/petition_detail.html', ctx)
# /<int:petition_id>/confirm/<confirmation_hash>
# Confirm signature to a petition
def confirm(request, petition_id, confirmation_hash):
petition = petition_from_id(petition_id)
check_petition_is_accessible(request, petition)
try:
successmsg = petition.confirm_signature(confirmation_hash)
if successmsg is None:
messages.error(request, _("Error: This confirmation code is invalid. Maybe you\'ve already confirmed?"))
else:
messages.success(request, successmsg)
request.session['just_confirmed'] = True
except ValidationError as e:
messages.error(request, _(e.message))
except Signature.DoesNotExist:
messages.error(request, _("Error: This confirmation code is invalid."))
return redirect(petition.url)
# <int:petition_id>/get_csv_signature
# <int:petition_id>/get_csv_confirmed_signature
# returns the CSV files of the list of signatures
@login_required
def get_csv_signature(request, petition_id, only_confirmed):
user = get_session_user(request)
try:
petition = Petition.objects.get(pk=petition_id)
except Petition.DoesNotExist:
return JsonResponse({}, status=404)
if petition.owner_type == "org" and not petition.org.is_allowed_to(user, "can_view_signatures"):
return JsonResponse({}, status=403)
elif petition.owner_type == "user" and petition.owner != user:
return JsonResponse({}, status=403)
filename = '{}.csv'.format(petition)
signatures = Signature.objects.filter(petition = petition)
if only_confirmed:
signatures = signatures.filter(confirmed = True)
else:
signatures = signatures.all()
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment;filename={}'.format(filename).replace('\r\n', '').replace(' ', '%20')
writer = csv.writer(response)
attrs = ['first_name', 'last_name', 'phone', 'email', 'subscribed_to_mailinglist', 'confirmed']
writer.writerow(attrs)
for signature in signatures:
values = [getattr(signature, field) for field in attrs]
writer.writerow(values)
return response
# resend/<int:signature_id>
# resend the signature confirmation email
@login_required
def go_send_confirmation_email(request, signature_id):
app_label = Signature._meta.app_label
signature = Signature.objects.filter(pk=signature_id).get()
send_confirmation_email(request, signature)
return redirect('admin:{}_signature_change'.format(app_label), signature_id)
# <int:petition_id>/sign
# Sign a petition
def create_signature(request, petition_id):
petition = petition_from_id(petition_id)
check_petition_is_accessible(request, petition)
if request.method == "POST":
form = SignatureForm(petition=petition, data=request.POST)
ctx = {
'petition': petition,
'form': form,
'meta': petition_detail_meta(request, petition_id),
'og_image_absolute_url': request.build_absolute_uri(petition.twitter_image)
}
if not form.is_valid():
return render(request, 'petition/petition_detail.html', ctx)
ipaddr = make_password(
get_client_ip(request),
salt=petition.salt.encode('utf-8'))
since = now() - timedelta(seconds=settings.SIGNATURE_THROTTLE_TIMING)
signatures = Signature.objects.filter(
petition=petition,
ipaddress=ipaddr,
date__gt=since)
if signatures.count() > settings.SIGNATURE_THROTTLE:
messages.error(request, _("Too many signatures from your IP address, please try again later."))
return render(request, 'petition/petition_detail.html', ctx)
else:
signature = form.save()
signature.ipaddress = ipaddr
signature.save()
send_confirmation_email(request, signature)
messages.success(request,
format_html(_("Thank you for signing this petition, an email has just been sent to you at your address \'{}\'" \
" in order to confirm your signature.<br>" \
"You will need to click on the confirmation link in the email.<br>" \
"If you cannot find the email in your Inbox, please have a look in your Spam box.")\
, signature.email))
if petition.has_newsletter and signature.subscribed_to_mailinglist:
subscribe_to_newsletter(petition, signature.email)
return redirect(petition.url)
# /org/<slug:orgslugname>/dashboard
# Show the dashboard of an organization
@login_required
def org_dashboard(request, orgslugname):
try:
org = Organization.objects.get(slugname=orgslugname)
except Organization.DoesNotExist:
messages.error(request, _("This organization does not exist: '{}'".format(orgslugname)))
return redirect("user_dashboard")
pytitionuser = get_session_user(request)
if pytitionuser not in org.members.all():
messages.error(request, _("You are not part of this organization: '{}'".format(org.name)))
return redirect("user_dashboard")
try:
permissions = Permission.objects.get(organization=org, user=pytitionuser)
except Permission.DoesNotExist:
messages.error(request,
_("Internal error, cannot find your permissions attached to this organization (\'{orgname}\')"
.format(orgname=org.name)))
return redirect("user_dashboard")
can_create_petition = org.is_allowed_to(pytitionuser, "can_create_petitions")
petitions = org.petition_set.all()
other_orgs = pytitionuser.organization_set.filter(~Q(name=org.name)).all()
return render(request, 'petition/org_dashboard.html',
{'org': org, 'user': pytitionuser, "other_orgs": other_orgs,
'petitions': petitions, 'user_permissions': permissions,
'can_create_petition': can_create_petition,
'displaying_dashboard': True})
# /user/dashboard
# Dashboard of the logged in user
@login_required
def user_dashboard(request):
user = get_session_user(request)
petitions = user.petition_set.all()
return render(
request,
'petition/user_dashboard.html',
{'user': user, 'petitions': petitions, 'can_create_petition': True,
'displaying_dashboard': True}
)
# /user/<user_name>
# Show the user profile
def user_profile(request, user_name):
try:
user = PytitionUser.objects.get(user__username=user_name)
except PytitionUser.DoesNotExist:
raise Http404(_("not found"))
sort = request.GET.get('sort', 'desc')
creation_date = '-creation_date' if sort == 'desc' else 'creation_date'
petitions = user.petition_set.filter(published=True, moderated=False).order_by(creation_date)
petitions = remove_user_moderated(petitions)
paginator = Paginator(petitions, settings.PAGINATOR_COUNT)
page = request.GET.get('page')
petitions = paginator.get_page(page)
return render(
request,
'petition/user_profile.html',
{'user': user, 'petitions': petitions, 'sort': sort }
)
# /org/<slug:orgslugname>/leave_org
# User is leaving the organisation
@login_required
def leave_org(request, orgslugname):
try:
org = Organization.objects.get(slugname=orgslugname)
except Organization.DoesNotExist:
raise Http404(_("not found"))
pytitionuser = get_session_user(request)
if pytitionuser not in org.members.all():
raise Http404(_("not found"))
with transaction.atomic():
if org.is_last_admin(pytitionuser):
messages.error(request, _('Impossible to leave this organisation, you are the last administrator'))
return redirect(reverse('account_settings') + '#a_org_form')
elif org.members.count() == 1:
messages.error(request, _('Impossible to leave this organisation, you are the last member'))
return redirect(reverse('account_settings') + '#a_org_form')
else:
org.members.remove(pytitionuser)
return redirect('account_settings')
# /org/<slug:orgslugname>
# Show the profile of an organization
def org_profile(request, orgslugname):
try:
user = get_session_user(request)
except:
user = None
try:
org = Organization.objects.get(slugname=orgslugname)
except Organization.DoesNotExist:
raise Http404(_("not found"))
sort = request.GET.get('sort', 'desc')
creation_date = '-creation_date' if sort == 'desc' else 'creation_date'
petitions = org.petition_set.filter(published=True, moderated=False).order_by(creation_date)
petitions = remove_user_moderated(petitions)
paginator = Paginator(petitions, settings.PAGINATOR_COUNT)
page = request.GET.get('page')
petitions = paginator.get_page(page)
ctx = {'org': org,
'petitions': petitions,
'sort': sort}
# if a user is logged-in, put it in the context, it will feed the navbar dropdown
if user is not None:
ctx['user'] = user
return render(request, "petition/org_profile.html", ctx)
# /get_user_list
# get the list of users
@login_required
def get_user_list(request):
q = request.GET.get('q', '')
if q != "":
users = PytitionUser.objects.filter(Q(user__username__contains=q) | Q(user__first_name__icontains=q) |
Q(user__last_name__icontains=q)).all()
else:
users = []
userdict = {
"values": [user.user.username for user in users],
}
return JsonResponse(userdict)
# PATH : org/<slug:orgslugname>/add_user
# Add an user to an organization
@login_required
def org_add_user(request, orgslugname):
adduser = request.GET.get('user', '')
try:
adduser = PytitionUser.objects.get(user__username=adduser)
except PytitionUser.DoesNotExist:
message = _("This user does not exist (anylonger?)")
return JsonResponse({"message": message}, status=404)
try:
org = Organization.objects.get(slugname=orgslugname)
except Organization.DoesNotExist:
message = _("This organization does not exist (anylonger?)")
return JsonResponse({"message": message}, status=404)
pytitionuser = get_session_user(request)
if org not in pytitionuser.organization_set.all():
message = _("You are not part of this organization.")
return JsonResponse({"message": message}, status=403)
if org in adduser.organization_set.all():
message = _("User is already member of {orgname} organization".format(orgname=org.name))
return JsonResponse({"message": message}, status=500)
if not org.is_allowed_to(pytitionuser, "can_add_members"):
message = _("You are not allowed to invite new members into this organization.")
return JsonResponse({"message": message}, status=403)
try:
adduser.invitations.add(org)
adduser.save()
except:
message = _("An error occured")
return JsonResponse({"message": message}, status=500)
message = _("You invited {username} to join {orgname}".format(username=adduser.name, orgname=org.name))
return JsonResponse({"message": message})
# /org/<slug:orgslugname>/invite_accept
# Accept an invitation to an organisation
# Called from /user/dashboard
@login_required
def invite_accept(request, orgslugname):
if orgslugname == "":
return HttpResponse(status=500)
pytitionuser = get_session_user(request)
try:
org = Organization.objects.get(slugname=orgslugname)
except Organization.DoesNotExist:
raise Http404(_("not found"))
if org in pytitionuser.invitations.all():
try:
with transaction.atomic():
pytitionuser.invitations.remove(org)
org.members.add(pytitionuser)
except:
return HttpResponse(status=500)
else:
raise Http404(_("not found"))
return redirect('user_dashboard')
# /org/<slug:orgslugname>/invite_dismiss
# Dismiss the invitation to an organisation
@login_required
def invite_dismiss(request, orgslugname):
if orgslugname == "":
return JsonResponse({}, status=500)
pytitionuser = get_session_user(request)
try:
org = Organization.objects.get(slugname=orgslugname)
except Organization.DoesNotExist:
raise Http404(_("not found"))
if org in pytitionuser.invitations.all():
try:
pytitionuser.invitations.remove(org)
except:
return JsonResponse({}, status=500)
else:
raise Http404(_("not found"))
return redirect('user_dashboard')
# /org/<slug:orgslugname>/new_template
# /user/new_template
# Create a new template
@login_required
def new_template(request, orgslugname=None):
pytitionuser = get_session_user(request)
ctx = {'user': pytitionuser}
if orgslugname:
redirection = "org_new_template"
try:
org = Organization.objects.get(slugname=orgslugname)
ctx['org'] = org
except Organization.DoesNotExist:
raise Http404(_("Organization does not exist"))
if org not in pytitionuser.organization_set.all():
return HttpResponseForbidden(_("You are not allowed to view this organization dashboard"))
try:
permissions = Permission.objects.get(organization=org, user=pytitionuser)
ctx['user_permissions'] = permissions
except Permission.DoesNotExist:
return HttpResponse(
_("Internal error, cannot find your permissions attached to this organization (\'{orgname}\')"
.format(orgname=org.name)), status=500)
if not permissions.can_create_templates:
return HttpResponseForbidden(_("You don't have the permission to create a Template in this organization"))
ctx['base_template'] = 'petition/org_base.html'
else:
redirection = "user_new_template"
ctx['base_template'] = 'petition/user_base.html'
if request.method == "POST":
template_name = request.POST.get('template_name', '')
if template_name != '':
if orgslugname:
template = PetitionTemplate(name=template_name, org=org)
else:
template = PetitionTemplate(name=template_name, user=pytitionuser)
template.save()
return redirect("edit_template", template.id)
else:
messages.error(request, _("You need to provide a template name."))
return redirect(redirection)
else:
return render(request, "petition/new_template.html", ctx)
# /templates/<int:template_id>/edit
# Edit a petition template
@login_required
def edit_template(request, template_id):
id = template_id
if id == '':
return HttpResponseForbidden(_("You need to provide the template id to modify"))
try:
template = PetitionTemplate.objects.get(pk=id)
except PetitionTemplate.DoesNotExist:
raise Http404(_("This template does not exist"))
pytitionuser = get_session_user(request)
context = {'user': pytitionuser}
if template.owner_type == "org":
owner = template.org
else:
owner = template.user
if template.owner_type == "org":
try:
permissions = Permission.objects.get(organization=owner, user=pytitionuser)
except:
return HttpResponse(
_("Internal error, cannot find your permissions attached to this organization (\'{orgname}\')"
.format(orgname=owner.name)), status=500)
context['user_permissions'] = permissions
if owner not in pytitionuser.organization_set.all() or not permissions.can_modify_templates:
return HttpResponseForbidden(_("You are not allowed to edit this organization's templates"))
context['org'] = owner
base_template = "petition/org_base.html"
else:
if owner != pytitionuser:
return HttpResponseForbidden(_("You are not allowed to edit this user's templates"))
base_template = "petition/user_base.html"
submitted_ctx = {
'content_form_submitted': False,
'email_form_submitted': False,
'social_network_form_submitted': False,
'newsletter_form_submitted': False,
'style_form_submitted': False,
}
if request.method == "POST":
if 'content_form_submitted' in request.POST:
content_form = ContentFormTemplate(request.POST)
submitted_ctx['content_form_submitted'] = True
if content_form.is_valid():
template.target = content_form.cleaned_data['target']
template.name = content_form.cleaned_data['name']
template.text = content_form.cleaned_data['text']
template.side_text = content_form.cleaned_data['side_text']
template.footer_text = content_form.cleaned_data['footer_text']
template.footer_links = content_form.cleaned_data['footer_links']
template.sign_form_footer = content_form.cleaned_data['sign_form_footer']
template.save()
else:
content_form = ContentFormTemplate({f: getattr(template, f) for f in ContentFormTemplate.base_fields})
if 'email_form_submitted' in request.POST:
email_form = EmailForm(request.POST)
submitted_ctx['email_form_submitted'] = True
if email_form.is_valid():
template.confirmation_email_reply = email_form.cleaned_data['confirmation_email_reply']
template.save()
else:
email_form = EmailForm({f: getattr(template, f) for f in EmailForm.base_fields})
if 'social_network_form_submitted' in request.POST:
social_network_form = SocialNetworkForm(request.POST, request.FILES)
submitted_ctx['social_network_form_submitted'] = True
if social_network_form.is_valid():
storage = FileSystemStorage()
file = social_network_form.cleaned_data['twitter_image']
if file:
path = os.path.join(pytitionuser.username, file.name)
name = storage.save(path, file)
template.twitter_image = storage.url(name)
if social_network_form.cleaned_data['remove_twitter_image']:
template.twitter_image = ""
template.twitter_description = social_network_form.cleaned_data['twitter_description']
template.org_twitter_handle = social_network_form.cleaned_data['org_twitter_handle']
template.has_email_share_button = social_network_form.cleaned_data['has_email_share_button']
template.has_facebook_share_button = social_network_form.cleaned_data['has_facebook_share_button']
template.has_tumblr_share_button = social_network_form.cleaned_data['has_tumblr_share_button']
template.has_linkedin_share_button = social_network_form.cleaned_data['has_linkedin_share_button']
template.has_twitter_share_button = social_network_form.cleaned_data['has_twitter_share_button']
template.has_mastodon_share_button = social_network_form.cleaned_data['has_mastodon_share_button']
template.has_whatsapp_share_button = social_network_form.cleaned_data['has_whatsapp_share_button']
template.save()
else:
remove_fields = ["twitter_image", "remove_twitter_image"]
fields = dict((k, v) for k,v in SocialNetworkForm.base_fields.items() if k not in remove_fields)
social_network_form = SocialNetworkForm({f: getattr(template, f) for f in fields})
if 'newsletter_form_submitted' in request.POST:
newsletter_form = NewsletterForm(request.POST)
submitted_ctx['newsletter_form_submitted'] = True
if newsletter_form.is_valid():
template.has_newsletter = newsletter_form.cleaned_data['has_newsletter']
template.newsletter_text = newsletter_form.cleaned_data['newsletter_text']
template.newsletter_subscribe_http_data = newsletter_form.cleaned_data['newsletter_subscribe_http_data']
template.newsletter_subscribe_http_mailfield = newsletter_form.cleaned_data['newsletter_subscribe_http_mailfield']
template.newsletter_subscribe_http_url = newsletter_form.cleaned_data['newsletter_subscribe_http_url']
template.newsletter_subscribe_mail_subject = newsletter_form.cleaned_data['newsletter_subscribe_mail_subject']
template.newsletter_subscribe_mail_from = newsletter_form.cleaned_data['newsletter_subscribe_mail_from']
template.newsletter_subscribe_mail_to = newsletter_form.cleaned_data['newsletter_subscribe_mail_to']
template.newsletter_subscribe_method = newsletter_form.cleaned_data['newsletter_subscribe_method']
template.newsletter_subscribe_mail_smtp_host = newsletter_form.cleaned_data['newsletter_subscribe_mail_smtp_host']
template.newsletter_subscribe_mail_smtp_port = newsletter_form.cleaned_data['newsletter_subscribe_mail_smtp_port']
template.newsletter_subscribe_mail_smtp_user = newsletter_form.cleaned_data['newsletter_subscribe_mail_smtp_user']
template.newsletter_subscribe_mail_smtp_password = newsletter_form.cleaned_data['newsletter_subscribe_mail_smtp_password']
template.newsletter_subscribe_mail_smtp_tls = newsletter_form.cleaned_data['newsletter_subscribe_mail_smtp_tls']
template.newsletter_subscribe_mail_smtp_starttls = newsletter_form.cleaned_data['newsletter_subscribe_mail_smtp_starttls']
template.save()
else:
newsletter_form = NewsletterForm({f: getattr(template, f) for f in NewsletterForm.base_fields})
if 'style_form_submitted' in request.POST:
submitted_ctx['style_form_submitted'] = True
style_form = StyleForm(request.POST)
if style_form.is_valid():
template.bgcolor = style_form.cleaned_data['bgcolor']
template.linear_gradient_direction = style_form.cleaned_data['linear_gradient_direction']
template.gradient_from = style_form.cleaned_data['gradient_from']
template.gradient_to = style_form.cleaned_data['gradient_to']
template.save()
else:
style_form = StyleForm({f: getattr(template, f) for f in StyleForm.base_fields})
else:
remove_fields = ["twitter_image", "remove_twitter_image"]
fields = dict((k, v) for k, v in SocialNetworkForm.base_fields.items() if k not in remove_fields)
social_network_form = SocialNetworkForm({f: getattr(template, f) for f in fields})
content_form = ContentFormTemplate({f: getattr(template, f) for f in ContentFormTemplate.base_fields})
email_form = EmailForm({f: getattr(template, f) for f in EmailForm.base_fields})
newsletter_form = NewsletterForm({f: getattr(template, f) for f in NewsletterForm.base_fields})
style_form = StyleForm({f: getattr(template, f) for f in StyleForm.base_fields})
ctx = {'content_form': content_form,
'email_form': email_form,
'social_network_form': social_network_form,
'newsletter_form': newsletter_form,
'style_form': style_form,
'petition': template,
'is_template': True}
context['base_template'] = base_template
context.update(ctx)
context.update(submitted_ctx)
return render(request, "petition/edit_template.html", context)
# /templates/<int:template_id>/delete
# Delete a template
@login_required
def template_delete(request, template_id):
pytitionuser = get_session_user(request)
if template_id == '':
return JsonResponse({}, status=500)
try:
template = PetitionTemplate.objects.get(pk=template_id)
except:
return JsonResponse({}, status=404)
if template.owner_type == "org":
if not pytitionuser in template.org.members.all():
return JsonResponse({}, status=403) # User not in organization
try:
permissions = Permission.objects.get(
organization=template.org,
user=pytitionuser)
except Permission.DoesNotExist:
return JsonResponse({}, status=500) # No permission? fatal error!
if not permissions.can_delete_templates:
return JsonResponse({}, status=403) # User does not have the permission!
else:
if pytitionuser != template.user:
return JsonResponse({}, status=403) # User cannot delete a template if it's not his
template.delete()
return JsonResponse({})
# /templates/<int:template_id>/fav
# Set a template as favourite
@login_required
def template_fav_toggle(request, template_id):
pytitionuser = get_session_user(request)
if template_id == '':
return JsonResponse({}, status=500)
try:
template = PetitionTemplate.objects.get(pk=template_id)
except PetitionTemplate.DoesNotExist:
return JsonResponse({}, status=404)
if template.owner_type == "org":
owner = template.org
else:
owner = template.user
if template.owner_type == "org":
if owner not in pytitionuser.organization_set.all():
return JsonResponse({}, status=403) # Forbidden
else:
if owner != pytitionuser:
return JsonResponse({'msg': _("You are not allowed to change this user's default template")}, status=403)
if owner.default_template == template:
owner.default_template = None
else:
owner.default_template = template
owner.save()
return JsonResponse({})
# /org/<slug:orgslugname>/delete_member
# Remove a member from an organization
@login_required
def org_delete_member(request, orgslugname):
member_name = request.GET.get('member', '')
try:
member = PytitionUser.objects.get(user__username=member_name)
except PytitionUser.DoesNotExist:
raise Http404(_("User does not exist"))
pytitionuser = get_session_user(request)
try:
org = Organization.objects.get(slugname=orgslugname)
except Organization.DoesNotExist:
raise Http404(_("Organization does not exist"))
if pytitionuser not in org.members.all():
return JsonResponse({}, status=403) # Forbidden
try:
permissions = Permission.objects.get(user=pytitionuser, organization=org)
except Permission.DoesNoeExist:
return JsonResponse({}, status=500)
if permissions.can_remove_members or pytitionuser == member:
if org in member.organization_set.all():
if org.is_last_admin(member):
return JsonResponse({}, status=403) # Forbidden
member.organization_set.remove(org)
else:
return JsonResponse({}, status=404)
else:
return JsonResponse({}, status=403) # Forbidden
return JsonResponse({}, status=200)
# PATH : org/<slug:orgslugname>/edit_user_permissions/<slug:user_name>
# Show a webpage to edit permissions
@login_required
def org_edit_user_perms(request, orgslugname, user_name):
"""Shows the page which lists the user permissions."""
pytitionuser = get_session_user(request)
try:
member = PytitionUser.objects.get(user__username=user_name)
except PytitionUser.DoesNotExist:
messages.error(request, _("User '{name}' does not exist".format(name=user_name)))
return redirect("org_dashboard", orgslugname)
try:
org = Organization.objects.get(slugname=orgslugname)
except Organization.DoesNotExist:
raise Http404(_("Organization '{name}' does not exist".format(name=orgslugname)))
if org not in member.organization_set.all():
messages.error(request, _("The user '{username}' is not member of this organization ({orgname}).".
format(username=user_name, orgname=org.name)))
return redirect("org_dashboard", org.slugname)
try:
permissions = Permission.objects.get(organization=org, user=member)
except Permission.DoesNotExist:
messages.error(request,
_("Internal error, this member does not have permissions attached to this organization."))
return redirect("org_dashboard", org.slugname)
try:
user_permissions = Permission.objects.get(organization=org, user=pytitionuser)
except:
return HttpResponse(
_("Internal error, cannot find your permissions attached to this organization (\'{orgname}\')"
.format(orgname=org.name)), status=500)
return render(request, "petition/org_edit_user_perms.html",
{'org': org, 'member': member, 'user': pytitionuser,
'permissions': permissions,
'user_permissions': user_permissions})
# PATH /org/<slug:orgslugname>/set_user_permissions/<slug:user_name>
# Set a permission for an user
@login_required
def org_set_user_perms(request, orgslugname, user_name):
"""Actually do the modification of user permissions.
Data come from "org_edit_user_perms" view's form.
"""
pytitionuser = get_session_user(request)
try:
org = Organization.objects.get(slugname=orgslugname)
except Organization.DoesNotExist:
raise Http404(_("Organization does not exist"))
if pytitionuser not in org.members.all():
messages.error(request, _("You are not part of this organization"))
return redirect("user_dashboard")
try:
userperms = Permission.objects.get(user=pytitionuser, organization=org)
except:
messages.error(request, _("Fatal error, you don't have permissions attached to you for this organization"))
return redirect("org_dashboard", org.slugname)
if not userperms.can_modify_permissions:
messages.error(request, _("You are not allowed to modify this organization members' permissions"))
return redirect("org_edit_user_perms", orgslugname, user_name)
try:
member = PytitionUser.objects.get(user__username=user_name)
except PytitionUser.DoesNotExist:
messages.error(request, _("User does not exist"))
return redirect("org_dashboard", orgslugname)
if org not in member.organization_set.all():
messages.error(request, _("This user is not part of organization \'{orgname}\'".format(orgname=org.name)))
return redirect("org_dashboard", org.slugname)
try:
permissions = Permission.objects.get(user=member, organization=org)
except Permission.DoesNotExist:
messages.error(request, _("Fatal error, this user does not have permissions attached for this organization"))
return redirect("org_dashboard", org.slugname)
if request.method == "POST":
error = False
post = request.POST
permissions.can_remove_members = post.get('can_remove_members', '') == 'on'
permissions.can_add_members = post.get('can_add_members', '') == 'on'
permissions.can_create_petitions = post.get('can_create_petitions', '') == 'on'
permissions.can_modify_petitions = post.get('can_modify_petitions', '') == 'on'
permissions.can_delete_petitions = post.get('can_delete_petitions', '') == 'on'
permissions.can_create_templates = post.get('can_create_templates', '') == 'on'
permissions.can_modify_templates = post.get('can_modify_templates', '') == 'on'
permissions.can_delete_templates = post.get('can_delete_templates', '') == 'on'
permissions.can_view_signatures = post.get('can_view_signatures', '') == 'on'
permissions.can_modify_signatures = post.get('can_modify_signatures', '') == 'on'
permissions.can_delete_signatures = post.get('can_delete_signatures', '') == 'on'
can_modify_perms = post.get('can_modify_permissions', '') == 'on'
with transaction.atomic():
# if user is dropping his own permissions
if not can_modify_perms and permissions.can_modify_permissions and pytitionuser == member:
# get list of people with can_modify_permissions permission on this org
owners = org.owners
if owners.count() > 1:
permissions.can_modify_permissions = can_modify_perms
else:
if org.members.count() > 1:
error = True
messages.error(request, _("You cannot remove your ability to change permissions on this "
"Organization because you are the only one left who can do this. "
"Give the permission to someone else before removing yours."))
else:
error = True
messages.error(request, _("You cannot remove your ability to change permissions on this "
"Organization because you are the only member left."))
if not error:
permissions.can_modify_permissions = can_modify_perms
messages.success(request, _("Permissions successfully changed!"))
permissions.save()
return redirect("org_edit_user_perms", orgslugname, user_name)
WizardTemplates = {"step1": "petition/new_petition_step1.html",
"step2": "petition/new_petition_step2.html",
"step3": "petition/new_petition_step3.html"}
WizardForms = [("step1", PetitionCreationStep1),
("step2", PetitionCreationStep2),
("step3", PetitionCreationStep3)]
# Class Based Controller
# PATH : subroutes of /wizard
@method_decorator(login_required, name='dispatch')
class PetitionCreationWizard(SessionWizardView):
def dispatch(self, request, *args, **kwargs):
if settings.DISABLE_USER_PETITION and "orgslugname" not in self.kwargs:
messages.error(request, _("Users are not allowed to create their own petitions."))
return redirect("user_dashboard")
return super().dispatch(request, *args, **kwargs)
def get_template_names(self):
return [WizardTemplates[self.steps.current]]
def get_form_initial(self, step):
template = None