def login(self, db, admin, password):
        cursor = db.cursor()
        sql = '''
        SELECT id, password FROM admin
        WHERE admin_login = %s
        '''
        try:
            cursor.execute(sql, (admin, ))
        except OperationalError as e:
            print(e)
            return abort(500)
        result = cursor.fetchone()
        if not result:
            return {'message': 'Admin not exist'}, 401
        uid, password_hash = result
        check = bcrypt.check_password_hash(password_hash.decode('UTF-8'),
                                           password)
        if not check:
            return {'message': 'incorrect admin/password combination'}, 401

        access_token = create_access_token(identity={
            'id': uid,
            'role': 'admin'
        })
        refresh_token = create_refresh_token(identity={
            'id': uid,
            'role': 'admin'
        })
        resp_body = {'message': f'admin {admin} ' f'logged in successfully'}

        resp = jsonify(resp_body)
        set_access_cookies(resp, access_token)
        set_refresh_cookies(resp, refresh_token)
        return resp
Esempio n. 2
0
def login():

    if current_user.is_authenticated:
        flash('You\'re already logged in', 'info')
        return redirect(url_for('base.index'))

    form = LoginForm()
    render_vars = {'page_name': 'Login', 'form': form}

    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):
            remember_me = False
            if form.remember_me:
                remember_me = True
            login_user(user, remember=remember_me)
            flash('Welcome back !', 'success')
            return redirect(url_for('base.index'))
        elif user:
            flash('Invalid password.', 'danger')
            return render_template('user/login.html', form=form)
        else:
            flash('Invalid email.', 'danger')
            return render_template('user/login.html', form=form)

    return render_template('user/login.html', **render_vars)
Esempio n. 3
0
 def post(self):
     body = request.get_json()
     user = User.query.filter_by(email=body.get('email')).first()
     if user and bcrypt.check_password_hash(user.password, body.get('password')):
         expires = timedelta(days=7)
         access_token = create_access_token(identity=str(user.id), expires_delta=expires)
         return {'token': access_token}, 200
     return {'error': 'Email or password invalid'}, 401
Esempio n. 4
0
 def authenticate(cls, login, password):
     if login is not "" and password is not "":
         user = cls.getuserbylogin(login)
         if user is not None:
             if bcrypt.check_password_hash(user.password, password):
                 User.update(lastlogindate=DateTime.local2utc(
                     datetime.now())).where(User.id == user.id).execute()
                 return user, True
     return None, False
Esempio n. 5
0
def login():
    if request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")

        # right way to find user with correct password
        user = User.query\
             .filter(User.username == username) \
             .first()

        session_cookie = str(uuid.uuid4())
        expiry_time = datetime.datetime.now() + datetime.timedelta(
            seconds=COOKIE_DURATION)

        redirect_url = request.args.get('redirectTo', url_for('main.index'))

        if user is None:
            flash("Username or password is wrong", "warning")
            logging.info(
                f"User {username} failed to login with wrong username.")
            return redirect(url_for('user.login', redirectTo=redirect_url))
        elif not bcrypt.check_password_hash(user.password_hash, password):
            flash("Username or password is wrong", "warning")
            logging.info(
                f"User {username} failed to login with wrong password.")
            return redirect(url_for('user.login', redirectTo=redirect_url))
        else:
            user.session_cookie = session_cookie
            user.session_expiry_datetime = expiry_time
            db.session.add(user)
            db.session.commit()
            logging.info(f"User {username} is logged in")

        response = make_response(redirect(redirect_url))
        response.set_cookie(WEBSITE_LOGIN_COOKIE_NAME,
                            session_cookie,
                            httponly=True,
                            samesite='Strict')
        return response

    elif request.method == "GET":
        cookie = request.cookies.get(WEBSITE_LOGIN_COOKIE_NAME)
        user = None

        if cookie is not None:
            user = User.query \
                .filter_by(session_cookie=cookie) \
                .filter(User.session_expiry_datetime >= datetime.datetime.now())\
                .first()

        if user is None:
            logged_in = False
        else:
            logged_in = True

        return render_template("login.html", logged_in=logged_in)
Esempio n. 6
0
def login():
    # fetch login credentials
    data = request.get_json(force=True)
    # find user
    user = session.query(User).filter_by(email=data['email']).first()
    if not user:
        return {"ok": True, "message": "User with email not found"}, 404
    if bcrypt.check_password_hash(user.password, data['password']):
        token = create_access_token(identity=data['email'])
        return jsonify(access_token=token)
    return {"ok": True, "message": "Incorrect password"}, 401
Esempio n. 7
0
def jwt_create():
    email = request.form.get('email')
    password = request.form.get('password')

    user = User.query.filter_by(email=email).first()

    # Validate credentials
    if not user or not bcrypt.check_password_hash(user.password, password):
        return jsonify({'message': 'Invalid username or password'}), 400
    else:
        jwt_token = create_access_token(identity=user.id)
        return jsonify(token=jwt_token), 200
Esempio n. 8
0
    def login(value):

        user = user_account.query.filter(
            user_account.username == value[0]).first()

        if user:

            password = bcrypt.check_password_hash(
                user.password.encode('utf-8'), value[1].encode('utf-8'))

            if password == False:
                user = None

        return user
