Python flask_login.current_user.password() Examples

The following are 30 code examples of flask_login.current_user.password(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask_login.current_user , or try the search function .
Example #1
Source File: web.py    From calibre-web with GNU General Public License v3.0 7 votes vote down vote up
def load_user_from_auth_header(header_val):
    if header_val.startswith('Basic '):
        header_val = header_val.replace('Basic ', '', 1)
    basic_username = basic_password = ''
    try:
        header_val = base64.b64decode(header_val).decode('utf-8')
        basic_username = header_val.split(':')[0]
        basic_password = header_val.split(':')[1]
    except (TypeError, UnicodeDecodeError, binascii.Error):
        pass
    user = _fetch_user_by_name(basic_username)
    if user and config.config_login_type == constants.LOGIN_LDAP and services.ldap:
        if services.ldap.bind_user(str(user.password), basic_password):
            return user
    if user and check_password_hash(str(user.password), basic_password):
        return user
    return 
Example #2
Source File: forms.py    From Flask-User with MIT License 6 votes vote down vote up
def validate(self):
        # Use feature config to remove unused form fields
        user_manager =  current_app.user_manager
        if not user_manager.USER_REQUIRE_RETYPE_PASSWORD:
            delattr(self, 'retype_password')
        # # Add custom password validator if needed
        # has_been_added = False
        # for v in self.new_password.validators:
        #     if v==user_manager.password_validator:
        #         has_been_added = True
        # if not has_been_added:
        #     self.new_password.validators.append(user_manager.password_validator)
        # Validate field-validators
        if not super(ResetPasswordForm, self).validate(): return False
        # All is well
        return True 
Example #3
Source File: views.py    From BhagavadGita with GNU General Public License v3.0 6 votes vote down vote up
def reset_password_request():
    """Respond to existing user's request to reset their password."""
    badge_list = []
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    form = RequestResetPasswordForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            token = user.generate_password_reset_token()
            reset_link = url_for(
                'account.reset_password', token=token, _external=True)
            send_email(
                recipient=user.email,
                subject='Reset Your Password',
                template='account/email/reset_password',
                user=user,
                reset_link=reset_link,
                next=request.args.get('next'))
        flash(
            'A password reset link has been sent to {}.'.format(
                form.email.data), 'warning')
        return redirect(url_for('account.login'))
    return render_template(
        'account/reset_password.html', form=form, badge_list=badge_list) 
Example #4
Source File: views.py    From BhagavadGita with GNU General Public License v3.0 6 votes vote down vote up
def reset_password(token):
    """Reset an existing user's password."""
    badge_list = []
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is None:
            flash('Invalid email address.', 'form-error')
            return redirect(url_for('main.index'))
        if user.reset_password(token, form.new_password.data):
            flash('Your password has been updated.', 'form-success')
            return redirect(url_for('account.login'))
        else:
            flash('The password reset link is invalid or has expired.',
                  'form-error')
            return redirect(url_for('main.index'))
    return render_template(
        'account/reset_password.html', form=form, badge_list=badge_list) 
Example #5
Source File: views.py    From BhagavadGita with GNU General Public License v3.0 6 votes vote down vote up
def change_password():
    """Change an existing user's password."""
    badge_list = []
    form = ChangePasswordForm()
    if form.validate_on_submit():
        if current_user.verify_password(form.old_password.data):
            current_user.password = form.new_password.data
            db.session.add(current_user)
            db.session.commit()
            flash('Your password has been updated.', 'form-success')
            return redirect(url_for('main.index'))
        else:
            flash('Original password is invalid.', 'form-error')
    return render_template(
        'account/manage.html',
        form=form,
        user=current_user,
        badge_list=badge_list) 
Example #6
Source File: user.py    From arch-security-tracker with MIT License 6 votes vote down vote up
def validate(self):
        rv = BaseForm.validate(self)
        if not rv:
            return False

        if current_user.name in self.password.data:
            self.password.errors.append(ERROR_PASSWORD_CONTAINS_USERNAME)
            return False

        if self.password.data != self.password_repeat.data:
            self.password_repeat.errors.append(ERROR_PASSWORD_REPEAT_MISMATCHES)
            return False

        if not compare_digest(current_user.password, hash_password(self.password_current.data, current_user.salt)):
            self.password_current.errors.append(ERROR_PASSWORD_INCORRECT)
            return False

        return True 
Example #7
Source File: views.py    From gitmark with GNU General Public License v2.0 6 votes vote down vote up
def post(self):
        if request.form.get('login_github'):
            session['oauth_callback_type'] = 'login'
            return github_auth.github_auth()
            # return 'login_github'

        form = forms.LoginForm(obj=request.form)
        if form.validate():
            try:
                user = models.User.objects.get(username=form.username.data)
            except models.User.DoesNotExist:
                user = None

            if user and user.verify_password(form.password.data):
                login_user(user, form.remember_me.data)
                user.last_login = datetime.datetime.now
                user.save()
                identity_changed.send(current_app._get_current_object(), identity=Identity(user.username))
                return redirect(request.args.get('next') or url_for('main.index'))
            flash('Invalid username or password', 'danger')
        return self.get(form=form) 
Example #8
Source File: views.py    From gitmark with GNU General Public License v2.0 6 votes vote down vote up
def post(self, create_su=False):
        if request.form.get('github'):
            session['oauth_callback_type'] = 'register'
            return github_auth.github_auth()
            # return 'github register'

        form = forms.RegistrationForm(obj=request.form)
        if form.validate():
            user = models.User()
            user.username = form.username.data
            user.password = form.password.data
            user.email = form.email.data

            user.display_name = user.username
            user.avatar_url = default_user_image

            if create_su and GitmarkSettings['allow_su_creation']:
                user.is_superuser = True
            user.save()

            return redirect(url_for('main.index'))
        return self.get(form=form, create_su=create_su) 
Example #9
Source File: views.py    From gitmark with GNU General Public License v2.0 6 votes vote down vote up
def add_user():
    form = forms.RegistrationForm()
    if form.validate_on_submit():
        user = models.User()
        user.username = form.username.data
        user.password = form.password.data
        user.email = form.email.data

        user.display_name = user.username
        user.avatar_url = default_user_image

        user.save()

        return redirect(url_for('accounts.users'))

    return render_template('accounts/registration.html', form=form) 
Example #10
Source File: forms.py    From Flask-User with MIT License 6 votes vote down vote up
def validate(self):
        # Use feature config to remove unused form fields
        user_manager =  current_app.user_manager
        if not user_manager.USER_REQUIRE_RETYPE_PASSWORD:
            delattr(self, 'retype_password')

        # # Add custom password validator if needed
        # has_been_added = False
        # for v in self.new_password.validators:
        #     if v==user_manager.password_validator:
        #         has_been_added = True
        # if not has_been_added:
        #     self.new_password.validators.append(user_manager.password_validator)

        # Validate field-validators
        if not super(ChangePasswordForm, self).validate(): return False

        # Verify current_user and current_password
        if not current_user or not user_manager.verify_password(self.old_password.data, current_user.password):
            self.old_password.errors.append(_('Old Password is incorrect'))
            return False

        # All is well
        return True 
Example #11
Source File: views.py    From gitmark with GNU General Public License v2.0 5 votes vote down vote up
def get(self, token):
        if current_user.is_email_confirmed:
            return redirect(url_for('accounts.password'))

        if current_user.confirm_email(token):
            flash('Your email has been confirmed', 'success')
        else:
            flash('The confirmation link is invalid or has expired', 'danger')

        return redirect(url_for('accounts.password')) 
Example #12
Source File: user_settings.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def set_password():
    """
    Set a new password for the logged in user..

    Notes
    -----
    Expects json containing 'password' and 'newPassword' keys.
    Checks the password is the same as the existing one and that
    the new password is strong.
    """
    edits = request.get_json()
    current_app.logger.debug("User tried to change password.")
    try:
        old_pass = edits["password"]
    except KeyError:
        raise InvalidUsage("Missing old password.", payload={"bad_field": "password"})
    try:
        new_pass = edits["newPassword"]
    except KeyError:
        raise InvalidUsage(
            "Missing new password.", payload={"bad_field": "newPassword"}
        )

    if current_user.is_correct_password(old_pass):
        if len(new_pass) == 0 or zxcvbn(new_pass)["score"] < 4:
            raise InvalidUsage(
                "Password not complex enough.", payload={"bad_field": "newPassword"}
            )
        current_user.password = new_pass
        db.session.add(current_user)
        db.session.commit()
        current_app.logger.debug("User password changed.")
        return jsonify({}), 200
    else:

        raise InvalidUsage("Password incorrect.", payload={"bad_field": "password"}) 
Example #13
Source File: user_manager__views.py    From Flask-User with MIT License 5 votes vote down vote up
def change_password_view(self):
        """ Prompt for old password and new password and change the user's password."""

        # Initialize form
        form = self.ChangePasswordFormClass(request.form)

        # Process valid POST
        if request.method == 'POST':
            if not form.validate():
                flash(_('There was an error changing your password.'), 'error')
                return redirect(url_for('user.change_password'))

            # Hash password
            new_password = form.new_password.data
            password_hash = self.hash_password(new_password)

            # Update user.password
            current_user.password = password_hash
            self.db_manager.save_object(current_user)
            self.db_manager.commit()

            # Send password_changed email
            if self.USER_ENABLE_EMAIL and self.USER_SEND_PASSWORD_CHANGED_EMAIL:
                self.email_manager.send_password_changed_email(current_user)

            # Send changed_password signal
            signals.user_changed_password.send(current_app._get_current_object(), user=current_user)

            # Flash a system message
            flash(_('Your password has been changed successfully.'), 'success')

            # Redirect to 'next' URL
            safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_CHANGE_PASSWORD_ENDPOINT)
            return redirect(safe_next_url)

        # Render form
        self.prepare_domain_translations()
        return render_template(self.USER_CHANGE_PASSWORD_TEMPLATE, form=form) 
