Exemplo n.º 1
0
def login():
    """
    Enables log in verification and provides authentication token.
    Method Type
    -----------
    POST
    JSON Parameters
    ---------------
    email : str
        Email of the user
    password : str
        (Un-hashed) Password of the user
    Restrictions
    ------------
    User log in information must be correct
    JSON Returns
    ------------
    status : int
        Status code representing success status of the request
    message : str
        Message explaining the response status
    user : dict, optional
        Dictionary with information about the user
        id : int
            ID of the user
        auth_token : str
            Authentication token of the user
        name : str
            Name of the user
        email : str
            Email of the user
        access_level : int
            Access level of the user
    """
    request_json = request.get_json()
    email = request_json['email']
    password = request_json['password']
    user = User.query.filter_by(email=email).first()
    if user and bcrypt.check_password_hash(user.password, password):
        user_info = {
            'id': user.id,
            'auth_token': user.get_auth_token(),
            'name': user.name,
            'email': user.email,
            'access_level': user.access_level
        }
        final_dict = {
            'user': user_info,
            'status': 0,
            'message': "Log in successful"
        }
        return json.dumps(final_dict)
    else:
        final_dict = {
            'status':
            1,
            'message':
            "The provided combination of email and password is incorrect."
        }
        return json.dumps(final_dict)
Exemplo n.º 2
0
    def check_password(self, password):
        """This is a helper function for checking the user's password."""
        return bcrypt.check_password_hash(self.password, password)



# More models can be added here...
Exemplo n.º 3
0
def login():
    incoming_data = request.data.decode('utf-8')
    login_form = json.loads(incoming_data)
    user = User.query.filter_by(email=login_form["Email"]).first()
    if user is None:
        print("failure to log in")
        return {"result": "User does not exist"}
    if bcrypt.check_password_hash(user.password, login_form["Password"]):
        login_user(user)
        get_settings = Settings.query.filter_by(
            user_id=current_user.id).first()
        settings = settings_sql_dict(get_settings)
        print("logged in")
        return {
            "result": "success",
            "user": {
                "id": current_user.id,
                "playername": user.playername,
                "email": user.email,
                "displaypicture": user.display_picture,
                "settings": settings
            }
        }
    else:
        return {"result": "Incorrect Password"}
Exemplo n.º 4
0
def login():
    try:
        auth = request.authorization

        if not auth:
            return jsonify({
                "status": 401,
                "field": "common",
                "msg": "Autherization required!"
            })

        username = base64.b64decode(auth.username).decode('utf-8')
        password = base64.b64decode(auth.password).decode('utf-8')

        if not username or not password:
            return jsonify({
                "status": 401,
                "field": "common",
                "msg": "Both Credentials required!"
            })

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

        if user != None:
            # check password
            if bcrypt.check_password_hash(user.password, password):
                # valid password
                # validation done
                token = jwt.encode({
                    'public_id': user.public_id,
                    'exp': datetime.datetime.utcnow() + datetime.timedelta(days=30)
                }, app.secret_key)

                return jsonify({
                    "status": 200,
                    "token": token.decode('utf-8'),
                    "msg": "You are now logged in!"
                }), 200
            else:
                # invalid password
                return jsonify({
                    "status": 401,
                    "field": "password",
                    "msg": "Password doesn't match!"
                }), 401
        else:
            return jsonify({
                "status": 401,
                "field": "username",
                "msg": "Invalid Username"
            }), 401
    except:
        return jsonify({
            "status": 500,
            "field": "common",
            "msg": "Oops, Some error happened! Try Again..."
        }), 500
Exemplo n.º 5
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(eth_address=form.eth_address.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('event_index'))
        else:
            flash('Login Unsuccessful. Please check email and password', 'danger')
    return render_template('login.html', title='Login', form=form)
Exemplo n.º 6
0
def login():
    if current_user.is_authenticated:
        abort(404)
    user_data = request.get_json()
    if not user_data or not 'password' in user_data or not 'email' in user_data:
        abort(400)

    user = User.query.filter_by(email=user_data['email']).first()
    if user and bcrypt.check_password_hash(user.password,
                                           user_data['password']):
        login_user(user, remember=True)
        access_token = create_access_token(identity={'id': user.id})
        result = access_token
    else:
        abort(400)

    return result
