Exemplo n.º 1
0
def get_current_user_uuid(token: str):
    try:
        payload = jwt.decode(token, config.SECRET_KEY, algorithms=[ALGORITHM])
        token_data = TokenPayload(**payload)
    except PyJWTError:
        return None
    return token_data.user_uuid
Exemplo n.º 2
0
def get_token_data(token: str = Depends(oauth2)) -> TokenPayload:
    try:
        secret_key = settings.SECRET_KEY.get_secret_value()
        payload = jwt.decode(token, secret_key, algorithms=[ALGORITHM])
        token_data = TokenPayload(**payload)
    except (jwt.JWTError, ValidationError):
        raise HTTPException(status_code=403,
                            detail="Could not validate credentials")
    return token_data
Exemplo n.º 3
0
def verify_token(token: str):
    try:
        payload = jwt.decode(token,
                             settings.SECRET_KEY,
                             algorithms=[ALGORITHM])
        print(payload)
        token_data = TokenPayload(**payload)
    except (jwt.JWTError, ValidationError):
        return False

    return True
Exemplo n.º 4
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, id=token_data.user_id)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user
async 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_401_UNAUTHORIZED,
            detail="Could not validate credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )
    user = await crud.user.get(id=token_data.user_id)
    if not user:
        raise HTTPException(status_code=HTTP_404_NOT_FOUND,
                            detail="User not found")
    return User(**user)
Exemplo n.º 6
0
async def get_current_employee(
        token: str = Security(reusable_oauth2), ) -> Employee:
    try:
        payload = jwt.decode(token,
                             settings.SECRET_KEY,
                             algorithms=[settings.ALGORITHM])
        token_data = TokenPayload(**payload)
    except (jwt.JWTError, ValidationError):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Could not validate credentials",
        )
    employee = await employee_service.get_by_id(employee_id=token_data.sub)
    if not employee:
        raise HTTPException(status_code=404, detail="Employee not found")
    return employee
Exemplo n.º 7
0
def get_current_user(token: str):
    try:
        payload = jwt.decode(token, config.SECRET_KEY, algorithms=[ALGORITHM])
        token_data = TokenPayload(**payload)

        user = db_session.query(Users).filter(
            Users.uuid == token_data.user_uuid).first()
        if not user:
            return None

        return user
    except Exception as e:
        db_session.rollback()
        return None
    finally:
        db_session.close()
def get_current_user(token: str = Security(reusable_oauth2)):
    try:
        payload = jwt.decode(token,
                             settings.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(id=token_data.user_id)
    if not user:
        raise HTTPException(
            status_code=HTTP_401_UNAUTHORIZED,
            detail="Could not validate credentials",
        )
    return user
Exemplo n.º 9
0
def check_token(secrets_key, algorithm,
                token: Optional[str] = Header(None)
                ) -> TokenPayload:
    """
    只解析验证token
    :param algorithm:
    :param secrets_key:
    :param token:
    :return:
    """

    try:
        payload = jwt.decode(
            token,
            secrets_key, algorithms=algorithm
        )
        return TokenPayload(**payload, token=token)
    except (jwt.JWTError, ValidationError, AttributeError) as e:
        raise AuthError(err_desc=f"access token fail, de {e}")
Exemplo n.º 10
0
def authenticate(access_token: Optional[str] = Header(None)):
    if not access_token or access_token == '':
        raise Invalid_Token_Exception(msg='Access_Token不能为空')
    try:
        payload = jwt.decode(access_token,
                             settings.SECRET_KEY,
                             algorithms=[ALGORITHM])
        # print(payload)
        token_data = TokenPayload(**payload)
        print(token_data)
        appid = token_data.sub
        db: Session = SessionLocal()
        invoker = db.query(Invoker).filter(Invoker.app_id == appid).filter(
            Invoker.active == 1).first()
        if invoker:
            return invoker
        else:
            raise Invalid_Token_Exception(msg='appid:{}已被禁用'.format(appid))

    except (jwt.JWTError, ValidationError):
        raise Invalid_Token_Exception()
Exemplo n.º 11
0
def get_current_user(token: HTTPAuthorizationCredentials = Depends(reusable_oauth2)):
    try:
        payload = jwt.decode(token.credentials, settings.SECRET_KEY, algorithms=[ALGORITHM])
        token_data = TokenPayload(**payload)
    except PyJWTError:
        raise HTTPException(
            status_code=HTTP_401_UNAUTHORIZED, detail="用户认证失败,请重新登陆"
        )
    user = User.get(uuid=token_data.user_id)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    token_key = f'Token_{user.uuid.hex}'
    if not redis_client.exists(token_key):
        raise HTTPException(
            status_code=HTTP_401_UNAUTHORIZED, detail="用户认证已过期,请重新登陆"
        )
    redis_token = redis_client.get(token_key).decode('utf-8')
    if redis_token != token.credentials:
        raise HTTPException(
            status_code=HTTP_401_UNAUTHORIZED, detail="您的账号在他处登陆,如非本人操作请注意账号安全"
        )
    return user