def authenticate_user_if_possible(csrf_token, request, response, state, user, _): """This signs the user in. """ if state.get('etag'): return db = state['website'].db if not db: return # Try to authenticate the user # We want to try cookie auth first, but we want password and email auth to # supersede it. session_p = None if SESSION in request.headers.cookie: creds = request.headers.cookie[SESSION].value.split(':', 2) if len(creds) == 2: creds = [creds[0], 1, creds[1]] if len(creds) == 3: session_p, state[ 'session_status'] = Participant.authenticate_with_session( *creds, allow_downgrade=True, cookies=response.headers.cookie) if session_p: user = state['user'] = session_p p = None session_suffix = '' redirect = False redirect_url = None if request.method == 'POST': # Form auth body = _get_body(request) if body: redirect = body.get('form.repost', None) != 'true' redirect_url = body.get('sign-in.back-to') # Remove email address from blacklist if requested email_address = body.pop('email.unblacklist', None) if email_address: remove_email_address_from_blacklist(email_address, user, request) # Proceed with form auth carry_on = body.pop('log-in.carry-on', None) if carry_on: can_carry_on = (session_p is not None and session_p.session_type != 'ro' and session_p.get_email_address() == carry_on) if not can_carry_on: state['log-in.carry-on'] = carry_on raise LoginRequired else: p = sign_in_with_form_data(body, state) if p: if not p.session: session_suffix = '.pw' # stands for "password" else: redirect = False elif request.method == 'GET': if request.qs.get('log-in.id') or request.qs.get('email.id'): # Prevent email software from messing up an email log-in or confirmation # with a single GET request. Also, show a proper warning to someone trying # to log in while cookies are disabled. require_cookie(state) if request.qs.get('log-in.id'): # Email auth id = request.qs.get_int('log-in.id') session_id = request.qs.get('log-in.key') if not session_id or session_id < '1001' or session_id > '1010': raise response.render('simplates/log-in-link-is-invalid.spt', state) token = request.qs.get('log-in.token') if not (token and token.endswith('.em')): raise response.render('simplates/log-in-link-is-invalid.spt', state) required = request.qs.parse_boolean('log-in.required', default=True) p = Participant.authenticate_with_session( id, session_id, token, allow_downgrade=not required, cookies=response.headers.cookie, )[0] if p: if p.id != user.id: submitted_confirmation_token = request.qs.get( 'log-in.confirmation') if submitted_confirmation_token: expected_confirmation_token = b64encode_s( blake2b( token.encode('ascii'), key=csrf_token.token.encode('ascii'), digest_size=48, ).digest()) confirmation_tokens_match = constant_time_compare( expected_confirmation_token, submitted_confirmation_token) if not confirmation_tokens_match: raise response.invalid_input( submitted_confirmation_token, 'log-in.confirmation', 'querystring') del request.qs['log-in.confirmation'] else: raise response.render( 'simplates/log-in-link-is-valid.spt', state) redirect = True db.run( """ DELETE FROM user_secrets WHERE participant = %s AND id = %s AND mtime = %s """, (p.id, p.session.id, p.session.mtime)) p.session = None session_suffix = '.em' elif required: raise response.render('simplates/log-in-link-is-invalid.spt', state) del request.qs['log-in.id'], request.qs['log-in.key'], request.qs[ 'log-in.token'] request.qs.pop('log-in.required', None) # Handle email verification email_id = request.qs.get_int('email.id', default=None) email_nonce = request.qs.get('email.nonce', '') if email_id and not request.path.raw.endswith('/disavow'): email_participant, email_is_already_verified = db.one( """ SELECT p, e.verified FROM emails e JOIN participants p On p.id = e.participant WHERE e.id = %s """, (email_id, ), default=(None, None)) if email_participant: result = email_participant.verify_email( email_id, email_nonce, p or user, request) state['email.verification-result'] = result request.qs.pop('email.id', None) request.qs.pop('email.nonce', None) if result == EmailVerificationResult.SUCCEEDED: request.qs.add( 'success', b64encode_s(_("Your email address is now verified."))) del email_participant # Set up the new session if p: if p.status == 'closed': p.update_status('active') if session_p: p.regenerate_session(session_p.session, response.headers.cookie, suffix=session_suffix) if not p.session: p.sign_in(response.headers.cookie, suffix=session_suffix) state['user'] = p # Redirect if appropriate if redirect: if not redirect_url: # Build the redirect URL with the querystring as it is now (we've # probably removed items from it at this point). redirect_url = request.path.raw + request.qs.serialize() response.redirect(redirect_url, trusted_url=False)
def authenticate_user_if_possible(request, response, state, user, _): """This signs the user in. """ if request.line.uri.startswith(b'/assets/'): return db = state['website'].db if not db: return # Try to authenticate the user # We want to try cookie auth first, but we want password and email auth to # supersede it. p = None if SESSION in request.headers.cookie: creds = request.headers.cookie[SESSION].value.split(':', 2) if len(creds) == 2: creds = [creds[0], 1, creds[1]] if len(creds) == 3: p = Participant.authenticate(*creds) if p: state['user'] = p session_p, p = p, None session_suffix = '' redirect = False redirect_url = None if request.method == 'POST': # Form auth body = _get_body(request) if body: # Remove email address from blacklist if requested email_address = body.pop('email.unblacklist', None) if email_address: remove_email_address_from_blacklist(email_address, user, request) # Proceed with form auth carry_on = body.pop('log-in.carry-on', None) if carry_on: p_email = session_p and session_p.get_email_address() if p_email != carry_on: state['log-in.carry-on'] = carry_on raise LoginRequired else: p = sign_in_with_form_data(body, state) if p: redirect = body.get('form.repost', None) != 'true' redirect_url = body.get('sign-in.back-to') or request.line.uri.decoded elif request.method == 'GET': if request.qs.get('log-in.id') or request.qs.get('email.id'): # Prevent email software from messing up an email log-in or confirmation # with a single GET request. Also, show a proper warning to someone trying # to log in while cookies are disabled. require_cookie(state) if request.qs.get('log-in.id'): # Email auth id = request.qs.get('log-in.id') session_id = request.qs.get('log-in.key') token = request.qs.get('log-in.token') if not (token and token.endswith('.em')): raise response.render('simplates/bad-login-link.spt', state) p = Participant.authenticate(id, session_id, token) if p: redirect = True session_p = p session_suffix = '.em' else: raise response.render('simplates/bad-login-link.spt', state) del request.qs['log-in.id'], request.qs['log-in.key'], request.qs['log-in.token'] # Handle email verification email_id = request.qs.get_int('email.id', default=None) email_nonce = request.qs.get('email.nonce', '') if email_id and not request.path.raw.endswith('/disavow'): email_participant, email_is_already_verified = db.one(""" SELECT p, e.verified FROM emails e JOIN participants p On p.id = e.participant WHERE e.id = %s """, (email_id,), default=(None, None)) if email_participant: result = email_participant.verify_email(email_id, email_nonce, p) state['email.verification-result'] = result request.qs.pop('email.id', None) request.qs.pop('email.nonce', None) if result == EmailVerificationResult.SUCCEEDED: request.qs.add('success', b64encode_s( _("Your email address is now verified.") )) del email_participant # Set up the new session if p: if session_p: session_p.sign_out(response.headers.cookie) if p.status == 'closed': p.update_status('active') if not p.session: p.sign_in(response.headers.cookie, suffix=session_suffix) state['user'] = p # Redirect if appropriate if redirect: if not redirect_url: # Build the redirect URL with the querystring as it is now (we've # probably removed items from it at this point). redirect_url = request.path.raw + request.qs.serialize() response.redirect(redirect_url, trusted_url=False)