def login():
    body = app.current_request.json_body
    record = get_users_db().get_item(
        Key={'username': body['username']})['Item']
    jwt_token = auth.get_jwt_token(body['username'], body['password'], record,
                                   get_auth_key())
    return {'token': jwt_token}
Exemple #2
0
def reset_password():
    json_body = app.current_request.json_body
    email = json_body['email']
    token = str(json_body['token'])
    password = json_body['password']
    if not (email or password or token):
        raise BadRequestError("Email, password and token mush be supplied.")
    with contextlib.closing(session_factory()) as session:
        user = session.query(User).filter(User.email == email).first()
        user_token = session.query(UserToken).filter(
            UserToken.user_id == user.id).first()
        if not user:
            raise NotFoundError("User not found")
        if datetime.now() > user_token.expire:
            raise BadRequestError("Token is expired.")
        if not user_token:
            raise BadRequestError("Please request for a token first")
        if not verify_password_reset_token(token=token,
                                           salt=user.password_salt,
                                           hashed_token=user_token.token):
            raise BadRequestError("Token is invalid")
        result = encode_password(password=password, salt=user.password_salt)
        session.query(User).filter(User.email == email).update(
            {'password_hash': result['hashed']})
        session.flush()
        session.commit()
        jwt_token = get_jwt_token(
            user.email + "," + str(user.role) + "," + str(user.id), password,
            user.password_salt, user.password_hash, JWT_SECRET)
        info = {'token': jwt_token, 'user': user}
        schema = TokenSchema()
        response = schema.dumps(info)
        if response.errors:
            raise ChaliceViewError(response.errors)
        return response.data
Exemple #3
0
def login():
    body = app.current_request.json_body
    record = get_users_db().get_item(
        Key={'username': body['username']})['Item']
    ## Generate the JWT token-- More analysis needed on the code
    jwt_token = auth.get_jwt_token(body['username'], body['password'], record)
    return {'token': jwt_token}
def login():
    body = app.current_request.json_body
    record = get_users_db().get_item(Key={'email': body['email']})
    log.debug(record)
    jwt_token = auth.get_jwt_token(body['email'], body['password'],
                                   record['Item'])

    return {'token': jwt_token.decode('utf-8')}
Exemple #5
0
def login():
    body = app.current_request.json_body
    try:
        record = get_users_db().get_item(
            Key={'username': body['username']})['Item']
        jwt_token = auth.get_jwt_token(body['username'], body['password'],
                                       record)
    except KeyError as e:
        raise UnauthorizedError("Bad credentials")
    return {'token': jwt_token}
Exemple #6
0
def login():
    json_body = app.current_request.json_body
    email = json_body['email']
    password = json_body['password']
    if not (email or password):
        raise BadRequestError("Email and password must be supplied.")

    with contextlib.closing(session_factory()) as session:
        user = session.query(User).filter(User.email == email).first()
        if not user:
            raise NotFoundError("User not found")
        print("{}, {}, {}".format(user.email, user.role, user.id))
        # Add to token ==> email + "|" + role
        jwt_token = get_jwt_token(
            user.email + "," + str(user.role) + "," + str(user.id), password,
            user.password_salt, user.password_hash, JWT_SECRET)
        info = {'token': jwt_token, 'user': user}
        schema = TokenSchema()
        response = schema.dumps(info)
        if response.errors:
            raise ChaliceViewError(response.errors)
        return response.data
def login():
    """"
    function to join session and generate jwt.
    :returns jwt token and session data (dict)
    """
    body = session_app.current_request.json_body
    if not body or not body.get('token'):
        return Response(body={'message': 'token is required'}, status_code=422)
    log.info(f"received session join request with {body['token']}")
    response = global_db_handler.get_user_db().validate_token(body['token'])
    log.info(f"response from db call for token  {body['token']} ")
    if len(response) <= 0:
        log.info("no session found with token")
        return Response(body={
            'message': 'no session found',
            'code': 'session_not_found'
        },
                        status_code=400)
    current_session_details = global_db_handler.get_session_db().get_item(
        response['sessionId'])
    if len(current_session_details) == 0:
        return Response(body={
            'message': 'no session found',
            'code': 'session_not_found'
        },
                        status_code=400)
    log.info(f'current session details for the token{current_session_details}')
    body['sessionDetails'] = {
        'email': response['email'],
        'firstName': response['firstName'],
        'lastName': response['lastName'],
        'token': body['token'],
        'role': response['role'],
        'userId': response['uid'],
        'sessionId': response['sessionId']
    }
    log.info('generating authentication token using jwt')
    jwt_token = auth.get_jwt_token(body['sessionDetails'])
    log.info('token generated, returning response ')
    session_audit_payload = {
        "sessionId": response['sessionId'],
        "statusId": 3,
        "status": "IN_PROGRESS",
        "timestamp": str(datetime.utcnow())
    }
    user_audit_payload = {
        "userId": response['uid'],
        "roleId": 3,
        "status": "JOINED",
        "timestamp": str(datetime.utcnow()),
        'email': response['email']
    }
    session_status_payload = {
        "sessionId": response['sessionId'],
        "status": "IN_PROGRESS"
    }
    audit_controller.update_audit("session", session_audit_payload)
    audit_controller.update_audit("user", user_audit_payload)
    update_session_status(session_status_payload)
    current_session_details = global_db_handler.replace_decimals(
        current_session_details)
    return Response(body={
        'token': jwt_token,
        'sessionDetails': current_session_details,
        'user': {
            'firstName': response['firstName'],
            'lastName': response['lastName'],
            'email': response['email'],
            'phoneNumber': response['phoneNumber'],
            'profilePicUrl': response['profilePicUrl']
        }
    },
                    status_code=200)