コード例 #1
0
ファイル: __init__.py プロジェクト: asheshv/pgadmin4
    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'))
コード例 #2
0
ファイル: __init__.py プロジェクト: asheshv/pgadmin4
    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'))
コード例 #3
0
    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(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(_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'))
コード例 #4
0
ファイル: __init__.py プロジェクト: ototan999/pgadmin4
    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'))
コード例 #5
0
ファイル: datastore.py プロジェクト: ziyangzhangbj/artemis
    def query_ldap_user(self, identifier):
        """Get information about a user throught AD."""
        con = self._get_ldap_con()

        result = con.search(
            search_base=config_value("LDAP_BASE_DN"),
            search_filter=config_value("LDAP_SEARCH_FILTER").format(
                identifier),
            search_scope=ldap3.SUBTREE,
            attributes=ldap3.ALL_ATTRIBUTES,
        )

        data = con.entries
        self._close_ldap_con(con)

        if result and data:
            return (data[0].entry_dn, data[0])
        raise LDAPExceptionError("User not found in LDAP")
コード例 #6
0
def send_reset_password_instructions(user):
    """Sends the reset password instructions email for the specified user.
    :param user: The user to send the instructions to
    """
    token = generate_reset_password_token(user)
    reset_link = frontend_url('reset-password', token=token)

    print(f"[+] The security is {_security}")

    if config_value('SEND_PASSWORD_RESET_EMAIL'):
        send_mail(config_value('EMAIL_SUBJECT_PASSWORD_RESET'),
                  user.email,
                  'reset_instructions',
                  user=user,
                  reset_link=reset_link)

    reset_password_instructions_sent.send(app._get_current_object(),
                                          user=user,
                                          token=token)
コード例 #7
0
ファイル: auth.py プロジェクト: infobyte/faraday
def send_reset_password_instructions(user):
    """Sends the reset password instructions email for the specified user.
    :param user: The user to send the instructions to
    """
    token = generate_reset_password_token(user)

    url_data = urlparse(request.base_url)
    reset_link = f"{url_data.scheme}://{url_data.netloc}/#resetpass/{token}/"

    if config_value('SEND_PASSWORD_RESET_EMAIL'):
        send_mail(config_value('EMAIL_SUBJECT_PASSWORD_RESET'),
                  user.email,
                  'reset_instructions',
                  user=user,
                  reset_link=reset_link)

    reset_password_instructions_sent.send(app._get_current_object(),
                                          user=user,
                                          token=token)
コード例 #8
0
def admin_login():
    form_class = security.login_form
    form = form_class(request.form)
    if form.validate_on_submit():
        login_user(form.user, remember=form.remember.data)
        after_this_request(_commit)
        return redirect(form.next.data or url_for('admin.index'))

    return security.render_template(config_value('LOGIN_USER_TEMPLATE'),
                                    login_user_form=form,
                                    **_ctx('login'))
コード例 #9
0
def send_mail(subject, recipients, template, language, **context):
    """Send an email via the Flask-Mail extension.

    :param subject: Email subject
    :param recipients: List of email recipients
    :param template: The name of the email template
    :param context: The context to render the template with
    """
    sender = config_value('EMAIL_SENDER')
    msg = Message(subject, sender=sender, recipients=recipients)

    ctx = ('email', template, language)

    if config_value('EMAIL_PLAINTEXT'):
        msg.body = render_template('%s/%s_%s.txt' % ctx, **context)
    # if config_value('EMAIL_HTML'):
    #     msg.html = render_template('%s/%s.html' % ctx, **context)

    mail = current_app.extensions.get('mail')
    mail.send(msg)
コード例 #10
0
ファイル: forms.py プロジェクト: cravattlab/cravattdb
    def validate(self):
        """Validate LDAP logins against AD."""
        if not super(LDAPLoginForm, self).validate():
            return False

        if self.email.data.strip() == '':
            self.email.errors.append(get_message('USERID_NOT_PROVIDED')[0])
            return False

        if self.password.data.strip() == '':
            self.password.errors.append(
                get_message('PASSWORD_NOT_PROVIDED')[0])
            return False

        try:
            user_dn, ldap_data = _datastore.query_ldap_user(self.email.data)

            if user_dn is None:
                self.email.errors.append(get_message('USER_DOES_NOT_EXIST')[0])
                return False

            if not _datastore.verify_password(user_dn, self.password.data):
                self.password.errors.append(get_message('INVALID_PASSWORD')[0])
                return False

            ldap_email = ldap_data[config_value('LDAP_EMAIL_FIELDNAME')].value
            password = encrypt_password(self.password.data)

            if _datastore.find_user(email=ldap_email):
                self.user = _datastore.get_user(ldap_email)
                # note that this is being stored per user login
                self.user.password = password
            else:
                self.user = _datastore.create_user(email=ldap_email,
                                                   password=password)
                _datastore.commit()
        except ldap3.LDAPExceptionError:
            self.password.errors.append(get_message('LDAP_SERVER_DOWN')[0])
            self.user = _datastore.get_user(self.email.data)
            if not self.user.password:
                self.password.errors.append(get_message('PASSWORD_NOT_SET')[0])
                return False
            if not verify_and_update_password(self.password.data, self.user):
                self.password.errors.append(get_message('INVALID_PASSWORD')[0])
                return False
            if requires_confirmation(self.user):
                self.email.errors.append(
                    get_message('CONFIRMATION_REQUIRED')[0])
                return False
            if not self.user.is_active:
                self.email.errors.append(get_message('DISABLED_ACCOUNT')[0])
                return False

        return True
コード例 #11
0
ファイル: __init__.py プロジェクト: tanderegg/pgadmin4
    def forgot_password():
        """View function that handles a forgotten password request."""
        has_error = False
        form_class = _security.forgot_password_form

        if request.json:
            form = form_class(MultiDict(request.json))
        else:
            form = form_class()

        if form.validate_on_submit():
            try:
                send_reset_password_instructions(form.user)
            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:
                do_flash(*get_message('PASSWORD_RESET_REQUEST',
                                      email=form.user.email))

        if request.json and not has_error:
            return _render_json(form, include_user=False)

        return _security.render_template(
            config_value('FORGOT_PASSWORD_TEMPLATE'),
            forgot_password_form=form,
            **_ctx('forgot_password'))
コード例 #12
0
ファイル: __init__.py プロジェクト: asheshv/pgadmin4
    def forgot_password():
        """View function that handles a forgotten password request."""
        has_error = False
        form_class = _security.forgot_password_form

        if request.json:
            form = form_class(MultiDict(request.json))
        else:
            form = form_class()

        if form.validate_on_submit():
            try:
                send_reset_password_instructions(form.user)
            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:
                do_flash(*get_message('PASSWORD_RESET_REQUEST',
                                      email=form.user.email))

        if request.json and not has_error:
            return _render_json(form, include_user=False)

        return _security.render_template(
            config_value('FORGOT_PASSWORD_TEMPLATE'),
            forgot_password_form=form,
            **_ctx('forgot_password'))
コード例 #13
0
def register_user(**kwargs):
    if kwargs.pop('random_password', False) or len(kwargs['password']) == 0:
        kwargs['password'] = _randompassword()

    # hash password so that we never store the original
    kwargs['password'] = hash_password(kwargs['password'])

    # pop ask_confirm value before kwargs is presented to create_user()
    ask_confirm = kwargs.pop('ask_confirm', False)

    # generate a User record and commit it
    kwargs['active'] = True
    roles = kwargs.get('roles', [])
    roles_step1 = [db.session.query(Role).filter_by(name=r).first() for r in roles]
    roles_step2 = [x for x in roles_step1 if x is not None]
    kwargs['roles'] = roles_step2
    kwargs['fs_uniquifier'] = uuid.uuid4().hex

    user = User(**kwargs)

    db.session.add(user)
    db.session.commit()

    # send confirmation email if we have been asked to
    if ask_confirm:
        confirmation_link, token = generate_confirmation_link(user)
        do_flash(*get_message('CONFIRM_REGISTRATION', email=user.email))

        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)

    else:
        user.confirmed_at = datetime.now()
        db.session.commit()

    return user
コード例 #14
0
    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(_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'))
コード例 #15
0
ファイル: forms.py プロジェクト: Ceredira/CerediraTess
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     if not self.next.data:
         self.next.data = request.args.get("next", "")
     self.remember.default = config_value("DEFAULT_REMEMBER_ME")
     if (current_app.extensions["security"].recoverable
             and not self.password.description):
         html = Markup('<a href="{url}">{message}</a>'.format(
             url=url_for_security("forgot_password"),
             message=get_message("FORGOT_PASSWORD")[0],
         ))
         self.password.description = html
     self.requires_confirmation = False
コード例 #16
0
def register_user(should_confirm, **kwargs):
    confirmation_link, token = None, None
    kwargs['password'] = encrypt_password(kwargs['password'])
    user = user_datastore.create_user(**kwargs)
    user_datastore.commit()
    flash(gettext('User created successfully'))
    if should_confirm:
        confirmation_link, token = generate_confirmation_link(user)
        do_flash(*get_message('CONFIRM_REGISTRATION', email=user.email))
        send_mail(
            config_value('EMAIL_SUBJECT_REGISTER'),
            user.email, 'welcome', user=user, confirmation_link=confirmation_link)
    user_registered.send(app, user=user, confirm_token=token)
コード例 #17
0
    def send_reset_password_instructions(user):
        """Sends the reset password instructions email for the specified user.

        :param user: The user to send the instructions to
        """
        token = generate_reset_password_token(user)
        reset_link = url_for('browser.reset_password', token=token,
                             _external=True)

        send_mail(config_value('EMAIL_SUBJECT_PASSWORD_RESET'), user.email,
                  'reset_instructions',
                  user=user, reset_link=reset_link)

        reset_password_instructions_sent.send(
            current_app._get_current_object(),
            user=user, token=token)
コード例 #18
0
ファイル: __init__.py プロジェクト: asheshv/pgadmin4
    def send_reset_password_instructions(user):
        """Sends the reset password instructions email for the specified user.

        :param user: The user to send the instructions to
        """
        token = generate_reset_password_token(user)
        reset_link = url_for('browser.reset_password', token=token,
                             _external=True)

        send_mail(config_value('EMAIL_SUBJECT_PASSWORD_RESET'), user.email,
                  'reset_instructions',
                  user=user, reset_link=reset_link)

        reset_password_instructions_sent.send(
            current_app._get_current_object(),
            user=user, token=token)
コード例 #19
0
ファイル: utils.py プロジェクト: zannkukai/rero-ils
def send_notification_to_location(loan, item, location):
    """Send a notification to the location defined email.

    :param loan: the loan to be parsed
    :param item: the requested item
    :param location: the location to inform
    """
    if not location.get('send_notification', False) \
            or not location.get('notification_email'):
        return
    template = 'email/others/location_notification.txt'
    recipient = location.get('notification_email')
    msg = TemplatedMessage(template_body=template,
                           sender=config_value('EMAIL_SENDER'),
                           recipients=[recipient],
                           ctx=_build_notification_email_context(
                               loan, item, location))
    text = msg.body.split('\n')
    msg.subject = text[0]
    msg.body = '\n'.join(text[1:])
    send_email.run(msg.__dict__)
コード例 #20
0
ファイル: forms.py プロジェクト: radusuciu/ctesi
    def validate(self):
        """Validate LDAP logins against AD."""
        if not super(LDAPLoginForm, self).validate():
            return False

        if self.email.data.strip() == '':
            self.email.errors.append(get_message('USERID_NOT_PROVIDED')[0])
            return False

        if self.password.data.strip() == '':
            self.password.errors.append(
                get_message('PASSWORD_NOT_PROVIDED')[0])
            return False

        try:
            # first we try authenticating against ldap
            user_dn, ldap_data = _datastore.query_ldap_user(self.email.data)

            if not _datastore.verify_password(user_dn, self.password.data):
                self.password.errors.append(get_message('INVALID_PASSWORD')[0])
                return False

            ldap_email = ldap_data[config_value('LDAP_EMAIL_FIELDNAME')].value
            password = encrypt_password(self.password.data)

            if _datastore.find_user(email=ldap_email):
                self.user = _datastore.get_user(ldap_email)
                # note that this is being stored per user login
                self.user.password = password
            else:
                self.user = _datastore.create_user(email=ldap_email,
                                                   password=password)
                _datastore.commit()
        except LDAPExceptionError:
            self.email.errors.append(get_message('LDAP_SERVER_DOWN')[0])
            return self._try_local_auth()
        except UserNotFoundInLDAP:
            return self._try_local_auth()

        return True
コード例 #21
0
 def send_mail(self, data):
     """Send email."""
     notification_type = data.get('notification_type')
     language = data['loan']['patron']['communication_language']
     template = 'email/{type}/{lang}'.format(type=notification_type,
                                             lang=language)
     recipient = data['loan']['patron']['email']
     msg = TemplatedMessage(
         # template_html='{template}.html'.format(template=template),
         template_body='{template}.txt'.format(template=template),
         sender=config_value('EMAIL_SENDER'),
         recipients=[recipient],
         ctx=data['loan'])
     text = msg.body.split('\n')
     msg.subject = text[0]
     msg.body = '\n'.join(text[1:])
     try:
         send_email.run(msg.__dict__)
         # TODO: investigate why delay does not work
         # send_email.delay(msg.__dict__)
         # current_app.extensions['mail'].send(msg)
     except Exception as e:
         raise (e)
コード例 #22
0
ファイル: __init__.py プロジェクト: chadmpdev/pgadmin4
    def forgot_password():
        """View function that handles a forgotten password request."""
        has_error = False
        form_class = _security.forgot_password_form

        if request.json:
            form = form_class(MultiDict(request.json))
        else:
            form = form_class()

        if form.validate_on_submit():
            # Check the Authentication source of the User
            user = User.query.filter_by(
                email=form.data['email'],
                auth_source=current_app.PGADMIN_DEFAULT_AUTH_SOURCE).first()

            if user is None:
                # If the user is not an internal user, raise the exception
                flash(
                    gettext(
                        'Your account is authenticated using an '
                        'external {} source. '
                        'Please contact the administrators of this '
                        'service if you need to reset your password.').format(
                            form.user.auth_source), 'danger')
                has_error = True
            if not has_error:
                try:
                    send_reset_password_instructions(form.user)
                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:
                do_flash(*get_message('PASSWORD_RESET_REQUEST',
                                      email=form.user.email))

        if request.json and not has_error:
            return default_render_json(form, include_user=False)

        return _security.render_template(
            config_value('FORGOT_PASSWORD_TEMPLATE'),
            forgot_password_form=form,
            **_ctx('forgot_password'))
コード例 #23
0
    def validate(self):
        """Validate LDAP logins against AD."""
        if not super(LDAPLoginForm, self).validate():
            return False

        if self.email.data.strip() == "":
            self.email.errors.append(get_message("USERID_NOT_PROVIDED")[0])
            return False

        if self.password.data.strip() == "":
            self.password.errors.append(get_message("PASSWORD_NOT_PROVIDED")[0])
            return False

        try:
            admin_user = _datastore.get_user(1)
            if self.email.data == admin_user.username:
                current_app.artemis_logger.info("Super-user login")
                return self._try_local_auth()

            # first we try authenticating against ldap
            user_dn, ldap_data = _datastore.query_ldap_user(self.email.data)

            if not _datastore.verify_password(user_dn, self.password.data):
                self.password.errors.append(get_message("INVALID_PASSWORD")[0])
                return False

            ldap_email = ldap_data[config_value("LDAP_EMAIL_FIELDNAME")].value
            password = encrypt_password(self.password.data)

            self.user = _datastore.find_user(email=ldap_email)
            if self.user:
                # note that this is being stored per user login
                self.user.password = password
            else:
                self.user = _datastore.create_user(
                    username=ldap_email,
                    email=ldap_email,
                    password=password,
                    active=True,
                )

            # need to somehow decide what role they are
            groups = config_value("LDAP_ADMIN_GROUPS")
            field = ldap_data[config_value("LDAP_ADMIN_GROUPS_FIELDNAME")].values

            if (
                isinstance(field, str) and any([group == field for group in groups])
            ) or (
                isinstance(field, list) and any([group in field for group in groups])
            ):
                add_role = _datastore.find_role("admin")
                remove_role = _datastore.find_role("user")
            else:
                add_role = _datastore.find_role("user")
                remove_role = _datastore.find_role("admin")
            _datastore.add_role_to_user(self.user, add_role)
            _datastore.remove_role_from_user(self.user, remove_role)
            _datastore.commit()
        except LDAPKeyError:
            current_app.artemis_logger.exception("")
            self.email.errors.append("LDAP Key failure")
            if self.user:
                add_role = _datastore.find_role("user")
                remove_role = _datastore.find_role("admin")
                _datastore.add_role_to_user(self.user, add_role)
                _datastore.remove_role_from_user(self.user, remove_role)
                _datastore.commit()
                return True
            return False
        except LDAPSocketOpenError:
            current_app.artemis_logger.info("LDAP offline.. Trying local auth")
            self.email.errors.append("LDAP Server offline")
            return self._try_local_auth()
        except LDAPExceptionError:
            current_app.artemis_logger.exception("")
            self.email.errors.append("LDAP Auth failed")
            return False

        return True
コード例 #24
0
    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'))
コード例 #25
0
ファイル: views.py プロジェクト: gothm/flask-security
def create_blueprint(app, name, import_name, **kwargs):
    """Creates the security extension blueprint"""

    bp = Blueprint(name, import_name, **kwargs)

    if config_value('PASSWORDLESS', app=app):
        bp.route(config_value('LOGIN_URL', app=app),
                 methods=['GET', 'POST'],
                 endpoint='login')(send_login)

        bp.route(config_value('LOGIN_URL', app=app) + '/<token>',
                 methods=['GET'],
                 endpoint='token_login')(token_login)
    else:
        bp.route(config_value('LOGIN_URL', app=app),
                 methods=['GET', 'POST'],
                 endpoint='login')(login)

    bp.route(config_value('LOGOUT_URL', app=app),
             endpoint='logout')(logout)

    if config_value('REGISTERABLE', app=app):
        bp.route(config_value('REGISTER_URL', app=app),
                 methods=['GET', 'POST'],
                 endpoint='register')(register)

    if config_value('RECOVERABLE', app=app):
        bp.route(config_value('RESET_URL', app=app),
                 methods=['GET', 'POST'],
                 endpoint='forgot_password')(forgot_password)
        bp.route(config_value('RESET_URL', app=app) + '/<token>',
                 methods=['GET', 'POST'],
                 endpoint='reset_password')(reset_password)

    if config_value('CONFIRMABLE', app=app):
        bp.route(config_value('CONFIRM_URL', app=app),
                 methods=['GET', 'POST'],
                 endpoint='send_confirmation')(send_confirmation)
        bp.route(config_value('CONFIRM_URL', app=app) + '/<token>',
                 methods=['GET', 'POST'],
                 endpoint='confirm_email')(confirm_email)

    return bp