Exemplo n.º 7
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('events.show_game'))
    form = LoginForm()
    if form.validate_on_submit():
        email = form.email.data
        password = form.password.data
        user = User.query.filter_by(email=email).first()
        if user and bcrypt.check_password_hash(user.password, password):
            logged_in_user = LoggedInUser(id=user.id, name=user.name, email=user.email, auth_token=user.get_auth_token())
            db.session.add(logged_in_user)
            db.session.commit()
            login_user(user, remember=form.remember.data)
            next_page = request.args.get('next')
            return redirect(next_page) if next_page else redirect(url_for('events.show_games'))
        else:
            flash("Authentication Failed", 'danger')
    return render_template('login.html', title='Login', form=form)
Exemplo n.º 8
0
def login():
    request_json = request.get_json()
    if request_json.get('isSnap'):
        display_name = request_json['display_name']
        snap_pic = request_json['snap_pic']
        user = User.query.filter_by(name=display_name,
                                    snapPic=snap_pic).first()
        if user:
            final_dict = {
                'id': user.id,
                'auth_token': user.get_auth_token(),
                'name': user.name,
                'email': user.email,
                'isParent': user.isParent,
                'status': 1
            }
            return json.dumps(final_dict)
        else:
            return json.dumps({
                'status':
                0,
                'error':
                "You need to register before you can log in."
            })
    email = request_json['email']
    password = request_json['password']
    user = User.query.filter_by(email=email).first()
    if user and bcrypt.check_password_hash(user.password, password):
        final_dict = {
            'id': user.id,
            'auth_token': user.get_auth_token(),
            'name': user.name,
            'email': user.email,
            'isParent': user.isParent,
            'status': 1
        }
        return json.dumps(final_dict)
    else:
        final_dict = {
            'status': 0,
            'error':
            "The provided combination of email and password is incorrect."
        }
        return json.dumps(final_dict)
    def post(self):
        data = trainer_login_parser.parse_args()
        current_trainer = Trainer.find_by_email(data['email'])
        if not current_trainer:
            return {'msg': f'Trainer {current_trainer} not found'}, 401

        if bcrypt.check_password_hash(current_trainer.password, data['password']):
            access_token = create_access_token(identity=data['email'])
            refresh_token = create_refresh_token(identity=data['email'])
            return {'message':
                    f'Trainer Logged in with email {current_trainer.email}',
                    'access_token': access_token,
                    'refresh_token': refresh_token,
                    'id': current_trainer.trainer_id,
                    'trainer': to_json_trainer(current_trainer)
                    }
        else:
            # create log for wrong credentials
            return {'msg': 'wrong credentials'}, 401
Exemplo n.º 10
0
def login():
    request_json = request.get_json()
    email = request_json['email']
    password = request_json['password']
    user = User.query.filter_by(email=email).first()
    if user and bcrypt.check_password_hash(user.password, password):
        final_dict = {
            'id': user.id,
            'auth_token': user.get_auth_token(),
            'name': user.name,
            'email': user.email,
            'isAdmin': user.isAdmin,
            'status': 1
        }
        return json.dumps(final_dict)
    else:
        final_dict = {
            'status': 0,
            'error':
            "The provided combination of email and password is incorrect."
        }
        return json.dumps(final_dict)
Exemplo n.º 11
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for("home"))
    form = LoginForm()

    # if the data is valid then flash a success prompt
    if form.validate_on_submit():

        # get user email
        user = User.query.filter_by(email=form.email.data).first()

        # User initial page selected before login
        next_page = request.args.get("next")
        if user and bcrypt.check_password_hash(user.password,
                                               form.password.data):
            login_user(user, remember=form.remember.data)

            # Redirect user to next page if there is any or just home if none
            return redirect(next_page) if next_page else redirect(
                url_for('home'))
        else:
            flash("Login failed. Please check your email and password",
                  "danger")
    return render_template('login.html', title="Login", form=form)
 def check_password(self, password: str) -> bool:
     return bcrypt.check_password_hash(self.password, password)