Example #14
Source File: views.py    From gitmark with GNU General Public License v2.0 5 votes vote down vote up
def register(create_su=False):
    if not GitmarkSettings['allow_registration']:
        msg = 'Register is forbidden, please contact administrator'
        return msg

    if create_su and not GitmarkSettings['allow_su_creation']:
        msg = 'Register superuser is forbidden, please contact administrator'
        return msg

    form = forms.RegistrationForm()
    if form.validate_on_submit():
        user = models.User()
        user.username = form.username.data
        user.password = form.password.data
        user.email = form.email.data

        user.display_name = user.username
        user.avatar_url = default_user_image

        if create_su and GitmarkSettings['allow_su_creation']:
            user.is_superuser = True
        user.save()

        return redirect(url_for('main.index'))

    return render_template('accounts/registration.html', form=form) 
Example #15
Source File: user_manager__views.py    From Flask-User with MIT License 5 votes vote down vote up
def change_username_view(self):
        """ Prompt for new username and old password and change the user's username."""

        # Initialize form
        form = self.ChangeUsernameFormClass(request.form)

        # Process valid POST
        if request.method == 'POST' and form.validate():

            # Change username
            new_username = form.new_username.data
            current_user.username=new_username
            self.db_manager.save_object(current_user)
            self.db_manager.commit()

            # Send username_changed email
            if self.USER_ENABLE_EMAIL and self.USER_SEND_USERNAME_CHANGED_EMAIL:
                self.email_manager.send_username_changed_email(current_user)

            # Send changed_username signal
            signals.user_changed_username.send(current_app._get_current_object(), user=current_user)

            # Flash a system message
            flash(_("Your username has been changed to '%(username)s'.", username=new_username), 'success')

            # Redirect to 'next' URL
            safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_CHANGE_USERNAME_ENDPOINT)
            return redirect(safe_next_url)

        # Render form
        self.prepare_domain_translations()
        return render_template(self.USER_CHANGE_USERNAME_TEMPLATE, form=form) 
