Beispiel #1
0
def read_user(
    username: EmailStr, 
    db: Session = Depends(dependancies.get_db),
    user: user_schema.User = Depends(dependancies.get_current_user)
):
    """Get user. Only accessible to Admin

    - **HEADERS**:
        ```
        {
            "Authorization": "Bearer <sample token>"
        }
        ```
    - **REQUEST**:
        ```
        {}
        ```
    - **RESPONSE**:
        ```
        {
            "username": "******",
            "is_admin": false
        }
        ```
    """  
    if not user.is_admin:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, 
            detail=constants.OPERATION_NOT_PERMITTED
        )
    db_user = UserHandler.get_user(db, username)
    if db_user is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=constants.RESOURCE_NOT_FOUND)
    return db_user
Beispiel #2
0
def get_current_user(db: Session = Depends(get_db),
                     token: str = Depends(oauth2_scheme)):
    """Extracts current user for token.
    """
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail=constants.CREDENTIALS_NOT_VALID,
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt_service.decode_token(token)
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_data = token_schema.TokenData(username=username)
    except JWTError:
        raise credentials_exception
    user = UserHandler.get_user(db, username=token_data.username)
    if user is None:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                            detail=constants.INCORRECT_CREDENTIALS)
    return user