Exemplo n.º 13
0
Arquivo: auth.py Projeto: jkwik/ce-be
def login():
    body = request.get_json(force=True)

    #  trim the email to remove unnecessary spaces
    email = body['email'].strip()
    # convert input email to lowercase
    email = email.lower()
    # Validate that the email is the correct format
    try:
        v = validate_email(email)  # validate and get info
        email = v["email"]  # replace with normalized form
    except EmailNotValidError as e:
        # email is not valid, return error code
        return {"error": "Invalid Email Format"}, 406

    # Grab user from the database given email and password combination
    user = User.query.filter_by(email=email).first()
    if user == None:
        return {"error": "Invalid username or password"}, 404

    # Check that the passwords match
    if not bcrypt.check_password_hash(
            user.password, body['password'].encode(encoding='utf-8')):
        return {"error": "Invalid username or password"}, 404

    token = ''

    # If the users access_token is empty, create a new one for them
    if user.access_token == '' or user.access_token == None:
        token = user.encode_auth_token({'id': user.id, 'role': user.role})

        # Update the users access_token
        user.access_token = token
        db.session.commit()
    else:
        # If the user has an access token, check if it is expired
        payload = user.decode_auth_token(user.access_token)
        if payload == 'Expired':
            token = user.encode_auth_token({'id': user.id, 'role': user.role})

            # Update the users access_token
            user.access_token = token
            db.session.commit()
        elif payload == 'Invalid':
            # Invalid tokens are intolerable
            print('User with email ' + user.email +
                  ' has invalid access_token')
            return {"error": "Internal Server Error"}, 500
        else:
            # If the access_token is valid and is non empty, we use this token
            token = user.access_token

    # Set the access_token in the session
    session['access_token'] = token

    # Parse the result of the user query
    result = user_schema.dump(user)

    # Delete the sensitive information
    del result['password']
    del result['access_token']
    del result['verification_token']
    db.session.close()
    return {"user": result}
Exemplo n.º 14
0
def check_password(pw, hashed):
    return bcrypt.check_password_hash(hashed, pw)
Exemplo n.º 15
0
Arquivo: user.py Projeto: jkwik/ce-be
def updateProfile(token_claims):
    body = request.get_json(force=True)
     # retrieve user with id passed in
    user = User()
    user = User.query.get(token_claims['id'])
    # check which parameters were passed into this function
    if 'email' in body:
        newEmail = True
        try:
            v = validate_email(body["email"]) # validate and get info
            email = v["email"] # replace with normalized form
        except EmailNotValidError as e:
            # email is not valid, return error code
            return {
                "error": "Invalid Email Format"
            }, 406
    else:
        newEmail = False

    if 'first_name' in body:
        newFirstName = True
    else:
        newFirstName = False

    if 'last_name' in body:
        newLastName = True
    else:
        newLastName = False
    
    if 'newPassword' in body:
        # check that the current password field was entered
        if 'oldPassword' not in body:
            return{
                "error": "User must enter old password"
            }
        # check that oldPassword matches the password in the database
        if not bcrypt.check_password_hash(user.password, body['oldPassword'].encode(encoding='utf-8')):
            return {
                "error": "The old password doesn't match the password in the database"
            }, 400
        newPassword = True
        encodedPassword = bcrypt.generate_password_hash(body['newPassword']).decode(encoding="utf-8")
    else:
        newPassword = False

     # update the requested fields for this user
    try:
        if newEmail == True:
            user.email = email
        if newFirstName == True:
            user.first_name = body['first_name']
        if newLastName == True:
            user.last_name = body['last_name']
        if newPassword == True:
            user.password = encodedPassword
        db.session.commit()
    except Exception as e:
        return {
            "error": "Internal Server Error"
        }, 500
        raise

    # Refresh the user to grab the id
    db.session.refresh(user)
    # Grab the user from the database and dump the result into a user schema
    user = User.query.get(user.id)
    result = user_schema.dump(user)
    # remove the sensitive data fields
    del result['password']
    del result['access_token']
    del result['verification_token']
    # Return the user
    db.session.close()
    return {
        "user": result
    }
Exemplo n.º 16
0
 def check_password(self, password):
     """This is a helper function for checking the user's password."""
     return bcrypt.check_password_hash(self.password, password)
Exemplo n.º 17
0
 def check_password(self, password):
     return bcrypt.check_password_hash(self.password, password)
 def verify_password(hash, attempted_password):
     return bcrypt.check_password_hash(hash, attempted_password)
    def get_token(cls, email: str, password: str) -> str:
        user = cls.query.filter_by(email=email).first()
        if not user or not bcrypt.check_password_hash(user.password, password):
            flask.abort(403, "Invalid credentials.")

        return flask_jwt_extended.create_access_token(identity=user.id)