Beispiel #1
0
def get_current_user(uow: UnitOfWork = Depends(get_uow),
                     token: str = Security(reusable_oauth2)) -> User:
    """Gets the current User object from the given token.

    Parameters
    ----------
    uow : UnitOfWork
        The unit of work to use.
    token : str
        The token to get the user from.

    Returns
    -------
    User
        The User model object for the current user.

    Raises
    ------
    HTTPException
        If the token could not be validated a ``403`` error is raised.
        If the user from the valid token could not be found then a
        ``404`` error is raised.

    """
    try:
        payload = jwt.decode(token, config.SECRET_KEY, algorithms=[ALGORITHM])
        payload['user_id'] = UUID(payload['user_id'])
    except jwt.PyJWTError:
        raise exceptions.PrivilegeError(
            "Could not validate the given credentials.")
    token_data = TokenPayload(**payload)
    return uow.user.get(token_data.user_id, raise_ex=True)
Beispiel #2
0
def check_superuser_or_admin(
    db: Session = Depends(get_db),
    token: str = Security(reusable_oauth2)
):
    try:
        payload = jwt.decode(token, config.SECRET_KEY, algorithms=[ALGORITHM])
        token_data = TokenPayload(**payload)
    except PyJWTError:
        raise HTTPException(
            status_code=HTTP_403_FORBIDDEN, detail="Token expirou/invalido"
        )
    environment = token_data.environment
    env_user = db.query(EnvUser).\
    filter_by(environment_id = str(environment), user_id = str(token_data.user_data.id)).first()
    user = crud_user.get(db, user_id=str(token_data.user_data.id))
       
    if env_user:
        env_user = env_user.is_admin
    env_user = env_user

    if token_data.user_data.is_superuser or env_user:
        return user    
    
    raise HTTPException(
            status_code=403, detail="Usuario não tem permissão"
        )
Beispiel #3
0
async def get_current_user(token: str = Security(reuseable_oauth2)):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        token_data = TokenPayload(**payload)
    except PyJWTError:
        raise HTTPException(status_code=HTTP_403_FORBIDDEN,
                            detail="Could not validate credentials")
    db = get_database()

    # ? CAN'T USE -> user = crud.user.get(db, username=token_data.username)
    logging.info("USERNAME : "******"SCOPE: " + token_data.scope)
    logging.info("CONTEXT: " + token_data.context)
    scope = token_data.scope
    if scope == USERTYPE_PERSONA:
        collection = get_collection(db, DOCTYPE_PERSONA)
        user = await collection.find_one({
            "username": token_data.username,
            "prj_id": ObjectId(token_data.context)
        })
    elif (scope == USERTYPE_CLIENT or scope == USERTYPE_EXPERT):
        collection = get_collection(db, DOCTYPE_PROJECT)
        user = await get_project_member(db, token_data.context,
                                        token_data.username)
    else:
        collection = get_collection(db, DOCTYPE_USER)
        user = await collection.find_one({"username": token_data.username})

    user["context"] = token_data.context
    if not (scope == USERTYPE_GAIA or scope == USERTYPE_LICENSE):
        user['admin_roles'] = []
    logging.info(token_data.context)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user
Beispiel #4
0
async def get_user_from_invitation(
        conn: AsyncIOMotorClient = Depends(get_database),
        token: str = Depends(get_invitation_token),
) -> UserTokenWrapper:
    try:
        payload: dict = decode(token,
                               str(settings.SECRET_KEY),
                               algorithms=[settings.ALGORITHM])
        if not payload.get("subject") in (
                TokenSubject.GROUP_INVITE_CO_OWNER,
                TokenSubject.GROUP_INVITE_MEMBER,
                TokenSubject.USER_INVITE,
        ):
            raise StarletteHTTPException(
                status_code=HTTP_403_FORBIDDEN,
                detail="This is not an invitation token")
        token_data: TokenPayload = TokenPayload(**payload)
    except PyJWTError:
        raise StarletteHTTPException(status_code=HTTP_403_FORBIDDEN,
                                     detail="Could not validate invitation")
    user_db: UserDB = await get_user_by_email(conn,
                                              token_data.user_email_invited)
    if not user_db:
        raise StarletteHTTPException(status_code=HTTP_404_NOT_FOUND,
                                     detail="This user doesn't exist")

    return UserTokenWrapper(**user_db.dict(), token=token)
def get_current_user(token: str = Security(reusable_oauth2)):
    try:
        payload = jwt.decode(token, config.SECRET_KEY, algorithms=[ALGORITHM])
        token_data = TokenPayload(**payload)
    except PyJWTError:
        raise HTTPException(status_code=HTTP_403_FORBIDDEN,
                            detail="Could not validate credentials")
    bucket = get_default_bucket()
    user = crud.user.get(bucket, username=token_data.username)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user
Beispiel #6
0
def get_current_user(db: Session = Depends(get_db),
                     token: str = Security(reusable_oauth2)):
    try:
        payload = jwt.decode(token, config.SECRET_KEY, algorithms=[ALGORITHM])
        token_data = TokenPayload(**payload)
    except PyJWTError:
        raise HTTPException(status_code=HTTP_403_FORBIDDEN,
                            detail="Could not validate credentials")
    user = crud.user.get(db, user_id=token_data.user_id)
    if not user:
        raise HTTPException(status_code=HTTP_404_NOT_FOUND,
                            detail="User not found")
    return user
