Exemple #1
0
def login():
    if current_user.is_authenticated:
        return redirect('/')

    form = LoginForm()
    if form.validate_on_submit():
        try:
            target_user = _get_user(email=form.email.data)
        except ConnectionError as e:
            util.shutdown_server()
            return 'No backend, please try again.', 400

        if target_user.password and bcrypt.check_password_hash(target_user.password, form.password.data):
            # init the user empty and load deferred from the data we already have
            user = WrappedUser()
            user.load(target_user)
            login_user(user)
            flash('Login succeeded for user {}'.format(form.email.data))

            next = util.get_redirect_target()
            return redirect(next)
        else:
            if target_user.email == form.email.data:
                sign = '=='
            else:
                sign = '!='
            logging.info('email login fail: "{target}" {sign} "{form}"'.format(
                target = target_user.email,
                form = form.email.data,
                sign = sign
                ))
            flash('Incorrect login details')
    return render_template('login.html', form=form)
Exemple #2
0
    def check_password(self, value):
        """Verify password against stored hashed password.

        :param str value: The password to verify.
        :return: True if the password matches the stored hashed password.
        :rtype: bool
        """
        return bcrypt.check_password_hash(self.password, value)
 def validate_password(password_hash, password):
     """
     验证密码是否正确
     :param password_hash:
     :param password:
     :return:
     """
     return bcrypt.check_password_hash(password_hash, password)
Exemple #4
0
def login():
    form = LoginForm()
    if (form.validate_on_submit()):
        user = User.query.filter_by(username=form.username.data).first()
        if user is not None:
            if (bcrypt.check_password_hash(user.password, form.password.data)):
                login_user(user)
                return redirect(url_for('public.index'))
    return render_template('login.html', form=form)
Exemple #5
0
    def verify_password(self, password):
        """
        Verify user password

        :param password: Raw password
        :return: Boolean
        """

        if bcrypt.check_password_hash(self.password, password):
            return True

        return False
