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: {}\nYour 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: {}\nYour 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: {}\nYour 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 bind_user(): """Bind user local account with openid account""" form_class = _security.login_form form = form_class() if form.validate_on_submit(): # 这里要确认用户为username还是邮箱 match = re.match(r'^.+@[^.].*\.[a-z]{2,10}$', form.email.data, re.IGNORECASE) if match is None: current_user.bind_username = form.email.data else: current_user.bind_email = form.email.data current_user.bind_remind = False _datastore.put(current_user) _datastore.commit() next_url = get_url(request.args.get('next')) or get_url(request.form.get('next')) \ or current_app.extensions['security'].post_login_view or '' return redirect(next_url) return render_template('security/bind_user.html', bind_form=form)
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=config_value('RESET_PASSWORD_WITHIN'))) if invalid or expired: return redirect(url_for('login.forgot_password')) form = ResetPasswordForm() if form.validate_on_submit(): update_password(user, form.new_password.data) do_flash(*get_message('PASSWORD_RESET')) login_user(user) return redirect( get_url(config_value('POST_RESET_VIEW')) or get_url(config_value('POST_LOGIN_VIEW'))) else: current_app.logger.error('Form did not validate: {}'.format( form.errors)) flash(form.errors, 'error') return render_template('login/reset_password.html', reset_password_form=form, reset_password_token=token)
def confirm_email(token): """View function which handles a email confirmation request.""" security = current_app.extensions.get('security') 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): 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 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 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 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 do_not_remind_bind(): """Not remind user to bind the account again.""" next_url = get_url(request.args.get('next')) or get_url(request.form.get('next')) \ or current_app.extensions['security'].post_login_view or '' current_user.bind_remind = False _datastore.put(current_user) _datastore.commit() return redirect(next_url)
def openid_login(provider): """Return OAuth2 login view for the given provider. :param provider: OAuth2 provider. """ # get parser for provider parser = eval(str.format('{0}_parser', provider.lower())) code = request.args.get('code') oauth_kwargs = current_app.config[str.format('OAUTH_{0}', provider.upper())] c = Client(**oauth_kwargs) # get request token c.request_token(parser=parser, redirect_uri=current_app.config['KINORSI_SERVER_HOST'], grant_type='authorization_code', code=code) if hasattr(c, 'error') and c.error != 0: current_app.logger.info(c.error_description) return redirect(url_for_security('login')) else: session[u'access_token'] = c.access_token session[u'refresh_token'] = c.refresh_token session[u'expires_in'] = c.expires_in # get open id res = c.request("/oauth2.0/me", parser=parser) res['oauth_consumer_key'] = res['client_id'] # get nickname. user_info = c.request('/user/get_user_info?' + urllib.urlencode(res), method='GET', parser=parser) # 看看是不是已经在数据库中了,没有就写一个 security = current_app.extensions['security'] datastore = security.datastore user = datastore.find_user(openid=res['openid'], provider=provider.lower()) if user is None: user = datastore.create_user(openid=res['openid'], provider=provider.lower(), nickname=user_info['nickname'], avatar=user_info['figureurl_qq_1']) datastore.commit() else: pass #print 'user :'******'is here' login_user(user) next_url = get_url(request.args.get('next')) or get_url(request.form.get('next')) \ or current_app.extensions['security'].post_login_view or '' # 如果用户没有绑定,可以让用户尝试进行首次的帐号绑定。如果不绑也可以在以后再绑 # 2014-12-5 先去掉绑定功能。不然似乎有点复杂过头了。 if user.bind_username is None and user.bind_email is None and (user.bind_remind is None or user.bind_remind ): form_class = _security.login_form form = form_class() form.next.data = next_url return render_template('security/bind_user.html', bind_form=form) return redirect(next_url)
def openid_authenticate(provider): """return openid authenticate url for client to authenticate :param provider: OAuth2 provider. """ oauth_kwargs = current_app.config.get(str.format('OAUTH_{0}', provider.upper())) if oauth_kwargs is None: abort(404); c = Client(**oauth_kwargs) next_url = get_url(request.args.get('next')) or get_url(request.form.get('next')) or '' return redirect(c.auth_uri(redirect_uri=str.format('{0}/openid/{1}/login?next={2}', current_app.config['KINORSI_SERVER_HOST'], provider, next_url), scope='get_user_info,add_t', scope_delim=','))
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( provider_id=cv['provider_id'], provider_user_id=cv['provider_user_id']) 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()) next_url = request.form.get('next', get_post_login_redirect()) redirect_url = (next_url or session.pop( config_value('POST_OAUTH_CONNECT_SESSION_KEY'), get_url(config_value('CONNECT_ALLOW_VIEW')))) do_flash(*msg) return redirect(redirect_url)
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( provider_id=cv['provider_id'], provider_user_id=cv['provider_user_id']) 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 login_handler(response, provider, query): """Shared method to handle the signin process""" connection = _datastore.find_connection(**query) if connection: after_this_request(_commit) token_pair = get_token_pair_from_oauth_response(provider, response) if (token_pair['access_token'] != connection.access_token or token_pair['secret'] != connection.secret): connection.access_token = token_pair['access_token'] connection.secret = token_pair['secret'] _datastore.put(connection) 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 login_handler(response, provider, query): """Shared method to handle the signin process""" connection = _datastore.find_connection(**query) if connection: after_this_request(_commit) token_pair = get_token_pair_from_oauth_response(provider, response) if (token_pair['access_token'] != connection.access_token or token_pair['secret'] != connection.secret): connection.access_token = token_pair['access_token'] connection.secret = token_pair['secret'] _datastore.put(connection) 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_url = 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_url)
def change_mode(self): form = EditModeForm() if form.validate_on_submit(): set_edit_mode(True) flash(u'You are in EDIT mode. Be wise and careful!') return redirect(form.next.data) form.next.data = get_url(request.args.get('next')) or '/' return self.render('admin/edit_mode.html', edit_mode_form=form)
def connect(provider_id): """Starts the provider connection OAuth flow""" provider = get_provider_or_404(provider_id) callback_url = get_authorize_callback('connect', provider_id) allow_view = get_url(config_value('CONNECT_ALLOW_VIEW')) pc = request.form.get('next', allow_view) session[config_value('POST_OAUTH_CONNECT_SESSION_KEY')] = pc return provider.authorize(callback_url)
def logout(): """View function which handles a logout request.""" logout_user() _logger.debug('User logged out') next_url = request.args.get('next', None) post_logout_url = get_url(_security.post_logout_view) return redirect(next_url or post_logout_url)
def connect_callback(provider_id): provider = get_provider_or_404(provider_id) def connect(response): cv = get_connection_values_from_oauth_response(provider, response) return cv cv = provider.authorized_handler(connect)() if cv is None: do_flash('Access was denied by %s' % provider.name, 'error') return redirect(get_url(config_value('CONNECT_DENY_VIEW'))) return connect_handler(cv, provider)
def reset_password(token): """View function that handles a reset password request.""" next = None form = ResetPasswordForm(csrf_enabled=not app.testing) if form.validate_on_submit(): try: user = reset_by_token(token=token, **form.to_dict()) msg = get_message('PASSWORD_RESET') next = (get_url(_security.post_reset_view) or get_url(_security.post_login_view)) except ResetPasswordError, e: msg = (str(e), 'error') if e.user: send_reset_password_instructions(e.user) msg = get_message('PASSWORD_RESET_EXPIRED', within=_security.reset_password_within, email=e.user.email) _logger.debug('Password reset error: ' + msg[0]) do_flash(*msg)
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'))
app=app._get_current_object()) _logger.debug('User %s registered' % user) <<<<<<< HEAD return redirect(_security.post_register_view or _security.post_login_view) do_flash(form.errors, 'error') ======= if not _security.confirmable or _security.login_without_confirmation: after_this_request(_commit) login_user(user) >>>>>>> 8919129c95bb1e27e30a925240811cf63e13ece9 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) @anonymous_user_required def send_login(): """View function that sends login instructions for passwordless login""" form = PasswordlessLoginForm(csrf_enabled=not app.testing) if form.validate_on_submit(): user = _datastore.find_user(**form.to_dict()) if user.is_active():
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(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 not has_error: after_this_request(view_commit) auth_obj = AuthSourceManager(form, [INTERNAL]) session['_auth_source_manager_obj'] = auth_obj.as_dict() if user.login_attempts >= config.MAX_LOGIN_ATTEMPTS > 0: flash( gettext('You successfully reset your password but' ' your account is locked. Please contact ' 'the Administrator.'), 'warning') return redirect(get_post_logout_redirect()) do_flash(*get_message('PASSWORD_RESET')) login_user(user) auth_obj = AuthSourceManager(form, [INTERNAL]) session['auth_source_manager'] = auth_obj.as_dict() 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'))
@login_required def confirm_email_modification(token): """View function which handles a email confirmation request.""" form = ModifyAndConfirmEmailForm() try: if form.validate_cache_data(token): if form.update_data(): current_app.logger.info('Successfully updated email') except Exception, e: current_app.logger.error( 'Fatal error attempting to confirm_email_modification; error: {}'. format(e)) flash(current_app.config['GENERIC_FORM_ERROR_MESSAGE'], 'error') return redirect(get_url('login.user_settings')) def resend_confirmation_email(): form = ResendConfirmationForm() try: if form.validate_on_submit(): if form.update_data(): return redirect(url_for('login.login')) except Exception, e: current_app.logger.error( 'Fatal error attempting to resend confirmation email; error: {}'. format(e)) flash(current_app.config['GENERIC_FORM_ERROR_MESSAGE'], 'error') return render_template('login/resend_confirmation_email.html',