Example #16
Source File: user_manager__views.py    From Flask-User with MIT License 5 votes vote down vote up
def forgot_password_view(self):
        """Prompt for email and send reset password email."""

        # Initialize form
        form = self.ForgotPasswordFormClass(request.form)

        # Process valid POST
        if request.method == 'POST' and form.validate():
            # Get User and UserEmail by email
            email = form.email.data
            user, user_email = self.db_manager.get_user_and_user_email_by_email(email)

            if user and user_email:
                # Send reset_password email
                self.email_manager.send_reset_password_email(user, user_email)

                # Send forgot_password signal
                signals.user_forgot_password.send(current_app._get_current_object(), user=user)

            # Flash a system message
            flash(_(
                "A reset password email has been sent to '%(email)s'. Open that email and follow the instructions to reset your password.",
                email=email), 'success')

            # Redirect to the login page
            return redirect(self._endpoint_url(self.USER_AFTER_FORGOT_PASSWORD_ENDPOINT))

        # Render form
        self.prepare_domain_translations()
        return render_template(self.USER_FORGOT_PASSWORD_TEMPLATE, form=form) 
Example #17
Source File: forms.py    From Flask-User with MIT License 5 votes vote down vote up
def validate(self):
        # remove certain form fields depending on user manager config
        user_manager =  current_app.user_manager
        if not user_manager.USER_ENABLE_USERNAME:
            delattr(self, 'username')
        if not user_manager.USER_ENABLE_EMAIL:
            delattr(self, 'email')
        if not user_manager.USER_REQUIRE_RETYPE_PASSWORD:
            delattr(self, 'retype_password')
        # # Add custom username validator if needed
        # if user_manager.USER_ENABLE_USERNAME:
        #     has_been_added = False
        #     for v in self.username.validators:
        #         if v==user_manager.username_validator:
        #             has_been_added = True
        #     if not has_been_added:
        #         self.username.validators.append(user_manager.username_validator)
        # # Add custom password validator if needed
        # has_been_added = False
        # for v in self.password.validators:
        #     if v==user_manager.password_validator:
        #         has_been_added = True
        # if not has_been_added:
        #     self.password.validators.append(user_manager.password_validator)
        # Validate field-validators
        if not super(RegisterForm, self).validate():
            return False
        # All is well
        return True 