Exemple #6
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('main.home'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(user.password,
                                               form.password.data):
            login_user(user, remember=form.remember.data)
            next_page = request.args.get('next')
            return redirect(next_page) if next_page else redirect(
                url_for('main.home'))
        else:
            flash('Login Unsuccessful. Please check email and password',
                  'danger')
    return render_template('login.html', title='Login', form=form)
Exemple #7
0
def test_new_user(client, init_database):
    """
    GIVEN a User model
    WHEN a new user is created
    THEN check the name, email and hashed_password fields are defined correctly
    """
    user = User(**user_dict)
    user.save()

    registered_user = User.query.filter_by(
        name=user_dict["name"]).first_or_404()

    assert registered_user.name == user_dict["name"].title()
    assert registered_user.email == user_dict["email"].lower()
    assert True is bcrypt.check_password_hash(registered_user.password,
                                              user_dict["password"])
def login_user():
    """Log user in."""
    try:
        post_data = request.get_json()
        email = post_data['email']
        password = post_data['password']
    except TypeError:
        raise ParseError('Missing login payload.')
    except KeyError:
        raise ParseError('Invalid login payload.')

    # Fetch the user data
    user = User.query.filter_by(email=email).first()
    if user and bcrypt.check_password_hash(user.password, password):
        auth_token = user.encode_auth_token(user.id)
        if auth_token:
            result = {'auth_token': auth_token.decode()}
            return result, 200
    raise NotFound('User does not exist.')
Exemple #9
0
def _login_user():
    form = LoginForm()
    user = User.query.filter_by(email=form.email.data).first()
    if user:
        if bcrypt.check_password_hash(user.password, form.password.data):
            # authenticate user and resave into db
            db.session.add(user)
            db.session.commit()
            flash('Login requested for user {}'.format(user.email))
            expires = datetime.timedelta(days=30)
            access_token = create_access_token(
                identity=user.username,
                expires_delta=expires)  # Create access token for user
            refresh_token = create_refresh_token(identity=user.username,
                                                 expires_delta=expires)
            return jsonify(access_token=access_token,
                           refresh_token=refresh_token), 200

    return json.dumps({'Login': False}), 500, {
        'ContentType': 'application/json'
    }
Exemple #10
0
def login():

    # If user already is logged in return to home page
    if current_user.is_authenticated:
        return redirect(url_for('main.home'))

    form = LoginForm() # Initialize Login FOrm and pass it to html template

    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        # If a user with given email exists and password is correct login
        if user and bcrypt.check_password_hash(user.password,form.password.data):
             login_user(user, remember=form.remember.data)   # FLaskLogin handles all sessions stuff
             flash(f'Logged in succesfully', 'success')

             next_page = request.args.get('next')

             return redirect(next_page) if next_page else redirect(url_for('main.home'))
        else:
             flash(f'The combination of Email and Password is not correct, Try again', 'danger')

    return render_template('login.html', title='Login', form=form)
Exemple #11
0
 def post(self):
     post_data = request.get_json()
     response_object = {"message": "Invalid payload."}
     if not post_data:
         return response_object, 400
     email = post_data.get("email")
     password = post_data.get("password")
     try:
         user = User.find(email=email)
         if user:
             valid_password = bcrypt.check_password_hash(
                 user.password_hash, password)
             if valid_password:
                 redis_client.setex(
                     user.id.__str__(),
                     int(current_app.config["JWT_ACCESS_TOKEN_EXPIRES"]),
                     "inactive")
                 token = create_access_token(identity=user.id.__str__(),
                                             fresh=True,
                                             user_claims=user.avatar)
                 jti = get_jti(token)
                 redis_client.setex(
                     user.id.__str__(),
                     int(current_app.config["JWT_ACCESS_TOKEN_EXPIRES"]),
                     jti)
                 response_object = {"token": token}
                 return response_object, 200
             else:
                 response_object["message"] = "Invalid Credentials."
                 return response_object, 401
         else:
             response_object["message"] = "User does not exist."
             return response_object, 404
     except Exception:
         db.session.rollback()
         db.session.flush()
         response_object["message"] = "Try again."
         return response_object, 500
Exemple #12
0
def user_edit(user_id=None):
    form = UserForm()
    form.submit.label.text = 'Update'

    if form.validate_on_submit():
        # check that old_password matches the current user's
        if bcrypt.check_password_hash(current_user.user.password, form.old_password.data):
            return user_submit(form, user_id)
        else:
            flash('Current password incorrect!')
    else:
        logging.info('loading current values because: {}'.format(form.errors))

        old_user = users.GetUser(u.GetUserRequest(_id=user_id))

        # All of this fuckery is needed because the proto object validates field types,
        # so we can't just change the field to a datetime object but need a new object
        user_dict = MessageToDict(message=old_user, preserving_proto_field_name=True)
        # Have to delete _id since it's not a valid field for a namedtuple
        del user_dict['_id']
        user_obj = namedtuple("User", user_dict.keys()) (*user_dict.values())
        form = UserForm(obj=user_obj)

    return render_template('user_edit.html', form=form, view='Edit User')
 def verify_password(self, password):
     return bcrypt.check_password_hash(self.password, password)
Exemple #14
0
 def check_password(self, password):
     return bcrypt.check_password_hash(self.passwd, password)
Exemple #15
0
 def check_password(self, value):
     return bcrypt.check_password_hash(self.password, value)
Exemple #16
0
 def check_password(self, value: str) -> bool:
     """Check password."""
     is_good_password: bool = bcrypt.check_password_hash(
         self.password, value)
     return is_good_password
Exemple #17
0
def login():
    """Endpoint for a user's credentials to be checked in order to log in to their account

    .. :quickref: User; Validate user credentials for login.

    **Example request**:

    .. sourcecode:: http

        POST /api/login HTTP/1.1
        Host: localhost
        Accept: application/json
        Content-Type: application/json

        {
            "username": "******",
            "password": "******"
        }

    **Example response**:

    .. sourcecode:: http

        HTTP/1.1 200 OK
        Content-Type: application/json

        {
            "message": "Logged in successfully",
            "user": {
                "username": "******"
            }
        }

    .. sourcecode:: http

        HTTP/1.1 401 UNAUTHORIZED
        Content-Type: application/json

        {
            "message": "Incorrect password",
            "user": null
        }

    :<json string username: unique username
    :<json string password: password for specified account
    :>json message: repsonse information such as error information
    :>json app.models.user.User user: the user object that has been created
    :resheader Content-Type: application/json
    :status 200: successful login
    :status 400: malformed request
    :status 401: incorrect password
    :status 404: user does not exist
    """

    response = {
        'message': '',
        'user': None
    }
    status = 200

    form_schema = LoginFormSchema()
    form_errors = form_schema.validate(request.json)
    if form_errors:
        response['message'] = form_errors
        status = 400
    else:
        username = request.json["username"]
        password = request.json["password"]

        # Checking if user is in database
        user = User.query.get(username)
        if user is None:
            response['message'] = {
                'user': ['User does not exist.']
            }
            status = 404
        else:
            # Checking wether passwords match
            passwords_match = bcrypt.check_password_hash(user.password, password)
            if passwords_match:
                response['message'] = "Logged in successfully"
                response['user'] = user_schema.dump(user)
                status = 200
            else:
                response['message'] = {
                    'user': ['Incorrect password.']
                }
                status = 401

    return response, status
Exemple #18
0
 def authenticate(self, password):
     password_hash = base64.b64decode(self.password_digest)
     return bcrypt.check_password_hash(password_hash, password)
 def verify_password(self, password):
     return bcrypt.check_password_hash(self.password, password)
Exemple #20
0
 def check_password(self, value):
     """Check password."""
     return bcrypt.check_password_hash(self.password, value)
 def check_password(self, value):
     """Check password."""
     return bcrypt.check_password_hash(self.password, value)
Exemple #22
0
	def login_valid(email, password):
		verify_user = User.get_by_email(email)
		if verify_user is not None:
			if bcrypt.check_password_hash(verify_user.password_hash, password):
				return verify_user
		return False
Exemple #23
0
 def _check_password(self, candidate):
     """
     Validate a candidate password with actual password
     """
     candidate_salt = candidate + self.salt
     return bcrypt.check_password_hash(self.password, candidate_salt)
Exemple #24
0
 def check_password(self, password):
     return bcrypt.check_password_hash(self.pw_hash,
                                       password.encode('utf-8'))
Exemple #25
0
 def check_password(self, password):
     return bcrypt.check_password_hash(self.pw_hash, password)
Exemple #26
0
 def is_correct_password(self, plaintext):
     return bcrypt.check_password_hash(self._password, plaintext)
Exemple #27
0
 def is_correct_password(self, plaintext):
     return bcrypt.check_password_hash(self._password, plaintext)
 def check_password(self, value):
     return bcrypt.check_password_hash(self.password, value)
Exemple #29
0
 def check_password(self, password):
     return bcrypt.check_password_hash(self.pw_hash, password.encode('utf-8'))