Esempio n. 9
0
def login_post():
    email = request.form.get('email')
    password = request.form.get('password')
    remember = True if request.form.get('remember') else False

    user = User.query.filter_by(email=email).first()

    # Validate credentials
    if not user or not bcrypt.check_password_hash(user.password, password):
        flash('Please check your login details and try again.')
        return redirect(url_for('auth.login'))  # Reload page

    # if the above check passes, then we know the user has the right credentials
    login_user(user, remember=remember)
    return redirect(url_for('main.profile'))
Esempio n. 10
0
def login():
    error = None
    form = LoginForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            if request.form['username'] == 'randall'\
                and bcrypt.check_password_hash(
                    PASSWORD,
                    request.form['password']
                    ):
                session['logged_in'] = True
                return redirect(url_for('home_ctrl.home'))
            else:
                error = 'Invalid credentials'
    return render_template('login.html', form=form, error=error)
Esempio n. 11
0
    def post(self):
        args = parser.parse_args()
        email = args['email']
        password = args['password']

        user = db.session.query(User).filter_by(email=email).first()
        print(user.user_id, "result of user.user_id")
        if user is None:
            return jsonify(authorization=False)
        if bcrypt.check_password_hash(user.password, password):
            login_user(user, remember=True)
            print(user, "user login")
            result = jsonify(isLoggedIn=current_user.is_authenticated,
                             user=user.as_dict())
        else:
            result = jsonify(authorization=False)
        return result
    def post(self):
        args = login_parser.parse_args()
        if len(args['userid']) > 100:
            return {
                'message':
                'username or email should be '
                'less than 100 characters'
            }, 400
        try:
            cursor = mysql.get_db().cursor()
            sql = '''
            SELECT user.id, password, username FROM user JOIN email
            ON user.id = email.user_id
            WHERE email.address = %s or user.username = %s
            '''
            cursor.execute(sql, (args['userid'], args['userid']))
            result = cursor.fetchone()
        except OperationalError as e:
            return error_resp(e)

        if not result:
            return ({'message': 'incorrect userid/password combination'}, 409)

        user_id, password, username = result
        if bcrypt.check_password_hash(password.decode('utf-8'),
                                      args['password']):
            access_token = create_access_token(identity=user_id)
            refresh_token = create_refresh_token(identity=user_id)
            resp_body = {
                'message': f'username {username} '
                f'logged in successfully'
            }

            resp = jsonify(resp_body)
            set_access_cookies(resp, access_token)
            set_refresh_cookies(resp, refresh_token)
            return resp

        return ({'message': 'incorrect userid/password combination'}, 409)
Esempio n. 13
0
def user_login():
    """
    Converts password text to hash string using bcrypt, verifies the
    combination against the database and creates a session for user in Flask
    :param email:
    :param password:
    :return: user.todict()
    """
    req = request.get_json()
    user = (User.query
            .filter(User.email == req['email'])
            .first()
            )
    if user is not None:
        if bcrypt.check_password_hash(user.password, req['password']):
            if user.is_active == False:
                return Error("Email not confirmed. Please check your mail",
                             http_code=403)()

            login_user(user)
            session.permanent = True

            # get all fields except
            fields = [c.name for c in User.__table__.c]
            fields = filter(
                    lambda x: x not in ['password', 'is_active', 'type'],
                    fields)
            fields = list(fields)
            fields.append("corporate")
            fields.append({"corporate": ["tests", "name", "id"]})

            json_dict = user.todict(fields)

            if json_dict['corporate'] != None:
                corporate_id = json_dict['corporate']['id']
                CookieHelper.set_corporate_cookie(corporate_id)

            return user.todict(fields)
    return Error("Invalid Email or Password", 401)()
Esempio n. 14
0
def change_password():
    """
    Allows User to change Password after validating the Old Password. User
    must be logged in to be able to do this.
    :return: 403 if old password doesn't match, 400 if any error, else 200
    """
    req = request.get_json()

    try:
        user = User.query \
            .filter(User.id == current_user.id) \
            .filter(User.is_active) \
            .one()

        if bcrypt.check_password_hash(user.password, req['old_password']):
            user.password = bcrypt.generate_password_hash(req['new_password'])
            db.session.commit()
            return ""

        return Error('Invalid Old Password', 403)
    except NoResultFound:
        return Error('Invalid User', 400)()
Esempio n. 15
0
 def check_password(self, password):
     return bcrypt.check_password_hash(self._password, password)
Esempio n. 16
0
 def check_password(self, plaintext):
     return bcrypt.check_password_hash(self._password, plaintext)
Esempio n. 17
0
 def check_password(self, password):
     return bcrypt.check_password_hash(self._password,
                                       password)
Esempio n. 18
0
 def check_password(self, value):
     """Check password."""
     return bcrypt.check_password_hash(self.password, value)
Esempio n. 19
0
 def check_password(self, value):
     check = bcrypt.check_password_hash(self.password, value)
     return check
Esempio n. 20
0
 def verify_password(self, password):
     return bcrypt.check_password_hash(self.password_hash, password)