Beispiel #7
0
async def _get_current_user(token: str) -> User:
    try:
        payload = jwt.decode(token, str(SECRET_KEY), algorithms=[ALGORITHM])
        token_data = TokenPayload(**payload)
    except PyJWTError:
        raise HTTPException(status_code=HTTP_403_FORBIDDEN,
                            detail="Could not validate credentials")
    db = await get_database()
    db_user = await crud_get_user_by_username(db, token_data.username)
    if not db_user:
        raise HTTPException(status_code=HTTP_404_NOT_FOUND,
                            detail="User not found")

    user = User(**db_user.dict(), token=token)
    return user
Beispiel #8
0
def get_current_user(
        token: str = Security(reusable_oauth2),
        conn: AsyncIOMotorClient = Depends(get_database),
):
    try:
        payload = jwt.decode(token, config.SECRET_KEY, algorithms=[ALGORITHM])
        token_data = TokenPayload(**payload)
    except PyJWTError:
        raise HTTPException(status_code=HTTP_403_FORBIDDEN,
                            detail="Could not validate credentials")
    # user = get_user(conn, username=token_data.username)
    user = get_user(conn, username=token_data.username)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user
Beispiel #9
0
def get_current_user(db_session: Session = Depends(get_db),
                     token: str = Depends(reusable_oauth2)):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        token_data = TokenPayload(**payload)
    except PyJWTError:
        raise HTTPException(status_code=HTTP_403_FORBIDDEN,
                            detail="Could not validate credentials")

    user_id = token_data.user_id
    user = crud.user.get_user_by_id(db_session=db_session, user_id=user_id)

    if not user:
        raise UserNotFoundException(user_id=user_id)

    return user
Beispiel #10
0
def get_current_user(
    db: Session = Depends(get_db),
    token: str = Security(reusable_oauth2)
    ):
    try:
        payload = jwt.decode(token, config.SECRET_KEY, algorithms=[ALGORITHM])
        token_data = TokenPayload(**payload)
    except PyJWTError:
        raise HTTPException(
            status_code=HTTP_403_FORBIDDEN, detail="Token expirou/invalido"
        )
    user = crud_user.get(db, user_id=token_data.user_data.id)
    print(user)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user
Beispiel #11
0
async def _get_current_user(db: DataBase = Depends(get_database),
                            token: str = Depends(
                                _get_authorization_token)) -> User:
    try:
        payload = jwt.decode(token, str(SECRET_KEY), algorithms=[ALGORITHM])
        token_data = TokenPayload(**payload)
    except PyJWTError:
        raise HTTPException(status_code=HTTP_403_FORBIDDEN,
                            detail="Could not validate credentials")

    async with db.pool.acquire() as conn:
        dbuser = await get_user(conn, token_data.username)
        if not dbuser:
            raise HTTPException(status_code=HTTP_404_NOT_FOUND,
                                detail="User not found")

        user = User(**dbuser.dict(), token=token)
        return user
Beispiel #12
0
async def _get_current_user(db: AsyncIOMotorClient = Depends(get_database),
                            token: str = Depends(oauth2_scheme)) -> User:
    try:
        payload = jwt.decode(token, str(SECRET_KEY), algorithms=[ALGORITHM])
        # TokenPayload可校验解密后内容
        token_data = TokenPayload(**payload)
    except PyJWTError:
        raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="无效的授权信息")
    # TODO 校验token是否过期token_data.exp 和当前时间比较

    dbuser = await get_user(db, id=token_data.id)
    if not dbuser:
        raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="用户不存在")
    if not dbuser.activated:
        raise HTTPException(status_code=HTTP_403_FORBIDDEN,
                            detail="用户被冻结,如需申诉,请联系管理员")

    user = User(**dbuser.dict(), token=token)
    return user
Beispiel #13
0
async def get_current_user(
    db: AsyncIOMotorClient = Depends(get_database), token: str = Depends(oauth2)
) -> UserSchema:
    try:
        payload = jwt.decode(
            token, SECRET_KEY, algorithms=[ALGORITHM]
        )
        token_data = TokenPayload(**payload)
    except (jwt.JWTError, ValidationError) as e:
        print(e)
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Could not validate credentials",
        )
    # user = crud.user.get(db, id=token_data.sub)
    user = await get_user(token_data.sub, db)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user
Beispiel #14
0
def get_current_user(token: str = Security(reusable_oauth2),
                     db: Session = Depends(get_db)):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, config.SECRET_KEY, algorithms=[ALGORITHM])
        user_id: int = payload.get("user_id")
        if user_id is None:
            raise credentials_exception
        token_data = TokenPayload(user_id=user_id)
    except JWTError:
        raise credentials_exception
    user = get_by_id(db, user_id=token_data.user_id)
    if user is None:
        raise credentials_exception
    return user
Beispiel #15
0
async def get_current_user(
        conn: AsyncIOMotorClient = Depends(get_database),
        token: str = Depends(get_token),
) -> UserTokenWrapper:
    try:
        payload: dict = decode(token,
                               str(settings.SECRET_KEY),
                               algorithms=[settings.ALGORITHM])
        token_data: TokenPayload = TokenPayload(**payload)
    except PyJWTError:
        raise StarletteHTTPException(status_code=HTTP_403_FORBIDDEN,
                                     detail="Could not validate credentials")

    user_db: UserDB = await get_user_by_email(conn, token_data.email)
    if not user_db:
        raise StarletteHTTPException(status_code=HTTP_404_NOT_FOUND,
                                     detail="This user doesn't exist")

    return UserTokenWrapper(**user_db.dict(), token=token)