Ejemplo n.º 1
0
async def authenticate_user(token: str):
    """Verifies that the token encodes a known username and returns the user

    The username is encoded in a JSON web token which will first be decoded and
    the corresponding entry is read from the database. In case of success the 
    user is returned.
    """
    db = database.SessionLocal()  # open database session defined
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[JWT_ALGORITHM])
        username: str = payload.get('sub')  # the subject is the username
        if username is None:
            raise credentials_exception
        # obtain user from database
        user = crud.get_user_by_username(db, username=username)
    except jwt.PyJWTError:
        logger.warn('PyJWTError')
        raise credentials_exception
    except:
        logger.warn('Unknown error')
        raise credentials_exception
    finally:
        db.close()  # close database session

    if user is None:
        raise credentials_exception
    return user
Ejemplo n.º 2
0
async def authenticate_user(token: str):
    """
    Extract the username from a JSON web token, and return the corresponding
    entry from the database.
    """
    db = SessionLocal()  # open database session
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[JWT_ALGORITHM])
        username: str = payload.get('sub')  # the subject is the username
        if username is None:
            raise credentials_exception
        # obtain user from database
        user = get_user_by_username(db, username=username)
    except jwt.PyJWTError:
        logging.warn('PyJWTError')
        raise credentials_exception
    except:
        logging.warn('Unknown error')
        raise credentials_exception
    finally:
        db.close()  # close database session

    if user is None:
        raise credentials_exception
    return user
Ejemplo n.º 3
0
    def test_get_user(self):
        username = '******'

        db = SessionLocal()
        try:
            user = crud.get_user_by_username(db, username)
            assert user.username == 'thilo'
        finally: db.close()
Ejemplo n.º 4
0
def get_user(db, username: str) -> models.user.UserInDB:
    """Retrieve user from database."""

    user = crud.get_user_by_username(db, username)
    if not user:
        return None
    # translate from sql orm to pydantic, otherwise there is no dict() method
    return models.user.UserInDB(uid=user.uid,
                                username=user.username,
                                hashed_password=user.hashed_password)
async def create_user(
        new_user: models.user.UserCreate,
        db: Session = Depends(get_db)):
    # user contains username (str) and password (str)
    if not new_user.username:
        raise HTTPException(
            status_code=HTTP_400_BAD_REQUEST,
            detail='Invalid username'
        )

    # check for duplicate names
    db_user = crud.get_user_by_username(db, new_user.username)
    if db_user:
        raise HTTPException(
            status_code=HTTP_400_BAD_REQUEST,
            detail='Username already exists'
        )

    # the user containing the ID generated by the database is returned
    user_in_db = crud.create_user(db, new_user)
    return user_in_db
Ejemplo n.º 6
0
async def create_user(new_user: models.user.UserCreate,
                      db: Session = Depends(get_db)):
    """Create a new user in the database

    Parameters
    ----------
    new_user
        username (str) and password (str)
    """

    # check for empty name( TODO: could also enforce minimum length)
    if not new_user.username:
        raise HTTPException(status_code=HTTP_400_BAD_REQUEST,
                            detail='Invalid username')

    # check for duplicate names
    db_user = crud.get_user_by_username(db, new_user.username)
    if db_user:
        raise HTTPException(status_code=HTTP_400_BAD_REQUEST,
                            detail='Username already exists')

    # the user containing the ID generated by the database is returned
    user_in_db = crud.create_user(db, new_user)
    return user_in_db