Esempio n. 1
0
    def reset_user_password(self):
        user = User.query.get(request.args['model_id'])
        new_pwd = request.form['new_password']
        return_url = request.headers['Referer']

        if user is None:
            flash(gettext('User not found. Please try again.'), 'error')
            return redirect(return_url)

        if len(new_pwd) < 6:
            flash(
                gettext(
                    'A password must contain at least 6 characters. Please try again.'
                ), 'error')
            return redirect(return_url)

        if ' ' in new_pwd:
            flash(
                gettext('Passwords cannot contain spaces. Please try again.'),
                'error')
            return redirect(return_url)

        change_user_password(user, new_pwd)
        db.session.commit()

        flash(
            gettext(
                'The password has been changed successfully. A notification has been sent to %s.'
                % user.email))
        return redirect(return_url)
Esempio n. 2
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(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'))
Esempio n. 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(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'))
Esempio n. 4
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._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 change_password():
    user = current_user._get_current_object()
    form = _security.change_password_form(MultiDict(request.get_json()))

    if form.validate_on_submit():
        after_this_request(_commit)
        change_user_password(user, form.newPassword.data)
    else:
        return jsonify({'errors': form.errors}), HTTPStatus.BAD_REQUEST

    return jsonify({'token': user.get_auth_token()})
Esempio n. 6
0
 def after_model_change(self, form, model, is_created):
     if form["new_password"].data:
         if not current_app.debug:
             change_user_password(model, form["new_password"].data)
         else:
             model.password = hash_password(form["new_password"].data)
             db.session.commit()
         flash(gettext("The password has been changed successfully."))
     for field in (f for f in form if f.name.startswith(_prefix)):
         fname = _unwrap_field(field.name)
         if fname not in model.profile:
             model.profile.extras[fname] = ProfileExtras(key=fname)
         model.profile[fname] = field.data
     db.session.commit()
Esempio n. 7
0
    def change_password(self):
        schema = RELS['v1.AuthView:change'][request.method]
        args = change_password_options.parse_args()

        try:
            validate(args, schema, format_checker=FormatChecker())
        except ValidationError as e:
            return dict(status=400, message=e.message), 400

        if not verify_password(args.get('old'), current_user.password):
            return dict(status=409, message='Invalid credentials'), 409

        change_user_password(current_user, password=args.get('new'))
        return {'status': 200, 'message': 'Password updated', 'user': generate_response_dict(user=current_user)}
Esempio n. 8
0
    def post(self, user_id=None, user=None):
        """ Update a user """
        if user is None:
            user = user_or_404(user_id)

        args = USER_EDIT_PARSER.parse_args(strict=True)
        args = clean_attrs(args)

        try:
            new_password = args.pop('password')
        except KeyError:
            pass
        else:
            change_user_password(user, new_password)

        rest_set_roles_perms(user, args.pop('roles'))
        return self.handle_write(user, data=args)
Esempio n. 9
0
def admin_user_reset_password(user_id):
    user = models.RegisteredUser.query.get_or_404(user_id)
    if user.is_ldap:
        message = (
            'The password can be changed only from the EIONET website ' + '(' +
            os.environ.get('EEA_PASSWORD_RESET') + ').')
        return render_template('message.html', message=message)

    form = ResetPasswordForm()

    if form.validate_on_submit():
        change_user_password(user, form.password.data)
        models.db.session.commit()
        msg = "Password successfully reseted."
        flash(msg, 'success')
    return render_template('auth/admin_user_reset_password.html', **{
        'user': user,
        'form': form,
    })
Esempio n. 10
0
def change_password():
    if current_user.is_anonymous:
        message = "You must log in before changing your password."
        return render_template('message.html', message=message)

    if current_user.is_ldap:
        message = (
            'Your password can be changed only from the EIONET website ' +
            '(' + os.environ.get('EEA_PASSWORD_RESET') + ').')
        return render_template('message.html', message=message)

    form = ChangePasswordForm()

    if form.validate_on_submit():
        change_user_password(current_user, form.new_password.data)
        models.db.session.commit()
        msg = "Your password has been changed. Please log in again."
        flash(msg, 'success')
        return redirect(url_for(HOMEPAGE_VIEW_NAME))

    return render_template('auth/change_password.html', **{
        'form': form,
    })