def login(): if request.is_json: form = _security.login_form(MultiDict(request.get_json())) else: form = _security.login_form(request.form) if form.validate_on_submit(): login_user(form.user, remember=form.remember.data) after_this_request(_commit) if not request.is_json: return redirect(get_post_login_redirect(form.next.data)) if not request.is_json: return _security.render_template(config_value('LOGIN_USER_TEMPLATE'), login_user_form=form, **_ctx('login')) # override error messages if necessary confirmation_required = get_message('CONFIRMATION_REQUIRED')[0] if confirmation_required in form.errors.get('email', []): return jsonify({ 'error': confirmation_required, }), HTTPStatus.UNAUTHORIZED elif form.errors: username_fields = config_value('USER_IDENTITY_ATTRIBUTES') return jsonify({ 'error': f"Invalid {', '.join(username_fields)} and/or password." }), HTTPStatus.UNAUTHORIZED return jsonify({ 'user': form.user, 'token': form.user.get_auth_token(), })
def change_password(): """View function which handles a change password request.""" form_class = _security.change_password_form if request.is_json: form = form_class(MultiDict(request.get_json()), meta=suppress_form_csrf()) else: form = form_class(meta=suppress_form_csrf()) if form.validate_on_submit(): after_this_request(view_commit) change_user_password(current_user._get_current_object(), form.new_password.data) if _security._want_json(request): form.user = current_user return base_render_json(form, include_auth_token=True) do_flash(*get_message("PASSWORD_CHANGE")) return redirect( get_url(_security.post_change_view) or get_url(_security.post_login_view)) if _security._want_json(request): form.user = current_user return base_render_json(form) return _security.render_template( config_value("CHANGE_PASSWORD_TEMPLATE"), change_password_form=form, **_ctx("change_password"), )
def confirm_change_email(token): """View function which handles a change email confirmation request. Based on confirm_email in Flask-Security.""" expired, invalid, user, new_email = ( confirm_change_email_token_status(token)) if not user or invalid: invalid = True do_flash(*get_message('INVALID_CONFIRMATION_TOKEN')) if expired: send_change_email_confirmation_instructions(user, new_email) do_flash(*(('You did not confirm your change of email within {0}. ' 'New instructions to confirm your change of email have ' 'been sent to {1}.' ).format(_security.confirm_email_within, new_email), 'error')) if invalid or expired: return redirect(url_for('home')) if user != current_user: logout_user() login_user(user) if change_user_email(user, new_email): after_this_request(_commit) msg = ('Thank you. Your change of email has been confirmed.', 'success') else: msg = ('Your change of email has already been confirmed.' 'info') do_flash(*msg) return redirect(url_for('home'))
def confirm_email(token): """View function which handles a email confirmation request.""" expired, invalid, user = confirm_email_token_status(token) if not user or invalid: invalid = True do_flash(*get_message('INVALID_CONFIRMATION_TOKEN')) if expired: send_confirmation_instructions(user) do_flash(*get_message('CONFIRMATION_EXPIRED', email=user.email, within=_security.confirm_email_within)) if invalid or expired: return redirect( get_url(_security.confirm_error_view) or url_for('send_confirmation')) if user != current_user: logout_user() login_user(user) confirm_user(user) after_this_request(_commit) do_flash(*get_message('EMAIL_CONFIRMED')) return redirect( get_url(_security.post_confirm_view) or get_url(_security.post_login_view))
def verify(): """View function which handles a authentication verification request.""" form_class = _security.verify_form if request.is_json: form = form_class(MultiDict(request.get_json()), meta=suppress_form_csrf()) else: form = form_class(meta=suppress_form_csrf()) if form.validate_on_submit(): # form may have called verify_and_update_password() after_this_request(view_commit) # verified - so set freshness time. session["fs_paa"] = time.time() if _security._want_json(request): return base_render_json(form) do_flash(*get_message("REAUTHENTICATION_SUCCESSFUL")) return redirect(get_post_verify_redirect()) if _security._want_json(request): assert form.user == current_user return base_render_json(form) return _security.render_template(config_value("VERIFY_TEMPLATE"), verify_form=form, **_ctx("verify"))
def confirm_email(token): """View function which handles a email confirmation request.""" expired, invalid, user = confirm_email_token_status(token) if not user or invalid: invalid = True already_confirmed = user is not None and user.confirmed_at is not None expired_and_not_confirmed = expired and not already_confirmed if expired_and_not_confirmed: send_confirmation_instructions(user) if invalid or expired_and_not_confirmed: return redirect(get_url(_security.confirm_error_view)) if confirm_user(user): after_this_request(_commit) if user != current_user: logout_user() login_user(user) return redirect(get_url(_security.post_confirm_view))
def post(self): form = LoginForm() if form.validate_on_submit(): login_user(form.user, remember=False) after_this_request(_commit) return _make_response(form, include_auth_token=True)
def two_factor_verify_password(): """View function which handles a password verification request.""" form_class = _security.two_factor_verify_password_form if request.is_json: form = form_class(MultiDict(request.get_json()), meta=suppress_form_csrf()) else: form = form_class(meta=suppress_form_csrf()) if form.validate_on_submit(): # form called verify_and_update_password() after_this_request(_commit) session["tf_confirmed"] = True m, c = get_message("TWO_FACTOR_PASSWORD_CONFIRMATION_DONE") if not _security._want_json(request): do_flash(m, c) return redirect(url_for_security("two_factor_setup")) else: form._errors = m return base_render_json(form) if _security._want_json(request): assert form.user == current_user # form.user = current_user return base_render_json(form) return _security.render_template( config_value("TWO_FACTOR_VERIFY_PASSWORD_TEMPLATE"), two_factor_verify_password_form=form, **_ctx("tf_verify_password"))
def reset_password(token): """View function that handles a reset password request.""" expired, invalid, user = reset_password_token_status(token) if invalid: return redirect(url_for('frontend.forgot_password') + '?invalid') elif expired: send_reset_password_instructions(user) return redirect(url_for('frontend.forgot_password') + '?expired') elif request.method == 'GET': return redirect(url_for('frontend.reset_password', token=token)) form = _security.reset_password_form() if form.validate_on_submit(): after_this_request(_commit) update_password(user, form.newPassword.data) login_user(user) else: return jsonify({'errors': form.errors}), HTTPStatus.BAD_REQUEST return jsonify({ 'token': user.get_auth_token(), 'user': user, })
def confirm_email(token): """View function which handles a email confirmation request.""" expired, invalid, user = confirm_email_token_status(token) if invalid: do_flash(gettext('Invalid confirmation token.'), 'error') if expired: send_confirmation_instructions(user) do_flash(gettext('You did not confirm your email within %(within)s. ' 'New instructions to confirm your email have been ' 'sent to %(email)s.', email=user.email, within=_security.confirm_email_within), 'error') if invalid or expired: return redirect(get_url(_security.confirm_error_view) or url_for('send_confirmation')) confirm_user(user) login_user(user, True) after_this_request(_commit) do_flash(gettext('Thank you. Your email has been confirmed.'), 'success') return redirect(get_url(_security.post_confirm_view) or get_url(_security.post_login_view))
def login_handler(response, provider, query): """Shared method to handle the signin process""" connection = _datastore.find_connection(**query) if connection: after_this_request(_commit) user = connection.user login_user(user) key = _social.post_oauth_login_session_key redirect_url = session.pop(key, get_post_login_redirect()) login_completed.send(current_app._get_current_object(), provider=provider, user=user) return redirect(redirect_url) login_failed.send(current_app._get_current_object(), provider=provider, oauth_response=response) #_security.login_manager.login_view = "user.register" #next = get_url(_security.login_manager.login_view) next = url_for('user.register', provider_id=provider.id, login_failed=1) msg = '%s account not associated with an existing user' % provider.name #if session['login_attempt']: # session['failed_login_connection'] = dict(dummy="dummy") do_flash(msg, 'danger' if session['login_attempt'] else 'info') return redirect(next)
def remote_authorize(*args, **kwargs): """Login via JSON from another application. :param string email: Email associated with user account :param string password: Password assocaited with user account :return bool """ form_class = _security.login_form error_message = 'No credentials provided' if request.json: form = form_class(MultiDict(request.json)) else: error_message = "Request did not use Content-Type:application/json" logger.info('[OAUTH::remote_authorize] %s', error_message) abort(403, error_message) if form.validate_on_submit(): login_user(form.user, remember=form.remember.data) after_this_request(_commit) current_user = form.user else: logger.error( '[OAUTH::remote_authorize] Validation Failed with ' 'message: %s', form.errors) return abort(403, form.errors) return True
def reset_password(token): """View function that handles a reset password request.""" expired, invalid, user = reset_password_token_status(token) if invalid: do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN')) if expired: send_reset_password_instructions(user) do_flash(*get_message('PASSWORD_RESET_EXPIRED', email=user.email, within=_security.reset_password_within)) if invalid or expired: return redirect(url_for('forgot_password')) form = _security.reset_password_form() if form.validate_on_submit(): after_this_request(_commit) update_password(user, form.password.data) do_flash(*get_message('PASSWORD_RESET')) login_user(user) return redirect(get_url(_security.post_reset_view) or get_url(_security.post_login_view)) return _security.render_template(config_value('RESET_PASSWORD_TEMPLATE'), reset_password_form=form, reset_password_token=token, **_ctx('reset_password'))
def confirm_email(token): """View function which handles a email confirmation request.""" expired, invalid, user = confirm_email_token_status(token) if not user or invalid: invalid = True do_flash(*get_message('INVALID_CONFIRMATION_TOKEN')) if expired: send_confirmation_instructions(user) do_flash(*get_message('CONFIRMATION_EXPIRED', email=user.email, within=_security.confirm_email_within)) if invalid or expired: return redirect(get_url(_security.confirm_error_view) or url_for('send_confirmation')) if user != current_user: logout_user() login_user(user) if confirm_user(user): after_this_request(_commit) msg = 'EMAIL_CONFIRMED' else: msg = 'ALREADY_CONFIRMED' do_flash(*get_message(msg)) return redirect(get_url(_security.post_confirm_view) or get_url(_security.post_login_view))
def remote_authorize(*args, **kwargs): """Login via JSON from another application. :param string email: Email associated with user account :param string password: Password assocaited with user account :return bool """ form_class = _security.login_form error_message = 'No credentials provided' if request.json: form = form_class(MultiDict(request.json)) else: abort(403, error_message) if form.validate_on_submit(): login_user(form.user, remember=form.remember.data) after_this_request(_commit) current_user = form.user else: abort(403, error_message) if not hasattr(current_user, 'id'): abort(403, error_message) return True
def register_user(user): """Performs the user registration process. Returns True if the user has been logged in, false otherwise. """ if not _security.confirmable or _security.login_without_confirmation: user.active = True # confirmation token depends on having user.id set, which requires # the user be committed to the database user.save(commit=True) confirmation_link, token = None, None if _security.confirmable: confirmation_link, token = generate_confirmation_link(user) user_registered.send(current_app._get_current_object(), user=user, confirm_token=token) if config_value('SEND_REGISTER_EMAIL'): send_mail(config_value('EMAIL_SUBJECT_REGISTER'), user.email, 'welcome', user=user, confirmation_link=confirmation_link) if not _security.confirmable or _security.login_without_confirmation: login_user(user) # login_user will modify the user object if _security.trackable is set, # but it will not request a session commit itself when it needs it :/ after_this_request(_commit) return True return False
def change_password(): """View function which handles a change password request.""" form_class = _security.change_password_form if request.json: form = form_class(MultiDict(request.json)) else: form = form_class() if form.validate_on_submit(): after_this_request(_commit) change_user_password(current_user, form.new_password.data) if request.json is None: do_flash(*get_message('PASSWORD_CHANGE')) return redirect(get_url(_security.post_change_view) or get_url(_security.post_login_view)) if request.json: form.user = current_user return _render_json(form) return _security.render_template(config_value('CHANGE_PASSWORD_TEMPLATE'), change_password_form=form, **_ctx('change_password'))
def change_password(): """View function which handles a change password request.""" form_class = _security.change_password_form if request.json: form = form_class(MultiDict(request.json)) else: form = form_class() if form.validate_on_submit(): after_this_request(_commit) change_user_password(current_user, form.new_password.data) if request.json is None: do_flash(*get_message('PASSWORD_CHANGE')) return redirect( get_url(_security.post_change_view) or get_url(_security.post_login_view)) if request.json: return _render_json(form) return render_template(config_value('CHANGE_PASSWORD_TEMPLATE'), change_password_form=form, **_ctx('change_password'))
def connect_handler(cv, provider): """Shared method to handle the connection process :param connection_values: A dictionary containing the connection values :param provider_id: The provider ID the connection shoudl be made to """ cv.setdefault('user_id', current_user.get_id()) connection = _datastore.find_connection(**cv) if connection is None: after_this_request(_commit) connection = _datastore.create_connection(**cv) msg = ('Connection established to %s' % provider.name, 'success') connection_created.send(current_app._get_current_object(), user=current_user._get_current_object(), connection=connection) else: msg = ('A connection is already established with %s ' 'to your account' % provider.name, 'notice') connection_failed.send(current_app._get_current_object(), user=current_user._get_current_object()) redirect_url = session.pop(config_value('POST_OAUTH_CONNECT_SESSION_KEY'), get_url(config_value('CONNECT_ALLOW_VIEW'))) do_flash(*msg) return redirect(redirect_url)
def register(): """View function which handles a registration request.""" if _security.confirmable or request.json: form_class = _security.confirm_register_form else: form_class = _security.register_form if request.json: form_data = MultiDict(request.json) else: form_data = request.form form = form_class(form_data) if form.validate_on_submit(): user = register_user(**form.to_dict()) form.user = user if not _security.confirmable or _security.login_without_confirmation: after_this_request(_commit) login_user(user) if not request.json: return redirect(get_post_register_redirect()) return _render_json(form, True) if request.json: return _render_json(form) return render_template(config_value('REGISTER_USER_TEMPLATE'), register_user_form=form, **_ctx('register'))
def us_verify_link(): """ Used to verify a magic email link. GET only """ if not all(v in request.args for v in ["email", "code"]): m, c = get_message("API_ERROR") if _security.redirect_behavior == "spa": return redirect(get_url(_security.login_error_view, qparams={c: m})) do_flash(m, c) return redirect(url_for_security("us_signin")) user = _datastore.find_user(email=request.args.get("email")) if not user or not user.active: if not user: m, c = get_message("USER_DOES_NOT_EXIST") else: m, c = get_message("DISABLED_ACCOUNT") if _security.redirect_behavior == "spa": return redirect(get_url(_security.login_error_view, qparams={c: m})) do_flash(m, c) return redirect(url_for_security("us_signin")) totp_secrets = user.us_get_totp_secrets() if "email" not in totp_secrets or not _security._totp_factory.verify_totp( token=request.args.get("code"), totp_secret=totp_secrets["email"], user=user, window=config_value("US_TOKEN_VALIDITY"), ): m, c = get_message("INVALID_CODE") if _security.redirect_behavior == "spa": return redirect( get_url( _security.login_error_view, qparams=user.get_redirect_qparams({c: m}), )) do_flash(m, c) return redirect(url_for_security("us_signin")) if (config_value("TWO_FACTOR") and "email" in config_value("US_MFA_REQUIRED") and (config_value("TWO_FACTOR_REQUIRED") or is_tf_setup(user))): return tf_login(user, primary_authn_via="email") login_user(user, authn_via=["email"]) after_this_request(_commit) if _security.redirect_behavior == "spa": # We do NOT send the authentication token here since the only way to # send it would be via a query param and that isn't secure. (logging and # possibly HTTP Referer header). # This means that this can only work if sessions are active which sort of # makes sense - otherwise you need to use /us-signin with a code. return redirect( get_url(_security.post_login_view, qparams=user.get_redirect_qparams())) do_flash(*get_message("PASSWORDLESS_LOGIN_SUCCESSFUL")) return redirect(get_post_login_redirect())
def _send_code_helper(form): # send code user = form.user method = form.chosen_method.data totp_secrets = _datastore.us_get_totp_secrets(user) # We 'auto-setup' email since in the case of no password the normal us-setup # mechanisms of course don't work. We rely on the fact that the user went # through the 'confirmation' process to validate the email. if method == "email" and method not in totp_secrets: after_this_request(_commit) totp_secrets[method] = _security._totp_factory.generate_totp_secret() _datastore.us_put_totp_secrets(user, totp_secrets) msg = user.us_send_security_token( method, totp_secret=totp_secrets[method], phone_number=getattr(user, "us_phone_number", None), send_magic_link=True, ) code_sent = True if msg: # send code didn't work code_sent = False form.chosen_method.errors.append(msg) return code_sent, msg
def login_handler(response, provider, query): """Shared method to handle the signin process""" connection = _datastore.find_connection(**query) if connection: after_this_request(_commit) user = connection.user login_user(user) key = _social.post_oauth_login_session_key redirect_url = session.pop(key, get_post_login_redirect()) login_completed.send(current_app._get_current_object(), provider=provider, user=user) return redirect(redirect_url) login_failed.send(current_app._get_current_object(), provider=provider, oauth_response=response) next = get_url(_security.login_manager.login_view) msg = '%s account not associated with an existing user' % provider.name do_flash(msg, 'error') return redirect(next)
def reset_password(token): """View function that handles a reset password request.""" expired, invalid, user = reset_password_token_status(token) if invalid: do_flash(gettext('Invalid reset password token.'), 'error') if expired: do_flash(gettext('You did not reset your password within %(within)s. ' 'New instructions have been sent to %(email)s.', email=user.email, within=_security.reset_password_within), 'error') if invalid or expired: return redirect(url_for('forgot_password')) form = ResetPasswordForm() if form.validate_on_submit(): after_this_request(_commit) update_password(user, form.password.data) do_flash(gettext('You successfully reset your password and you have ' 'been logged in automatically.'), 'success') login_user(user, True) return redirect(get_url(_security.post_reset_view) or get_url(_security.post_login_view)) return _render_template('security/reset_password.html', reset_password_form=form, reset_password_token=token, **_ctx('reset_password'))
def func_wrapper(*args, **kwargs): # get the auth token auth_header = request.headers.get('Authentication-Token') if auth_header: auth_token = auth_header.split(" ")[1] else: auth_token = None if auth_token: # resp is user id in case of sucess resp = decode_auth_token(auth_token) if isinstance(resp, dict): if (request.path != '/auth/logout'): after_this_request( extend_jwt(resp, auth_token), ) return func(*args, **kwargs) responseObject = { 'status': 'fail', 'message': resp } return make_response(jsonify(responseObject)), \ html_codes.HTTP_BAD_UNAUTHORIZED else: responseObject = { 'status': 'fail', 'message': 'Provide a valid auth token.' } return make_response(jsonify(responseObject)), \ html_codes.HTTP_BAD_FORBIDDEN
def register(): """View function which handles a registration request.""" if _security.confirmable or request.json: form_class = ConfirmRegisterForm else: form_class = RegisterForm if request.json: form_data = MultiDict(request.json) else: form_data = request.form form = form_class(form_data) if form.validate_on_submit(): user = register_user(**form.to_dict()) form.user = user if not _security.confirmable or _security.login_without_confirmation: after_this_request(_commit) login_user(user) if not request.json: post_register_url = get_url(_security.post_register_view) post_login_url = get_url(_security.post_login_view) return redirect(post_register_url or post_login_url) if request.json: return _render_json(form) return render_template('security/register_user.html', register_user_form=form, **_ctx('register'))
def us_setup_validate(token): """ Validate new setup. The token is the state variable which is signed and timed and contains all the state that once confirmed will be stored in the user record. """ form_class = _security.us_setup_validate_form if request.is_json: form = form_class(MultiDict(request.get_json()), meta=suppress_form_csrf()) else: form = form_class(meta=suppress_form_csrf()) expired, invalid, state = check_and_get_token_status( token, "us_setup", get_within_delta("US_SETUP_WITHIN")) if invalid: m, c = get_message("API_ERROR") if expired: m, c = get_message("US_SETUP_EXPIRED", within=config_value("US_SETUP_WITHIN")) if invalid or expired: if _security._want_json(request): payload = json_error_response(errors=m) return _security._render_json(payload, 400, None, None) do_flash(m, c) return redirect(url_for_security("us_setup")) form.totp_secret = state["totp_secret"] form.user = current_user if form.validate_on_submit(): after_this_request(_commit) method = state["chosen_method"] phone = state["phone_number"] if method == "sms" else None _datastore.us_set(current_user, method, state["totp_secret"], phone) us_profile_changed.send(app._get_current_object(), user=current_user, method=method) if _security._want_json(request): return base_render_json( form, include_user=False, additional=dict(chosen_method=method, phone=current_user.us_phone_number), ) else: do_flash(*get_message("US_SETUP_SUCCESSFUL")) return redirect( get_url(_security.us_post_setup_view) or get_url(_security.post_login_view)) # Code not correct/outdated. if _security._want_json(request): return base_render_json(form, include_user=False) m, c = get_message("INVALID_PASSWORD_CODE") do_flash(m, c) return redirect(url_for_security("us_setup"))
def confirm_email(token): """ View function which handles a email confirmation request. """ expired, invalid, user = confirm_email_token_status(token) if not user or invalid: invalid = True do_flash(*get_message("INVALID_CONFIRMATION_TOKEN")) if expired: send_confirmation_instructions(user) do_flash(*get_message("CONFIRMATION_EXPIRED", email=user.email, within=_security.confirm_email_within)) if invalid or expired: return redirect(get_url(_security.confirm_error_view)) if user != current_user: logout_user() login_user(user) if confirm_user(user): after_this_request(_commit) msg = "EMAIL_CONFIRMED" else: msg = "ALREADY_CONFIRMED" do_flash(*get_message(msg)) return redirect(get_url(_security.post_confirm_view))
def remove_connection(provider_id, provider_user_id): """Remove a specific connection for the authenticated user to the specified provider """ provider = get_provider_or_404(provider_id) ctx = dict(provider=provider.name, user=current_user, provider_user_id=provider_user_id) deleted = _datastore.delete_connection(user_id=current_user.get_id(), provider_id=provider_id, provider_user_id=provider_user_id) if deleted: after_this_request(_commit) msg = ('Connection to %(provider)s removed' % ctx, 'info') connection_removed.send(current_app._get_current_object(), user=current_user._get_current_object(), provider_id=provider_id) else: msg = ('Unabled to remove connection to %(provider)s' % ctx, 'error') do_flash(*msg) return redirect(request.referrer)
def login(): """View function for login view""" form_class = _security.login_form if request.json: form = form_class(MultiDict(request.json)) else: form = form_class() if form.validate_on_submit(): login_user(form.user, remember=form.remember.data) after_this_request(_commit) if not request.json: return redirect(get_post_login_redirect()) form.next.data = get_url(request.args.get('next')) \ or get_url(request.form.get('next')) or '' if request.json: return _render_json(form, True) return render_template(config_value('LOGIN_USER_TEMPLATE'), login_user_form=form, **_ctx('login'))
def register(): """View function which handles a registration request.""" if _security.confirmable or request.json: form_class = _security.confirm_register_form else: form_class = _security.register_form if request.json: form_data = MultiDict(request.json) else: form_data = request.form form = form_class(form_data) if form.validate_on_submit(): user = register_user(**form.to_dict()) form.user = user if not _security.confirmable or _security.login_without_confirmation: after_this_request(_commit) login_user(user) if not request.json: return redirect(get_post_register_redirect()) if request.json: return _render_json(form) return render_template(config_value('REGISTER_USER_TEMPLATE'), register_user_form=form, **_ctx('register'))
def reset_password(token): """View function that handles a reset password request.""" expired, invalid, user = reset_password_token_status(token) if invalid: do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN')) if expired: do_flash(*get_message('PASSWORD_RESET_EXPIRED', email=user.email, within=_security.reset_password_within)) if invalid or expired: return redirect(url_for('forgot_password')) form = _security.reset_password_form() if form.validate_on_submit(): after_this_request(_commit) update_password(user, form.password.data) do_flash(*get_message('PASSWORD_RESET')) login_user(user) return redirect( get_url(_security.post_reset_view) or get_url(_security.post_login_view)) return render_template(config_value('RESET_PASSWORD_TEMPLATE'), reset_password_form=form, reset_password_token=token, **_ctx('reset_password'))
def post(self, **kwargs): """Reset user password.""" user = self.get_user(**kwargs) after_this_request(_commit) update_password(user, kwargs['password']) login_user(user) return self.success_response(user)
def login(): """View function for login view""" form_class = _security.login_form if request.json: form = form_class(MultiDict(request.json)) else: form = form_class() pdb.set_trace() if form.validate_on_submit(): login_user(form.user, remember=form.remember.data) after_this_request(_commit) if not request.json: return redirect(get_post_login_redirect()) form.next.data = get_url(request.args.get('next')) \ or get_url(request.form.get('next')) or '' if request.json: return _render_json(form, True) return render_template(config_value('LOGIN_USER_TEMPLATE'), login_user_form=form, **_ctx('login'))
def reset_password(token): """View function that handles a reset password request.""" expired, invalid, user = reset_password_token_status(token) if invalid: do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN')) if expired: do_flash(*get_message('PASSWORD_RESET_EXPIRED', email=user.email, within=_security.reset_password_within)) if invalid or expired: return redirect(url_for('browser.forgot_password')) has_error = False form = _security.reset_password_form() if form.validate_on_submit(): try: update_password(user, form.password.data) except SOCKETErrorException as e: # Handle socket errors which are not covered by SMTPExceptions. logging.exception(str(e), exc_info=True) flash( gettext(u'SMTP Socket error: {}\n' u'Your password has not been changed.').format(e), 'danger') has_error = True except (SMTPConnectError, SMTPResponseException, SMTPServerDisconnected, SMTPDataError, SMTPHeloError, SMTPException, SMTPAuthenticationError, SMTPSenderRefused, SMTPRecipientsRefused) as e: # Handle smtp specific exceptions. logging.exception(str(e), exc_info=True) flash( gettext(u'SMTP error: {}\n' u'Your password has not been changed.').format(e), 'danger') has_error = True except Exception as e: # Handle other exceptions. logging.exception(str(e), exc_info=True) flash( gettext(u'Error: {}\n' u'Your password has not been changed.').format(e), 'danger') has_error = True if not has_error: after_this_request(_commit) do_flash(*get_message('PASSWORD_RESET')) login_user(user) return redirect( get_url(_security.post_reset_view) or get_url(_security.post_login_view)) return _security.render_template( config_value('RESET_PASSWORD_TEMPLATE'), reset_password_form=form, reset_password_token=token, **_ctx('reset_password'))
def change_password(): """View function which handles a change password request.""" has_error = False form_class = _security.change_password_form if request.json: form = form_class(MultiDict(request.json)) else: form = form_class() if form.validate_on_submit(): try: change_user_password(current_user, form.new_password.data) except SOCKETErrorException as e: # Handle socket errors which are not covered by SMTPExceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'SMTP Socket error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True except (SMTPConnectError, SMTPResponseException, SMTPServerDisconnected, SMTPDataError, SMTPHeloError, SMTPException, SMTPAuthenticationError, SMTPSenderRefused, SMTPRecipientsRefused) as e: # Handle smtp specific exceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'SMTP error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True except Exception as e: # Handle other exceptions. logging.exception(str(e), exc_info=True) flash( gettext( u'Error: {}\n' u'Your password has not been changed.' ).format(e), 'danger' ) has_error = True if request.json is None and not has_error: after_this_request(_commit) do_flash(*get_message('PASSWORD_CHANGE')) return redirect(get_url(_security.post_change_view) or get_url(_security.post_login_view)) if request.json and not has_error: form.user = current_user return _render_json(form) return _security.render_template( config_value('CHANGE_PASSWORD_TEMPLATE'), change_password_form=form, **_ctx('change_password'))
def reset_password(token): """View function that handles a reset password request.""" expired, invalid, user = reset_password_token_status(token) if invalid: do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN')) if expired: do_flash(*get_message('PASSWORD_RESET_EXPIRED', email=user.email, within=_security.reset_password_within)) if invalid or expired: return redirect(url_for('browser.forgot_password')) has_error = False form = _security.reset_password_form() if form.validate_on_submit(): try: update_password(user, form.password.data) except SOCKETErrorException as e: # Handle socket errors which are not covered by SMTPExceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'SMTP Socket error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True except (SMTPConnectError, SMTPResponseException, SMTPServerDisconnected, SMTPDataError, SMTPHeloError, SMTPException, SMTPAuthenticationError, SMTPSenderRefused, SMTPRecipientsRefused) as e: # Handle smtp specific exceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'SMTP error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True except Exception as e: # Handle other exceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'Error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True if not has_error: after_this_request(_commit) do_flash(*get_message('PASSWORD_RESET')) login_user(user) return redirect(get_url(_security.post_reset_view) or get_url(_security.post_login_view)) return _security.render_template( config_value('RESET_PASSWORD_TEMPLATE'), reset_password_form=form, reset_password_token=token, **_ctx('reset_password'))
def error(code, reason): def set_code(response): response.status_code = code return response after_this_request(set_code) return {"error": reason}
def after_this_request(self, fn): """ Register a function to run after this request. :param fn: The function to run. It should accept one argument, the response, which it should also return """ after_this_request(fn)
def staticCahcingCheck(script): noCacheList = ["common.py", "sheetDialog.py", "sheetDefault.css"] print(script) if script in noCacheList: fl.after_this_request(noCaching) return fl.send_from_directory("./static/", script) else: fl.redirect("/static/" + script)
def login_user(self, user): """Perform any login actions.""" if ( not current_security.confirmable or current_security.login_without_confirmation ): after_this_request(_commit) login_user(user)
def change_password(): """View function which handles a change password request.""" has_error = False form_class = _security.change_password_form if request.json: form = form_class(MultiDict(request.json)) else: form = form_class() if form.validate_on_submit(): try: change_user_password(current_user._get_current_object(), form.new_password.data) except SOCKETErrorException as e: # Handle socket errors which are not covered by SMTPExceptions. logging.exception(str(e), exc_info=True) flash(gettext(SMTP_SOCKET_ERROR).format(e), 'danger') has_error = True except (SMTPConnectError, SMTPResponseException, SMTPServerDisconnected, SMTPDataError, SMTPHeloError, SMTPException, SMTPAuthenticationError, SMTPSenderRefused, SMTPRecipientsRefused) as e: # Handle smtp specific exceptions. logging.exception(str(e), exc_info=True) flash(gettext(SMTP_ERROR).format(e), 'danger') has_error = True except Exception as e: # Handle other exceptions. logging.exception(str(e), exc_info=True) flash(gettext(PASS_ERROR).format(e), 'danger') has_error = True if request.json is None and not has_error: after_this_request(view_commit) do_flash(*get_message('PASSWORD_CHANGE')) old_key = get_crypt_key()[1] set_crypt_key(form.new_password.data, False) from pgadmin.browser.server_groups.servers.utils \ import reencrpyt_server_passwords reencrpyt_server_passwords(current_user.id, old_key, form.new_password.data) return redirect( get_url(_security.post_change_view) or get_url(_security.post_login_view)) if request.json and not has_error: form.user = current_user return default_render_json(form) return _security.render_template( config_value('CHANGE_PASSWORD_TEMPLATE'), change_password_form=form, **_ctx('change_password'))
def confirm_email(token): """View function which handles a email confirmation request.""" expired, invalid, user = confirm_email_token_status(token) print(expired) print(invalid) print(user) if not user or invalid: invalid = True do_flash(*get_message('INVALID_CONFIRMATION_TOKEN')) already_confirmed = user is not None and user.confirmed_at is not None if expired and not already_confirmed: send_confirmation_instructions(user) do_flash(*get_message('CONFIRMATION_EXPIRED', email=user.email, within=_security.confirm_email_within)) if invalid or (expired and not already_confirmed): #if not request.is_json: # return redirect(get_url(_security.confirm_error_view) or # url_for('send_confirmation')) #else: if invalid: #code=202 #response={"errors": {"token":"Invalid"}} return redirect( "http://www.frontend.com/get?message=Token_invalid", code=302) else: #code=202 #response={"errors": {"token":"Expired"}} return redirect( "http://www.frontend.com/get?message=Token_expired", code=302) #return jsonify(dict(meta=dict(code=code), response=response)), code if user != current_user: logout_user() if confirm_user(user): after_this_request(_commit) msg = 'EMAIL_CONFIRMED' else: msg = 'ALREADY_CONFIRMED' do_flash(*get_message(msg)) #if not request.is_json: # return redirect(get_url(_security.post_confirm_view) or # get_url(_security.post_login_view)) #else: #code=200 #response="Email confermata" #return jsonify(dict(meta=dict(code=code), response=response)), code return redirect("http://www.frontend.com/get?message=Email_confermata", code=302)
def setup_args_handling(): """Set up request arguments handling. It creates g.unused_args set, with names of unused parameters. It is expected that as parameters get used, they will be removed from the set. After request is handled, _check_unused_args_empty verifies that all parameters were used, and returns 400 response if not. """ g.unused_args = set(request.args.iterkeys()) after_this_request(_check_unused_args_empty)
def login(): form_class = _security.login_form form = form_class() if form.validate_on_submit(): login_user(form.user, remember=form.remember.data) after_this_request(_commit) if not request.json: return redirect(get_post_login_redirect(form.next.data)) return render_html('content/login.html', login_user_form=form)
def confirm_email(token): """View function which handles a email confirmation request.""" after_this_request(_commit) try: user = confirm_by_token(token) except ConfirmationError, e: _logger.debug('Confirmation error: %s' % e) if e.user: send_confirmation_instructions(e.user) do_flash(str(e), 'error') confirm_error_url = get_url(_security.confirm_error_view) return redirect(confirm_error_url or url_for('send_confirmation'))
def oauth_authenticate(client_id, user, require_existing_link=False, remember=False): """Authenticate an oauth authorized callback.""" # Authenticate via the access token (access token used to get user_id) if not requires_confirmation(user): after_this_request(_commit) if login_user(user): if require_existing_link: account = RemoteAccount.get(user.id, client_id) if account is None: logout_user() return False return True return False
def setup_audit(): g.audit_data = { 'resource': request.path, 'method': request.method, 'remote_address': request.remote_addr, # The following MUST be there, but may be updated later 'user_id': None, 'project_id': None, 'message': None, 'extra': {} } if current_app.config['AUDIT_VERBOSITY'] > 0: after_this_request(save_audit_data)
def login(): form = LoginForm(request.form) if request.method == 'POST': if form.validate_on_submit(): login_user(form.user) after_this_request(_commit) flash("You are now logged in.", 'success') if request.args.get("next"): return redirect(request.args.get("next")) else: return redirect(url_for('public.overview')) else: flash_errors(form) return render_template("public/login.html", form=form)
def post(self): data = get_data() if data is not None: form = self.form_class(MultiDict(data)) else: form = self.form_class() if form.validate_on_submit(): login_user(form.user, remember=form.remember.data) after_this_request(_commit) # This returns the response and the status code. See function. return authentication_response(form) return form.as_json(), 400
def dispatch_request(self): form = forms.LoginForm() if form.validate_on_submit(): utils.login_user(form.user, remember=form.remember.data) flask.after_this_request(security_views._commit) return flask.redirect(utils.get_post_login_redirect()) form.next.data = ( utils.get_url(flask.request.args.get('next')) or utils.get_url(flask.request.form.get('next')) or '' ) return flask.render_template('login.html', form=form)
def login(): """View function for login view""" form = LoginForm() if form.validate_on_submit(): login_user(form.user, remember=form.remember.data) after_this_request(_commit) if not request.json: return redirect(get_post_login_redirect()) return render('login.html', login_user_form=form)
def token_login(token): """View function that handles passwordless login via a token""" expired, invalid, user = login_token_status(token) if invalid: do_flash(*get_message("INVALID_LOGIN_TOKEN")) if expired: send_login_instructions(user) do_flash(*get_message("LOGIN_EXPIRED", email=user.email, within=_security.login_within)) if invalid or expired: return redirect(url_for("login")) login_user(user) after_this_request(_commit) do_flash(*get_message("PASSWORDLESS_LOGIN_SUCCESSFUL")) return redirect(get_post_login_redirect())
def token_login(token): """View function that handles passwordless login via a token""" expired, invalid, user = login_token_status(token) if invalid: do_flash(gettext('Invalid login token.'), 'error') if expired: send_login_instructions(user) do_flash(gettext('You did not login within %(within)s. New instructions ' 'to login have been sent to %(email)s.', email=user.email, within=_security.login_within), 'error') if invalid or expired: return redirect(url_for('login')) login_user(user, True) after_this_request(_commit) do_flash(gettext('You have successfully logged in.'), 'success') return redirect(get_post_login_redirect())
def confirm_email(token): """View function which handles a email confirmation request.""" expired, invalid, user = confirm_email_token_status(token) if not user or invalid: invalid = True do_flash(*get_message("INVALID_CONFIRMATION_TOKEN")) if expired: send_confirmation_instructions(user) do_flash(*get_message("CONFIRMATION_EXPIRED", email=user.email, within=_security.confirm_email_within)) if invalid or expired: return redirect(get_url(_security.confirm_error_view) or url_for("send_confirmation")) confirm_user(user) login_user(user) after_this_request(_commit) do_flash(*get_message("EMAIL_CONFIRMED")) return redirect(get_url(_security.post_confirm_view) or get_url(_security.post_login_view))
def oauth_authenticate(client_id, user, require_existing_link=False, remember=False): """Authenticate an oauth authorized callback. :param client_id: The client id. :param user: A user instance. :param require_existing_link: If ``True``, check if remote account exists. (Default: ``False``) :returns: ``True`` if the user is successfully authenticated. """ # Authenticate via the access token (access token used to get user_id) if not requires_confirmation(user): after_this_request(_commit) if login_user(user, remember=remember): if require_existing_link: account = RemoteAccount.get(user.id, client_id) if account is None: logout_user() return False return True return False
def remove_all_connections(provider_id): """Remove all connections for the authenticated user to the specified provider """ provider = get_provider_or_404(provider_id) ctx = dict(provider=provider.name, user=current_user) deleted = _datastore.delete_connections(user_id=current_user.get_id(), provider_id=provider_id) if deleted: after_this_request(_commit) msg = ('All connections to %s removed' % provider.name, 'info') connection_removed.send(current_app._get_current_object(), user=current_user._get_current_object(), provider_id=provider_id) else: msg = ('Unable to remove connection to %(provider)s' % ctx, 'error') do_flash(*msg) return redirect(request.referrer)