Coverage for portality/view/account.py: 48%
400 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 13:43 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 13:43 +0000
1import uuid, json
2import random
4from flask import Blueprint, request, url_for, flash, redirect, make_response, g, current_app
5from flask import render_template, abort
6from flask_login import login_user, logout_user, current_user, login_required
7from wtforms import StringField, HiddenField, PasswordField, DecimalField, validators, Form, SelectMultipleField
9from portality import util
10from portality import constants
11from portality.core import app
12from portality.datasets import language_options, country_options
13from portality.decorators import ssl_required, write_required
14from portality.models import Account, Event
15from portality.forms.validate import DataOptional, EmailAvailable, ReservedUsernames, IdAvailable, IgnoreUnchanged, \
16 CurrentISOLanguage
17from portality.bll import DOAJ
18from portality.bll import exceptions as bll_exc
19from portality.ui.messages import Messages
21from portality.ui import templates
23blueprint = Blueprint('account', __name__)
25@blueprint.url_value_preprocessor
26def pull_lang(endpoint, values):
27 # Remove 'lang' so it is not passed to the view function, but keep it
28 # around so url_for can still fill it in when building urls for
29 # endpoints (eg .forgot) that require it, since it's otherwise lost
30 # from request.view_args once popped below.
31 if values:
32 lang = values.pop('lang', None)
33 if lang:
34 # store the active language on the flask.g so url_defaults can access it
35 g.lang = lang
37@blueprint.url_defaults
38def add_lang(endpoint, values):
39 """Ensure that url_for() populates the 'lang' value for this blueprint when generating URLs.
41 If a language has been set on g (by pull_lang) then default the 'lang' for generated URLs
42 to that value so callers don't need to explicitly pass it.
43 """
44 if 'lang' not in values and current_app.url_map.is_endpoint_expecting(endpoint, 'lang'):
45 lang = getattr(g, 'lang', None)
46 if lang:
47 values.setdefault('lang', lang)
49class RedirectForm(Form):
50 next = HiddenField()
52 def __init__(self, *args, **kwargs):
53 Form.__init__(self, *args, **kwargs)
54 if not self.next.data:
55 self.next.data = get_redirect_target() or ''
57 def redirect(self, endpoint='index', **values):
58 if self.next.data == util.is_safe_url(self.next.data):
59 return redirect(self.next.data)
60 target = get_redirect_target()
61 return redirect(target or url_for(endpoint, **values))
63@blueprint.route('/')
64@login_required
65@ssl_required
66def index():
67 if not current_user.has_role("list_users"):
68 abort(401)
69 return render_template(templates.USER_LIST)
71class UserEditForm(Form):
73 # Let's not allow anyone to change IDs - there lies madness and destruction (referential integrity)
74 # id = StringField('ID', [IgnoreUnchanged(), ReservedUsernames(), IdAvailable()])
76 name = StringField('Account name', [DataOptional(), validators.Length(min=3, max=64)])
77 email = StringField('Email address', [
78 IgnoreUnchanged(),
79 validators.Length(min=3, max=254),
80 validators.Email(message='Must be a valid email address'),
81 EmailAvailable(),
82 validators.EqualTo('email_confirm', message='Email confirmation must match'),
83 ])
84 email_confirm = StringField('Confirm email address')
85 roles = StringField('User roles')
86 attribute_workflow = SelectMultipleField(
87 "Workflow Participation",
88 choices=[(x,x) for x in constants.EWF__ALL_STAGES]
89 )
90 attribute_language = SelectMultipleField(
91 'Can Review Languages',
92 [
93 CurrentISOLanguage()
94 ],
95 choices=language_options
96 )
97 attribute_country = SelectMultipleField(
98 'Can Review Applications from Countries',
99 choices=country_options
100 )
101 attribute_tag = StringField('Other User Attributes')
102 password_change = PasswordField('Change password', [
103 validators.EqualTo('password_confirm', message='Passwords must match'),
104 ])
105 password_confirm = PasswordField('Confirm password')
107class RegisterForm(RedirectForm):
108 identifier = StringField('ID', [ReservedUsernames(), IdAvailable()])
109 name = StringField('Name', [validators.Optional(), validators.Length(min=3, max=64)])
110 sender_email = StringField('Email address', [
111 validators.DataRequired(),
112 validators.Length(min=3, max=254),
113 validators.Email(message='Must be a valid email address'),
114 EmailAvailable(message="That email address is already in use. Please <a href='/account/forgot'>reset your password</a>. If you still cannot login, <a href='/contact'>contact us</a>.")
115 ])
116 roles = StringField('Roles')
117 # These are honeypot (bot-trap) fields
118 email = StringField('email')
119 hptimer = DecimalField('hptimer', [validators.Optional()])
121 def is_bot(self):
122 """
123 Checks honeypot fields and determines whether the form was submitted by a bot
124 :return: True, if bot suspected; False, if human
125 """
126 return self.email.data != "" or self.hptimer.data is None or self.hptimer.data < app.config.get("HONEYPOT_TIMER_THRESHOLD", 5000)
129@blueprint.route('/<username>', methods=['GET', 'POST', 'DELETE'])
130@login_required
131@ssl_required
132@write_required()
133def username(username):
134 acc = Account.pull(username)
136 template = templates.PUBLIC_EDIT_USER
137 if current_user.is_super:
138 template = templates.ADMIN_EDIT_USER
139 elif current_user.has_role(constants.ROLE_ASSOCIATE_EDITOR) or current_user.has_role(constants.ROLE_EDITOR):
140 template = templates.EDITOR_EDIT_USER
142 if acc is None:
143 abort(404)
144 if (request.method == 'DELETE' or
145 (request.method == 'POST' and request.values.get('submit', False) == 'Delete')):
146 if current_user.id != acc.id and not current_user.is_super:
147 abort(401)
148 else:
149 conf = request.values.get("delete_confirm")
150 if conf is None or conf != "delete_confirm":
151 Messages.flash(Messages.ACCOUNT__CONFIRM_CHECKBOX_REQUIRED)
152 return render_template(template, account=acc, form=UserEditForm(obj=acc))
153 acc.delete()
154 Messages.flash(Messages.ACCOUNT__DELETED.format(id=acc.id))
155 return redirect(url_for('.index'))
157 elif request.method == 'POST':
158 if current_user.id != acc.id and not current_user.is_super:
159 abort(401)
161 form = UserEditForm(obj=acc, formdata=request.form)
163 if not form.validate():
164 return render_template(template, account=acc, form=form)
166 newdata = request.values
167 try:
168 newdata = request.json
169 except:
170 pass
172 # newdata = request.json if request.json else request.values
173 if request.values.get('submit', False) == 'Generate a new API Key':
174 acc.generate_api_key()
176 if 'name' in newdata:
177 acc.set_name(newdata['name'])
178 if 'password_change' in newdata and len(newdata['password_change']) > 0 and not newdata['password_change'].startswith('sha1'):
179 acc.set_password(newdata['password_change'])
181 # only super users can re-write roles and attributes
182 if current_user.is_super:
183 if "roles" in newdata:
184 new_roles = [r.strip() for r in newdata.get("roles").split(",")]
185 acc.set_role(new_roles)
187 # remove old attributes
188 del acc.attributes
190 # apply new attributes
191 if hasattr(form, "attribute_workflow") and form.attribute_workflow.data:
192 for aw in form.attribute_workflow.data:
193 acc.add_attribute(constants.USER_ATTR__WORKFLOW, aw)
194 if hasattr(form, "attribute_language") and form.attribute_language.data:
195 for al in form.attribute_language.data:
196 acc.add_attribute(constants.USER_ATTR__LANGUAGE, al)
197 if hasattr(form, "attribute_country") and form.attribute_country.data:
198 for ac in form.attribute_country.data:
199 acc.add_attribute(constants.USER_ATTR__COUNTRY, ac)
200 if "attribute_tag" in newdata:
201 for at in newdata["attribute_tag"].split(","):
202 acc.add_attribute(constants.USER_ATTR__TAG, at.strip())
205 if "marketing_consent" in newdata:
206 acc.set_marketing_consent(newdata["marketing_consent"] == "true")
208 if 'email' in newdata and len(newdata['email']) > 0 and newdata['email'] != acc.email:
209 acc.set_email(newdata['email'])
211 # If the user updated their own email address, invalidate the password and require verification again.
212 if current_user.id == acc.id:
213 acc.clear_password()
214 reset_token = uuid.uuid4().hex
215 acc.set_reset_token(reset_token, app.config.get("PASSWORD_RESET_TIMEOUT", 86400))
216 acc.save()
218 events_svc = DOAJ.eventsService()
219 events_svc.trigger(Event(constants.EVENT_ACCOUNT_PASSWORD_RESET, acc.id, context={"account" : acc.data}))
220 Messages.flash(Messages.ACCOUNT__EMAIL_UPDATED_LOGGED_OUT)
222 logout_user()
224 if app.config.get('DEBUG', False):
225 reset_url = url_for('account.reset', reset_token=acc.reset_token)
226 util.flash_with_url('Debug mode - url for reset is <a href={0}>{0}</a>'.format(reset_url))
228 return redirect(url_for('doaj.home'))
230 acc.save()
231 Messages.flash(Messages.ACCOUNT__RECORD_UPDATED)
232 return render_template(template, account=acc, form=form)
234 else: # GET
235 if util.request_wants_json():
236 resp = make_response(
237 json.dumps(acc.data, sort_keys=True, indent=4))
238 resp.mimetype = "application/json"
239 return resp
240 else:
241 form = UserEditForm(obj=acc)
242 return render_template(template, account=acc, form=form)
245def get_redirect_target(form=None, acc=None):
246 form_target = ''
247 if form and hasattr(form, 'next') and getattr(form, 'next'):
248 form_target = form.next.data
250 for target in form_target, request.args.get('next', []):
251 if not target:
252 continue
253 if target == util.is_safe_url(target):
254 return target
256 if acc is None:
257 return ""
259 destinations = app.config.get("ROLE_LOGIN_DESTINATIONS")
260 for role, dest in destinations:
261 if acc.has_role(role):
262 return url_for(dest)
264 return url_for(app.config.get("DEFAULT_LOGIN_DESTINATION"))
267class LoginForm(RedirectForm):
268 user = StringField('Email address or username', [validators.DataRequired()])
269 password = PasswordField('Password', [validators.Optional()])
270 action = StringField('Action', [validators.DataRequired()])
273class LoginCodeForm(RedirectForm):
274 code = StringField('Code', [validators.DataRequired()])
275 user = HiddenField('User')
277def _get_param(param_name):
278 """Get parameter value from either GET or POST request"""
279 return request.args.get(param_name) or request.form.get(param_name)
281def _complete_verification(account):
282 """Complete the verification process and log in the user"""
283 account.remove_login_code()
284 account.save()
285 login_user(account, remember=True)
288def get_wait_period(secs: int) -> str:
289 secs = int(secs or 0)
290 if secs >= 7200:
291 return f"{(secs + 3599) // 3600} hours"
292 if secs >= 3600:
293 return "1 hour"
294 if secs >= 120:
295 return f"{(secs + 59) // 60} minutes"
296 if secs >= 60:
297 return "1 minute"
298 return f"{secs} seconds"
301def _handle_pwless_login(user, form, redirected: str = ""):
302 """ Handler for passwordless login backoff + email sending.
304 Returns a rendered verify_code template with appropriate resend_wait.
305 """
306 cps = DOAJ.concurrencyPreventionService()
307 allowed, wait_remaining, interval = cps.record_pwless_resend(user.email)
309 if not allowed:
310 tpl = Messages.ACCOUNT__PWLESS__RESEND_RATE_LIMIT
311 Messages.flash((tpl[0].format(wait=get_wait_period(wait_remaining)), tpl[1]))
312 return render_template(templates.LOGIN_VERIFY_CODE, email=user.email, form=form, resend_wait=wait_remaining)
314 try:
315 svc = DOAJ.accountService()
316 code = svc.initiate_login_code(user)
317 login_url = svc.send_login_code_email(user, code, redirected or "", next_url=form.next.data or "")
318 Messages.flash(Messages.ACCOUNT__PWLESS__EMAIL_SENT)
320 if app.config.get('DEBUG', False):
321 util.flash_with_url('Debug mode - url for login link is <a href={0}>{0}</a>'.format(login_url))
322 except bll_exc.ArgumentException:
323 Messages.flash(Messages.ACCOUNT__PWLESS__EMAIL_ERROR)
325 return render_template(templates.LOGIN_VERIFY_CODE, email=user.email, form=form, resend_wait=interval)
327@blueprint.route('/verify-code', methods=['GET', 'POST'])
328def verify_code():
329 form = LoginForm(request.form, csrf_enabled=False)
331 # Handle resend requests posted from the code entry page
332 if request.method == 'POST' and (request.form.get('action') == 'resend'):
333 email = _get_param('email')
334 if not email:
335 Messages.flash(Messages.ACCOUNT__EMAIL_REQUIRED_FOR_RESEND)
336 return redirect(url_for('account.login'))
338 user = Account.pull_by_email(email)
339 if not user:
340 Messages.flash(Messages.ACCOUNT__NOT_RECOGNISED)
341 return redirect(url_for('account.login'))
343 return _handle_pwless_login(user, form, _get_param('redirected') or '')
345 svc = DOAJ.accountService()
347 try:
348 account, _redirected, _next = svc.verify_login_code(
349 encrypted_token=_get_param('token'),
350 email=_get_param('email'),
351 code=_get_param('code'),
352 )
353 except bll_exc.ArgumentException:
354 Messages.flash(Messages.ACCOUNT__REQUIRED_PARAMS_NOT_AVAILABLE)
355 return redirect(url_for('account.login'))
356 except bll_exc.NoSuchObjectException:
357 Messages.flash(Messages.ACCOUNT__NOT_RECOGNISED)
358 return redirect(url_for('account.login'))
359 except bll_exc.IllegalStatusException:
360 Messages.flash(Messages.ACCOUNT__INVALID_OR_EXPIRED_CODE)
361 return redirect(url_for('account.login'))
363 # Preserve existing UI behavior for application redirect
364 redirected_page = request.args.get("redirected") or _redirected
365 if redirected_page == "apply":
366 form['next'].data = url_for("apply.public_application")
367 elif _next:
368 # next target carried in the emailed login link token; get_redirect_target checks it's safe
369 form['next'].data = _next
371 _complete_verification(account)
372 return redirect(get_redirect_target(form=form, acc=account))
376class ResetForm(Form):
377 password = PasswordField('Password', [
378 validators.DataRequired(),
379 validators.EqualTo('confirm', message='Passwords must match')
380 ])
381 confirm = PasswordField('Repeat Password')
383def get_user_account(username):
384 # If our settings allow, try getting the user account by ID first, then by email address
385 if app.config.get('LOGIN_VIA_ACCOUNT_ID', False):
386 return Account.pull(username) or Account.pull_by_email(username)
387 return Account.pull_by_email(username)
390def handle_login_code_request(user, form):
391 LOGIN_CODE_LENGTH = 6
392 LOGIN_CODE_TIMEOUT = 600 # 10 minutes
394 code = ''.join(str(random.randint(0, 9)) for _ in range(LOGIN_CODE_LENGTH))
395 user.set_login_code(code, timeout=LOGIN_CODE_TIMEOUT)
396 user.save()
398 svc = DOAJ.accountService()
399 svc.send_login_code_email(user, code, request.args.get("redirected", ""))
400 Messages.flash(Messages.ACCOUNT__PWLESS__EMAIL_SENT)
402 return render_template(templates.LOGIN_VERIFY_CODE, email=user.email, form=form)
404def handle_password_login(user, form):
405 if user.check_password(form.password.data):
406 login_user(user, remember=True)
407 Messages.flash(Messages.ACCOUNT__WELCOME_BACK)
408 return redirect(get_redirect_target(form=form, acc=user))
409 else:
410 forgot_url = url_for(".forgot")
411 form.password.errors.append(
412 f'The password you entered is incorrect. Try again or <a href="{forgot_url}">reset your password</a>.'
413 )
415def handle_incomplete_verification():
416 forgot_url = url_for('.forgot')
417 forgot_instructions = f'<a href="{forgot_url}"><click here></a> to send a new reset link.'
418 util.flash_with_url(
419 'Account verification is incomplete. Check your emails for the link or ' + forgot_instructions,
420 'error'
421 )
423def handle_login_template_rendering(form):
424 if request.args.get("redirected") == "apply":
425 form['next'].data = url_for("apply.public_application")
426 return render_template(templates.LOGIN_TO_APPLY, form=form)
427 return render_template(templates.GLOBAL_LOGIN, form=form)
429@blueprint.route('/login', methods=['GET', 'POST'])
430@ssl_required
431def login():
432 current_info = {'next': request.args.get('next', '')}
433 form = LoginForm(request.form, csrf_enabled=False, **current_info)
434 if request.method == 'POST' and form.validate():
435 username = form.user.data
436 action = request.form.get('action')
438 svc = DOAJ.accountService()
439 try:
440 user = svc.resolve_user(username)
441 if user is None:
442 raise bll_exc.NoSuchObjectException()
444 if action == 'get_link':
445 return _handle_pwless_login(user, form, request.args.get("redirected", ""))
447 elif action == 'password_login':
448 account = svc.verify_password_login(user, form.password.data)
449 login_user(account, remember=True)
450 Messages.flash(Messages.ACCOUNT__WELCOME_BACK)
451 return redirect(get_redirect_target(form=form, acc=account))
453 else:
454 # Unknown action
455 raise bll_exc.ArgumentException("Unknown login action")
457 except bll_exc.NoSuchObjectException:
458 form.user.errors.append('Account not recognised. If you entered an email address, try your username instead.')
459 except bll_exc.IllegalStatusException as e:
460 msg = str(e) if e.args else ""
461 if msg == 'incomplete_verification':
462 handle_incomplete_verification()
463 return redirect(url_for('doaj.home'))
464 elif msg == 'incorrect_password':
465 forgot_url = url_for(".forgot")
466 form.password.errors.append(
467 f'The password you entered is incorrect. Try again or <a href="{forgot_url}">reset your password</a>.'
468 )
469 else:
470 # Generic illegal status
471 Messages.flash(Messages.ACCOUNT__STATUS_LOGIN_FAILED)
472 except bll_exc.ArgumentException:
473 Messages.flash(Messages.ACCOUNT__REQUEST_PROBLEM)
475 return handle_login_template_rendering(form)
477@blueprint.route('/forgot', methods=['GET', 'POST'])
478@ssl_required
479@write_required()
480def forgot():
481 CONTACT_INSTR = ' Please <a href="{url}">contact us.</a>'.format(url=url_for('doaj.contact'))
482 if request.method == 'POST':
483 # get hold of the user account
484 un = request.form.get('un', "")
485 if app.config.get('LOGIN_VIA_ACCOUNT_ID', False):
486 account = Account.pull(un) or Account.pull_by_email(un)
487 else:
488 account = Account.pull_by_email(un)
490 if account is None:
491 util.flash_with_url('Error - your account username / email address is not recognised.' + CONTACT_INSTR,
492 'error')
493 return render_template(templates.FORGOT_PASSWORD)
495 if not account.data.get('email'):
496 util.flash_with_url('Error - your account does not have an associated email address.' + CONTACT_INSTR,
497 'error')
498 return render_template(templates.FORGOT_PASSWORD)
500 # if we get to here, we have a user account to reset
501 reset_token = uuid.uuid4().hex
502 account.set_reset_token(reset_token, app.config.get("PASSWORD_RESET_TIMEOUT", 86400))
503 account.save()
505 events_svc = DOAJ.eventsService()
506 events_svc.trigger(Event(constants.EVENT_ACCOUNT_PASSWORD_RESET, account.id, context={"account": account.data}))
507 Messages.flash(Messages.ACCOUNT__RESET_EMAIL_SENT)
509 if app.config.get('DEBUG', False):
510 util.flash_with_url('Debug mode - url for reset is <a href={0}>{0}</a>'.format(
511 url_for('account.reset', reset_token=account.reset_token)))
513 return render_template(templates.FORGOT_PASSWORD)
516@blueprint.route("/reset/<reset_token>", methods=["GET", "POST"])
517@ssl_required
518@write_required()
519def reset(reset_token):
520 form = ResetForm(request.form, csrf_enabled=False)
521 account = Account.get_by_reset_token(reset_token)
522 if account is None:
523 abort(404)
525 if request.method == "POST" and form.validate():
526 # check that the passwords match, and bounce if not
527 pw = request.values.get("password")
528 conf = request.values.get("confirm")
529 if pw != conf:
530 Messages.flash(Messages.ACCOUNT__PASSWORDS_NOT_MATCH)
531 return render_template(templates.RESET_PASSWORD, account=account, form=form)
533 # update the user's account
534 account.set_password(pw)
535 account.remove_reset_token()
536 account.save()
537 Messages.flash(Messages.ACCOUNT__PASSWORD_SET_AND_LOGGED_IN)
539 # log the user in
540 login_user(account, remember=True)
541 return redirect(url_for('doaj.home'))
543 return render_template(templates.RESET_PASSWORD, account=account, form=form)
546@blueprint.route('/logout', methods=['POST'])
547@ssl_required
548def logout():
549 logout_user()
550 Messages.flash(Messages.ACCOUNT__LOGGED_OUT)
551 return redirect('/')
553@blueprint.route('/register', methods=['GET', 'POST'])
554@ssl_required
555@write_required()
556def register(template=templates.REGISTER):
557 # ~~-> Honeypot:Feature ~~
558 # 3rd-party registration only for those with create_user role, only allow public registration when configured
559 if current_user.is_authenticated and not current_user.has_role("create_user") \
560 or current_user.is_anonymous and app.config.get('PUBLIC_REGISTER', False) is False:
561 abort(401) # todo: we may need a template to explain this since it's linked from the application form
563 form = RegisterForm(request.form, csrf_enabled=False,
564 roles=",".join(app.config.get("DEFAULT_REGISTER_ROLES", [])),
565 identifier=Account.new_short_uuid())
567 if request.method == 'POST':
569 if not current_user.is_authenticated and form.is_bot():
570 flash(Messages.ARE_YOU_A_HUMAN, "error")
571 return render_template(template, form=form)
573 if form.validate():
574 account = Account.make_account(email=form.sender_email.data, username=form.identifier.data, name=form.name.data)
575 if current_user.is_authenticated and current_user.has_role(constants.ROLE_ADMIN):
576 roles = [r.strip() for r in form.roles.data.split(',')]
577 for r in roles:
578 account.add_role(r)
579 else:
580 # for all accounts, add the default roles
581 default_roles = app.config.get("DEFAULT_REGISTER_ROLES", [])
582 for role in default_roles:
583 account.add_role(role)
586 account.save()
588 event_svc = DOAJ.eventsService()
589 event_svc.trigger(Event(constants.EVENT_ACCOUNT_CREATED, account.id, context={"account" : account.data}))
590 # send_account_created_email(account)
592 if app.config.get('DEBUG', False):
593 util.flash_with_url('Debug mode - url for verify is <a href={0}>{0}</a>'.format(url_for('account.reset', reset_token=account.reset_token)))
595 if current_user.is_authenticated:
596 util.flash_with_url('Account created for {0}. View Account: <a href={1}>{1}</a>'.format(account.email, url_for('.username', username=account.id)))
597 return redirect(url_for('.index'))
598 else:
599 tpl = Messages.ACCOUNT__VERIFY_EMAIL_TO_SET_PASSWORD
600 Messages.flash((tpl[0].format(email=form.sender_email.data), tpl[1]))
602 # We must redirect home because the user now needs to verify their email address.
603 return redirect(url_for('doaj.home'))
604 else:
605 Messages.flash(Messages.ACCOUNT__PLEASE_CORRECT_ERRORS)
607 return render_template(template, form=form)
609@blueprint.route('/create/', methods=['GET', 'POST'])
610@write_required()
611@login_required
612def create():
613 if not current_user.has_role(constants.ROLE_ADMIN):
614 abort(404)
615 return register(template=templates.CREATE_USER)