Example #18
Source File: inventory.py    From eNMS with GNU General Public License v3.0 5 votes vote down vote up
def desktop_connection(self, id, **kwargs):
        device = db.fetch("device", id=id, rbac="connect")
        credentials = (
            (device.username, self.get_password(device.password))
            if kwargs["credentials"] == "device"
            else (current_user.name, self.get_password(current_user.password))
            if kwargs["credentials"] == "user"
            else (kwargs["username"], kwargs["password"])
        )
        uuid, port = str(uuid4()), self.get_ssh_port()
        session = db.factory(
            "session",
            name=uuid,
            user=current_user.name,
            timestamp=self.get_time(),
            device=device.id,
        )
        db.session.commit()
        try:
            ssh_connection = SshConnection(
                device.ip_address, *credentials, session.id, uuid, port
            )
            Thread(
                target=ssh_connection.start_session, args=(session.id, uuid, port),
            ).start()
            return {
                "port": port,
                "username": uuid,
                "device_name": device.name,
                "device_ip": device.ip_address,
            }
        except Exception as exc:
            return {"error": exc.args} 
Example #19
Source File: views.py    From BhagavadGita with GNU General Public License v3.0 5 votes vote down vote up
def register():
    """Register a new user, and send them a confirmation email."""
    badge_list = []
    form = RegistrationForm()

    if form.validate_on_submit():
        max_id = db.session.query(db.func.max(User.id)).scalar()
        user = User(
            id=max_id + 1,
            first_name=form.first_name.data,
            last_name=form.last_name.data,
            email=form.email.data,
            password=form.password.data)
        db.session.add(user)
        db.session.commit()
        token = user.generate_confirmation_token()
        confirm_link = url_for('account.confirm', token=token, _external=True)
        send_email(
            recipient=user.email,
            subject='Confirm Your Account',
            template='account/email/confirm',
            user=user,
            confirm_link=confirm_link)
        flash('A confirmation link has been sent to {}.'.format(user.email),
              'warning')
        return redirect(url_for('main.index'))
    return render_template(
        'account/register.html', form=form, badge_list=badge_list) 
Example #20
Source File: views.py    From BhagavadGita with GNU General Public License v3.0 5 votes vote down vote up
def login():
    """Log in an existing user."""
    badge_list = []
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.password_hash is not None and \
                user.verify_password(form.password.data):
            login_user(user, form.remember_me.data)
            flash('You are now logged in. Welcome back!', 'success')
            return redirect(request.args.get('next') or url_for('main.index'))
        else:
            flash('Invalid email or password.', 'form-error')
    return render_template(
        'account/login.html', form=form, badge_list=badge_list) 
Example #21
Source File: views.py    From Flashcards with MIT License 5 votes vote down vote up
def password_reset(token):
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    form = PasswordResetForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is None:
            return redirect(url_for('main.index'))
        if user.reset_password(token, form.password.data):
            flash('Your password has been updated.')
            return redirect(url_for('auth.login'))
        else:
            flash('Could not Reset Password')
            return redirect(url_for('main.index'))
    return render_template('auth/reset_password.html', form=form) 
Example #22
Source File: views.py    From Simpleblog with MIT License 5 votes vote down vote up
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        user = User(email=form.email.data,
                    nickname=form.nickname.data,
                    password=form.password.data)
        db.session.add(user)
        flash('你可以登录了。')
        return redirect(url_for('auth.login'))
    return render_template('auth/register.html',
                           form=form,
                           title='注册') 
Example #23
Source File: views.py    From Simpleblog with MIT License 5 votes vote down vote up
def change_password():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        if current_user.verify_password(form.old_password.data):
            current_user.password = form.password.data
            db.session.add(current_user)
            flash('你的密码已经更改。')
            return redirect(url_for('user.index'))
        else:
            flash('无效的密码。')
    return render_template('auth/change_password.html',
                           form=form,
                           title='更改密码') 
