-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathviews.py
More file actions
executable file
·3388 lines (2903 loc) · 111 KB
/
Copy pathviews.py
File metadata and controls
executable file
·3388 lines (2903 loc) · 111 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
__copyright__ = "Copyright 2017 Birkbeck, University of London"
__author__ = "Martin Paul Eve & Andy Byers"
__license__ = "AGPL v3"
__maintainer__ = "Birkbeck Centre for Technology and Publishing"
from importlib import import_module
import json
from urllib.parse import unquote, urlencode
import pytz
import time
import warnings
from django.contrib import messages
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth import authenticate, logout, login
from django.contrib.auth.decorators import login_required
from django.core.cache import cache
from django.urls import NoReverseMatch, reverse, reverse_lazy
from django.shortcuts import render, get_object_or_404, redirect, Http404
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.http import HttpResponse, QueryDict, JsonResponse
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.sessions.models import Session
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
from django.db import IntegrityError
from django.conf import settings as django_settings
from django.views.decorators.http import require_GET, require_POST
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.generic import CreateView, UpdateView, DeleteView
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import gettext_lazy as _
from django.utils.html import mark_safe
from django.utils import translation
from django.db.models import Q, OuterRef, Subquery, Count, Avg
from django.views import generic
from core import models, forms, logic, workflow, files, models as core_models
from core.model_utils import NotImplementedField, SafePaginator, search_model_admin
from security.decorators import (
editor_user_required,
article_author_required,
has_journal,
any_editor_user_required,
role_can_access,
user_can_edit_setting,
)
from submission import models as submission_models
from utils.forms import clean_orcid_id
from review import models as review_models
from copyediting import models as copyedit_models
from production import models as production_models
from journal import models as journal_models
from proofing import logic as proofing_logic
from proofing import models as proofing_models
from press import forms as press_forms
from utils import models as util_models, setting_handler, orcid
from utils.logger import get_logger
from utils.decorators import GET_language_override
from utils.shared import language_override_redirect, clear_cache
from repository import models as rm
from events import logic as events_logic
logger = get_logger(__name__)
def user_login(request):
"""
Allows an unauthenticated user to login
:param request: HttpRequest
:return: HttpResponse
"""
next_url = request.GET.get("next", "")
if request.user.is_authenticated:
messages.info(request, "You are already logged in.")
return redirect(request.site_type.auth_success_url(next_url=next_url))
else:
bad_logins = logic.check_for_bad_login_attempts(request)
if bad_logins >= 10:
messages.info(
request,
_("You have been banned from logging in due to failed attempts."),
)
logger.warning("[LOGIN_DENIED][FAILURES:%d]" % bad_logins)
return redirect(reverse("website_index"))
form = forms.LoginForm(bad_logins=bad_logins)
if request.POST:
form = forms.LoginForm(request.POST, bad_logins=bad_logins)
if form.is_valid():
username = request.POST.get("user_name").lower()
password = request.POST.get("user_pass")
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
messages.info(request, "Login successful.")
logic.clear_bad_login_attempts(request)
orcid_token = request.POST.get("orcid_token", None)
if orcid_token:
try:
token_obj = models.OrcidToken.objects.get(
token=orcid_token, expiry__gt=timezone.now()
)
user.orcid = token_obj.orcid
user.save()
token_obj.delete()
except models.OrcidToken.DoesNotExist:
pass
return redirect(request.site_type.auth_success_url(next_url=next_url))
else:
empty_password_check = logic.no_password_check(
request.POST.get("user_name").lower()
)
if empty_password_check:
messages.add_message(
request,
messages.INFO,
_(
"Password reset process has been initiated,"
" please check your inbox for a"
" reset request link."
),
)
logic.start_reset_process(request, empty_password_check)
else:
messages.add_message(
request,
messages.ERROR,
_(
"Wrong email/password combination or your"
" email address has not been confirmed yet."
),
)
util_models.LogEntry.add_entry(
types="Authentication",
description="Failed login attempt for user {0}".format(
request.POST.get("user_name")
),
level="Info",
actor=None,
request=request,
)
logic.add_failed_login_attempt(request)
context = {
"form": form,
}
template = "admin/core/accounts/login.html"
return render(request, template, context)
def user_login_orcid(request):
"""
Allow a user to log in with their ORCID account
or switch to registering if needed.
:param request: HttpRequest object
:return: HttpResponse object
"""
# First figure out what the user is trying to do (action) and where they want to
# be returned to in Janeway (next).
# This information may be encoded in a 'state' parameter that we get back from ORCID
# or it may be in the generic request parameters.
state_string = request.GET.get("state", "")
state = orcid.decode_state(state_string)
if "action" in state:
action = state.get("action", "login")
else:
action = request.GET.get("action", "login")
if "next" in state:
next_url = state.get("next", "")
else:
next_url = request.GET.get("next", "")
# If ORCID is not enabled, redirect the user to the regular Janeway login page.
if not django_settings.ENABLE_ORCID:
messages.add_message(
request,
messages.WARNING,
_("ORCID is not enabled.Please log in with your username and password."),
)
return redirect(logic.reverse_with_next("core_login", next_url))
# If the orcid code is missing, that means the user has not come from
# orcid.org, just from a Janeway link.
# Send them to orcid.org to authenticate first.
# Encode the next URL and the action via 'state',
# which the ORCID auth system will pass back.
orcid_code = request.GET.get("code", "")
if not orcid_code:
base = django_settings.ORCID_URL
query_dict = {
"client_id": django_settings.ORCID_CLIENT_ID,
"response_type": "code",
"scope": "/authenticate",
"redirect_uri": orcid.build_redirect_uri(request.site_type),
"state": orcid.encode_state(next_url, action),
}
orcid_login_url = f"{base}?{urlencode(query_dict, safe='/')}"
return redirect(orcid_login_url)
# There is an orcid code, meaning the user has authenticated on orcid.org.
# Make another request to orcid.org to verify it.
orcid_id = orcid.retrieve_tokens(orcid_code, request.site_type)
# If verification did not work, send them to the regular login page.
if not orcid_id:
messages.add_message(
request,
messages.WARNING,
"Valid ORCID not returned. "
"Please try again, or log in with your username and password.",
)
return redirect(logic.reverse_with_next("core_login", next_url))
# The verification worked.
# If the user wanted to log in, try to log them in.
if action == "login":
try:
user = models.Account.objects.get(orcid=orcid_id)
login(
request,
user,
backend="django.contrib.auth.backends.ModelBackend",
)
return redirect(request.site_type.auth_success_url(next_url=next_url))
except models.Account.DoesNotExist:
# Lookup ORCID email addresses
orcid_details = orcid.get_orcid_record_details(orcid_id)
for email in orcid_details.get("emails", []):
candidates = models.Account.objects.filter(email=email)
if candidates.exists():
# Store ORCID for future authentication requests
candidates.update(orcid=orcid_id)
login(
request,
candidates.first(),
backend="django.contrib.auth.backends.ModelBackend",
)
return redirect(
request.site_type.auth_success_url(next_url=next_url)
)
# If no account was found for login,
# then prepare an ORCID token for registration.
# Then send the user to a decision page that tells them
# the ORCID login did not work and they will need to register.
models.OrcidToken.objects.filter(orcid=orcid_id).delete()
new_token = models.OrcidToken.objects.create(orcid=orcid_id)
return redirect(
logic.reverse_with_next(
"core_orcid_registration",
next_url,
kwargs={"token": str(new_token.token)},
)
)
# If the user wanted to register, send them to the registration page
# and pass along their orcid token so information can be pre-filled.
elif action == "register":
models.OrcidToken.objects.filter(orcid=orcid_id).delete()
new_token = models.OrcidToken.objects.create(orcid=orcid_id)
return redirect(
logic.reverse_with_next(
"core_register_with_orcid_token",
next_url,
kwargs={"orcid_token": str(new_token.token)},
)
)
@login_required
def user_logout(request):
"""
Logs a user session out.
:param request: HttpRequest object
:return: HttpResponse object
"""
messages.info(request, _("You have been logged out."))
logout(request)
return redirect(reverse("website_index"))
def get_reset_token(request):
"""
Generates a password reset token and emails it to the user's email account
:param request: HttpRequest object
:return: HttpResponse object
"""
new_reset_token = None
next_url = request.GET.get("next", "")
form = forms.GetResetTokenForm()
if request.POST:
form = forms.GetResetTokenForm(
request.POST,
)
if form.is_valid():
email_address = form.cleaned_data.get("email_address")
messages.add_message(
request,
messages.INFO,
_("If your account was found, an email has been sent to you."),
)
try:
account = models.Account.objects.get(email__iexact=email_address)
logic.start_reset_process(request, account)
return redirect(logic.reverse_with_next("core_login", next_url))
except models.Account.DoesNotExist:
return redirect(logic.reverse_with_next("core_login", next_url))
template = "admin/core/accounts/get_reset_token.html"
context = {
"new_reset_token": new_reset_token,
"form": form,
}
return render(request, template, context)
def reset_password(request, token):
"""
Takes a reset token and checks if it is valid.
Then it allows a user to reset their password,
and finally it expires the token.
:param request: HttpRequest
:param token: string, PasswordResetToken.token
:return: HttpResponse object
"""
next_url = request.GET.get("next", "")
reset_token = get_object_or_404(
models.PasswordResetToken, token=token, expired=False
)
form = forms.PasswordResetForm()
if reset_token.has_expired():
raise Http404
if request.POST:
form = forms.PasswordResetForm(request.POST)
password_policy_check = logic.password_policy_check(request)
if password_policy_check:
for policy_fail in password_policy_check:
form.add_error("password_1", policy_fail)
if form.is_valid():
password = form.cleaned_data["password_2"]
reset_token.account.set_password(password)
reset_token.account.is_active = True
logic.clear_bad_login_attempts(request)
reset_token.account.save()
reset_token.expired = True
reset_token.save()
messages.add_message(
request, messages.SUCCESS, "Your password has been reset."
)
return redirect(logic.reverse_with_next("core_login", next_url))
template = "admin/core/accounts/reset_password.html"
context = {
"reset_token": reset_token,
"form": form,
}
return render(request, template, context)
def register(request, orcid_token=None):
"""
Displays a form for users to register with the press or journal.
If the user is registering on a journal we give them
the Author role.
An ORCID token is passed when the user arrives here after they
tried to log in with ORCID, but Janeway said "No account found,
would you like to register instead?"
:param request: HttpRequest object
:param orcid_token: str UUID4 belonging to an active OrcidToken
:return: HttpResponse object
"""
context = {}
initial = {}
token_obj = None
next_url = request.GET.get("next", "")
if orcid_token:
token_obj = get_object_or_404(models.OrcidToken, token=orcid_token)
orcid_details = orcid.get_orcid_record_details(token_obj.orcid)
# we use the full orcid uri for display
context["orcid"] = orcid_details["uri"]
# but we save only the orcid (not uri) in the db
initial["orcid"] = orcid_details["orcid"]
initial["first_name"] = orcid_details.get("first_name", "")
initial["last_name"] = orcid_details.get("last_name", "")
if orcid_details.get("emails"):
initial["email"] = orcid_details["emails"][0]
form = forms.RegistrationForm(
journal=request.journal,
initial=initial,
)
if request.POST:
form = forms.RegistrationForm(
request.POST,
journal=request.journal,
)
password_policy_check = logic.password_policy_check(request)
if password_policy_check:
for policy_fail in password_policy_check:
form.add_error("password_1", policy_fail)
if form.is_valid():
if token_obj:
new_user = form.save()
if new_user.orcid:
orcid_details = orcid.get_orcid_record_details(token_obj.orcid)
for orcid_affil in orcid_details.get("affiliations", []):
orcid_affil_form = forms.OrcidAffiliationForm(
orcid_affiliation=orcid_affil,
tzinfo=new_user.preferred_timezone,
data={"account": new_user},
)
if orcid_affil_form.is_valid():
orcid_affil_form.save()
token_obj.delete()
# If the email matches the user email on ORCID, log them in
if new_user.email == initial.get("email"):
new_user.is_active = True
new_user.save()
login(
request,
new_user,
backend="django.contrib.auth.backends.ModelBackend",
)
return redirect(
request.site_type.auth_success_url(next_url=next_url)
)
else:
new_user = form.save()
if request.journal:
new_user.add_account_role("author", request.journal)
logic.send_confirmation_link(request, new_user)
messages.add_message(
request,
messages.SUCCESS,
_(
"Your account has been created. Please follow the "
"instructions in the email that has been sent to you."
),
)
return redirect(logic.reverse_with_next("core_login", next_url))
template = "admin/core/accounts/register.html"
context["form"] = form
return render(request, template, context)
def orcid_registration(request, token):
"""
Users arrive at this view when they have tried to log in
via ORCID, but no suitable Janeway account was found.
The view suggests to them they might want to register a new
account instead, and gives them options.
:param request: HttpRequest object
:param token: str UUID4 belonging to active OrcidToken
"""
token = get_object_or_404(models.OrcidToken, token=token, expiry__gt=timezone.now())
template = "admin/core/accounts/orcid_registration.html"
context = {
"token": token,
}
return render(request, template, context)
def activate_account(request, token):
"""
Activates a user account if an Account object with the
matching token is found and is not already active.
:param request: HttpRequest object
:param token: string, Account.confirmation_token
:return: HttpResponse object
"""
next_url = request.GET.get("next", "")
try:
account = models.Account.objects.get(confirmation_code=token, is_active=False)
except models.Account.DoesNotExist:
account = None
if account and request.method == "POST":
account.is_active = True
account.confirmation_code = None
account.save()
messages.add_message(
request,
messages.SUCCESS,
_("Account activated"),
)
return redirect(logic.reverse_with_next("core_login", next_url))
template = "admin/core/accounts/activate_account.html"
context = {
"account": account,
}
return render(request, template, context)
@login_required
def edit_profile(request):
"""
Allows a user to edit their own profile, reset their password or change their email address.
:param request: HttpRequest object
:return: HttpResponse object
"""
user = request.user
form = forms.EditAccountForm(instance=user)
send_reader_notifications = False
next_url = request.GET.get("next", "")
if request.journal:
send_reader_notifications = setting_handler.get_setting(
"notifications", "send_reader_notifications", request.journal
).value
if user.staffgroupmember_set.first():
staff_group_membership_form = press_forms.StaffGroupMemberForm(
instance=user.staffgroupmember_set.first()
)
else:
staff_group_membership_form = None
if request.POST:
if "email" in request.POST:
email_address = request.POST.get("email_address")
try:
validate_email(email_address)
try:
next_url = reverse("core_edit_profile")
logic.handle_email_change(request, email_address, next_url=next_url)
return redirect(reverse("website_index"))
except IntegrityError:
messages.add_message(
request,
messages.WARNING,
_("An account with that email address already exists."),
)
except ValidationError:
messages.add_message(
request,
messages.WARNING,
_("Email address is not valid."),
)
elif "change_password" in request.POST:
old_password = request.POST.get("current_password")
new_pass_one = request.POST.get("new_password_one")
new_pass_two = request.POST.get("new_password_two")
if old_password and request.user.check_password(old_password):
if new_pass_one == new_pass_two:
problems = request.user.password_policy_check(request, new_pass_one)
if not problems:
request.user.set_password(new_pass_one)
request.user.save()
messages.add_message(
request, messages.SUCCESS, _("Password updated.")
)
else:
[
messages.add_message(request, messages.INFO, problem)
for problem in problems
]
else:
messages.add_message(
request, messages.WARNING, _("Passwords do not match")
)
else:
messages.add_message(
request, messages.WARNING, _("Old password is not correct.")
)
elif "subscribe" in request.POST and send_reader_notifications:
request.user.add_account_role(
"reader",
request.journal,
)
messages.add_message(
request,
messages.SUCCESS,
_("Successfully subscribed to article notifications."),
)
elif "unsubscribe" in request.POST and send_reader_notifications:
request.user.remove_account_role("reader", request.journal)
messages.add_message(
request,
messages.SUCCESS,
_("Successfully unsubscribed from article notifications."),
)
elif "edit_profile" in request.POST:
form = forms.EditAccountForm(request.POST, request.FILES, instance=user)
if form.is_valid():
form.save()
messages.add_message(request, messages.SUCCESS, "Profile updated.")
if next_url:
return redirect(next_url)
else:
return redirect(reverse("core_edit_profile"))
elif "edit_staff_member_info" in request.POST:
form = press_forms.StaffGroupMemberForm(
request.POST, instance=user.staffgroupmember_set.first()
)
if form.is_valid():
form.save()
messages.add_message(
request, messages.SUCCESS, "Staff member info updated."
)
if next_url:
return redirect(next_url)
else:
return redirect(reverse("core_edit_profile"))
elif "export" in request.POST:
return logic.export_gdpr_user_profile(user)
template = "admin/core/accounts/edit_profile.html"
context = {
"form": form,
"staff_group_membership_form": staff_group_membership_form,
"user_to_edit": user,
"send_reader_notifications": send_reader_notifications,
"user_is_reader": user.is_reader(request),
}
return render(request, template, context)
def public_profile(request, uuid):
"""
A page that displays a user's public profile if they have enabled display
:param request: django HTTPRequest object
:param uuid: a uuid4 string
:return: HTTPResponse
"""
user = get_object_or_404(
models.Account,
uuid=uuid,
is_active=True,
enable_public_profile=True,
)
template = "core/accounts/public_profile.html"
context = {
"user": user,
}
if request.journal:
context["editorial_groups"] = user.editorialgroupmember_set.filter(
group__journal=request.journal
)
context["roles"] = models.AccountRole.objects.filter(
user=user,
journal=request.journal,
)
if not context["roles"]:
raise Http404()
elif request.press:
context["editorial_groups"] = user.editorialgroupmember_set.filter(
group__press=request.press,
group__journal__isnull=True,
)
context["staff_groups"] = user.staffgroupmember_set.all()
return render(request, template, context)
@login_required
def affiliation_update_from_orcid(request, how_many="primary"):
"""
Allows a user to update their own affiliations
from public ORCID records.
:param request: HttpRequest object
:return: HttpResponse object
"""
next_url = request.GET.get("next", "")
try:
cleaned_orcid = clean_orcid_id(request.user.orcid)
except ValueError:
cleaned_orcid = None
if not cleaned_orcid:
messages.add_message(
request,
messages.WARNING,
_(
"Your account does not have an ORCID. "
"Please log in with ORCID and try again."
),
)
if next_url:
return redirect(next_url)
else:
return redirect(reverse("core_edit_profile"))
orcid_details = orcid.get_orcid_record_details(cleaned_orcid)
orcid_affils = orcid_details.get("affiliations", [])
if not orcid_affils:
messages.add_message(
request,
messages.WARNING,
_(
"No affiliations were found on your public ORCID record "
"for ID %(orcid_id)s. "
"Please update your affiliations on orcid.org and try again."
)
% {"orcid_id": cleaned_orcid},
)
if next_url:
return redirect(next_url)
else:
return redirect(reverse("core_edit_profile"))
form = forms.ConfirmDeleteForm()
new_affils = []
if how_many == "primary":
orcid_affils = orcid_affils[:1]
for orcid_affil in orcid_affils:
orcid_affil_form = forms.OrcidAffiliationForm(
orcid_affil,
tzinfo=request.user.preferred_timezone,
data={"account": request.user},
)
if orcid_affil_form.is_valid():
new_affils.append(orcid_affil_form.save(commit=False))
if request.method == "POST":
form = forms.ConfirmDeleteForm(request.POST)
if form.is_valid():
request.user.affiliations.delete()
for affil in new_affils:
affil.save()
messages.add_message(
request,
messages.SUCCESS,
_("Affiliations updated."),
)
if next_url:
return redirect(next_url)
else:
return redirect(reverse("core_edit_profile"))
template = "admin/core/affiliation_update_from_orcid.html"
context = {
"account": request.user,
"form": form,
"old_affils": request.user.affiliations,
"new_affils": new_affils,
}
return render(request, template, context)
@has_journal
@login_required
def dashboard(request):
"""
Displays a dashboard for authenticated users.
:param request: HttpRequest object
:return: HttpResponse object
"""
template = "core/dashboard.html"
new_proofing, active_proofing, completed_proofing = proofing_logic.get_tasks(
request
)
(
new_proofing_typesetting,
active_proofing_typesetting,
completed_proofing_typesetting,
) = proofing_logic.get_typesetting_tasks(request)
section_editor_articles = review_models.EditorAssignment.objects.filter(
editor=request.user,
editor_type="section-editor",
article__journal=request.journal,
)
# TODO: Move most of this to model logic.
context = {
"new_proofing": new_proofing.count(),
"active_proofing": active_proofing.count(),
"completed_proofing": completed_proofing.count(),
"new_proofing_typesetting": new_proofing_typesetting.count(),
"completed_proofing_typesetting": completed_proofing_typesetting.count(),
"active_proofing_typesetting": active_proofing_typesetting.count(),
"unassigned_articles_count": submission_models.Article.objects.filter(
stage=submission_models.STAGE_UNASSIGNED, journal=request.journal
).count(),
"assigned_articles_count": submission_models.Article.objects.filter(
Q(stage=submission_models.STAGE_ASSIGNED)
| Q(stage=submission_models.STAGE_UNDER_REVIEW)
| Q(stage=submission_models.STAGE_UNDER_REVISION),
journal=request.journal,
).count(),
"editing_articles_count": submission_models.Article.objects.filter(
Q(stage=submission_models.STAGE_EDITOR_COPYEDITING)
| Q(stage=submission_models.STAGE_AUTHOR_COPYEDITING)
| Q(stage=submission_models.STAGE_FINAL_COPYEDITING),
journal=request.journal,
).count(),
"production_articles_count": submission_models.Article.objects.filter(
Q(stage=submission_models.STAGE_TYPESETTING), journal=request.journal
).count(),
"proofing_articles_count": submission_models.Article.objects.filter(
Q(stage=submission_models.STAGE_PROOFING), journal=request.journal
).count(),
"prepub_articles_count": submission_models.Article.objects.filter(
Q(stage=submission_models.STAGE_READY_FOR_PUBLICATION),
journal=request.journal,
).count(),
"is_editor": request.user.is_editor(request),
"is_author": request.user.is_author(request),
"is_reviewer": request.user.is_reviewer(request),
"section_editor_articles": section_editor_articles,
"active_submission_count": submission_models.Article.objects.filter(
owner=request.user, journal=request.journal
)
.exclude(stage=submission_models.STAGE_UNSUBMITTED)
.count(),
"in_progress_submission_count": submission_models.Article.objects.filter(
owner=request.user,
journal=request.journal,
stage=submission_models.STAGE_UNSUBMITTED,
).count(),
"assigned_articles_for_user_review_count": review_models.ReviewAssignment.objects.filter(
Q(is_complete=False)
& Q(reviewer=request.user)
& Q(article__stage=submission_models.STAGE_UNDER_REVIEW)
& Q(date_accepted__isnull=True),
article__journal=request.journal,
).count(),
"assigned_articles_for_user_review_accepted_count": review_models.ReviewAssignment.objects.filter(
Q(is_complete=False)
& Q(reviewer=request.user)
& Q(article__stage=submission_models.STAGE_UNDER_REVIEW)
& Q(date_accepted__isnull=False),
article__journal=request.journal,
).count(),
"assigned_articles_for_user_review_completed_count": review_models.ReviewAssignment.objects.filter(
Q(is_complete=True)
& Q(reviewer=request.user)
& Q(date_declined__isnull=True),
article__journal=request.journal,
).count(),
"copyeditor_requests": copyedit_models.CopyeditAssignment.objects.filter(
Q(copyeditor=request.user)
& Q(decision__isnull=True)
& Q(copyedit_reopened__isnull=True),
article__journal=request.journal,
).count(),
"copyeditor_accepted_requests": copyedit_models.CopyeditAssignment.objects.filter(
Q(
copyeditor=request.user,
decision="accept",
copyeditor_completed__isnull=True,
article__journal=request.journal,
)
| Q(
copyeditor=request.user,
decision="accept",
copyeditor_completed__isnull=False,
article__journal=request.journal,
copyedit_reopened__isnull=False,
copyedit_reopened_complete__isnull=True,
)
).count(),
"copyeditor_completed_requests": copyedit_models.CopyeditAssignment.objects.filter(
(Q(copyeditor=request.user) & Q(copyeditor_completed__isnull=False))
| (
Q(copyeditor=request.user)
& Q(copyeditor_completed__isnull=False)
& Q(copyedit_reopened_complete__isnull=False)
),
article__journal=request.journal,
).count(),
"typeset_tasks": production_models.TypesetTask.active_objects.filter(
assignment__article__journal=request.journal,
accepted__isnull=True,
completed__isnull=True,
typesetter=request.user,
).count(),
"typeset_in_progress_tasks": production_models.TypesetTask.active_objects.filter(
assignment__article__journal=request.journal,
accepted__isnull=False,
completed__isnull=True,
typesetter=request.user,
).count(),
"typeset_completed_tasks": production_models.TypesetTask.active_objects.filter(
assignment__article__journal=request.journal,
accepted__isnull=False,
completed__isnull=False,
typesetter=request.user,
).count(),
"active_submissions": submission_models.Article.objects.filter(
owner=request.user, journal=request.journal
)
.exclude(
stage__in=[
submission_models.STAGE_UNSUBMITTED,
submission_models.STAGE_PUBLISHED,
],
)
.order_by("-date_submitted"),
"published_submissions": submission_models.Article.objects.filter(
frozenauthor__author=request.user,
journal=request.journal,
stage=submission_models.STAGE_PUBLISHED,
).order_by("-date_published"),
"progress_submissions": submission_models.Article.objects.filter(
journal=request.journal,
owner=request.user,
stage=submission_models.STAGE_UNSUBMITTED,
).order_by("-date_started"),
"workflow_elements": workflow.element_names(
request.journal.workflow().elements.all()
),
"workflow_element_url": request.GET.get("workflow_element_url", False),
}
return render(request, template, context)
@has_journal
@any_editor_user_required
def active_submissions(request):
template = "core/active_submissions.html"
active_submissions = (
submission_models.Article.active_objects.exclude(
stage=submission_models.STAGE_PUBLISHED,
)
.filter(journal=request.journal)
.order_by("pk", "title")
)
if not request.user.is_editor(request) and request.user.is_section_editor(request):
active_submissions = logic.filter_articles_to_editor_assigned(
request, active_submissions
)
context = {
"active_submissions": active_submissions,
"sections": submission_models.Section.objects.filter(
is_filterable=True, journal=request.journal
),
"workflow_element_url": request.GET.get("workflow_element_url", False),
}
return render(request, template, context)
@has_journal
@any_editor_user_required
def active_submission_filter(request):
articles = logic.build_submission_list(request)
html = ""