Example #24
Source File: routes.py    From VectorCloud with GNU General Public License v3.0 5 votes vote down vote up
def settings_user():
    form = SettingsForms()
    user_form = RegisterForm()

    if user_form.validate_on_submit():
        current_user.username = user_form.username.data
        hashed_password = bcrypt.generate_password_hash(
            user_form.password.data).decode('utf-8')
        current_user.password = hashed_password
        flash('Login Credentials Updated!', 'success')
        db.session.commit()
        return redirect(url_for('settings_system.settings'))

    elif request.method == 'GET':
        user_form.username.data = current_user.username

    err_msg = get_stats()
    if err_msg:
        flash('No Vector is Connected. Error message: ' + err_msg, 'warning')

    vector_status = Status.query.first()
    return render_template('settings/user.html', form=form,
                           vector_status=vector_status,
                           user_form=user_form,
                           sdk_version=sdk_version)


# this clears the user table, redirects to register 
Example #25
Source File: views.py    From Flashcards with MIT License 5 votes vote down vote up
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user, form.remember_me)
            return redirect(request.args.get('next') or url_for('main.index'))
        flash('Invalid username or password')
    return render_template('auth/login.html', form=form) 
Example #26
Source File: views.py    From Flashcards with MIT License 5 votes vote down vote up
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(email=form.email.data,
                    username=form.username.data,
                    password=form.password.data)
        db.session.add(user)
        db.session.commit()
        token = user.generate_confirmation_token()
        send_email(user.email, 'Confirm Your Account', 'auth/email/confirm', user=user, token=token)
        flash('A confirmation email has been sent to you by email.')
        return redirect(url_for('main.index'))
    return render_template('auth/register.html', form=form) 
Example #27
Source File: views.py    From Flashcards with MIT License 5 votes vote down vote up
def change_password():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        if current_user.verify_password(form.old_password.data):
            current_user.password = form.password.data
            db.session.add(current_user)
            flash('Your password has been updated.')
            return redirect(url_for('main.index'))
        else:
            flash('Invalid Password.')
    return render_template('auth/change_password.html', form=form) 
Example #28
Source File: views.py    From Flashcards with MIT License 5 votes vote down vote up
def password_reset_request():
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    form = PasswordResetRequestForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            token = user.generate_reset_token()
            send_email(user.email, 'Reset Your Password',
                       'auth/email/reset_password',
                       user=user, token=token,
                       next=request.args.get('next'))
        flash('An email with instructions to reset your password has been sent to you.')
        return redirect(url_for('auth.login'))
    return render_template('auth/reset_password.html', form=form) 
Example #29
Source File: views.py    From Simpleblog with MIT License 5 votes vote down vote up
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user, form.remember_me.data)
            return redirect(request.args.get('next') or url_for('user.index'))
        flash('账号或密码无效。')
    return render_template('auth/login.html',
                           title = '登录',
                           form =form) 
Example #30
Source File: controller.py    From specter-desktop with MIT License 5 votes vote down vote up
def login():
    ''' login '''
    app.specter.check()
    if request.method == 'POST':
        if app.specter.config['auth'] == 'none':
            app.login('admin')
            app.logger.info("AUDIT: Successfull Login no credentials")
            return redirect_login(request)
        if app.specter.config['auth'] == 'rpcpasswordaspin':
            # TODO: check the password via RPC-call
            if app.specter.cli is None:
                flash("We could not check your password, maybe Bitcoin Core is not running or not configured?","error")
                app.logger.info("AUDIT: Failed to check password")
                return render_template('login.jinja', specter=app.specter, data={'controller':'controller.login'}), 401
            cli = app.specter.cli.clone()
            cli.passwd = request.form['password']
            if cli.test_connection():
                app.login('admin')
                app.logger.info("AUDIT: Successfull Login via RPC-credentials")
                return redirect_login(request)
        elif app.specter.config['auth'] == 'usernamepassword':
            # TODO: This way both "User" and "user" will pass as usernames, should there be strict check on that here? Or should we keep it like this?
            username = request.form['username']
            password = request.form['password']
            user = User.get_user_by_name(app.specter, username)
            if user:
                if verify_password(user.password, password):
                    app.login(user.id)
                    return redirect_login(request)
        # Either invalid method or incorrect credentials
        flash('Invalid username or password', "error")
        app.logger.info("AUDIT: Invalid password login attempt")
        return render_template('login.jinja', specter=app.specter, data={'controller':'controller.login'}), 401
    else:
        if app.config.get('LOGIN_DISABLED'):
            app.login('admin')
            return redirect('/')
        return render_template('login.jinja', specter=app.specter, data={'next':request.args.get('next')})