.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
the search function
self, request: Request
) -> Optional[HTTPAuthorizationCredentials]:
authorization: str = request.headers.get("Authorization")
scheme, credentials = get_authorization_scheme_param(authorization)
if not (authorization and scheme and credentials):
if self.auto_error:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
else:
return None
if scheme.lower() != "bearer":
if self.auto_error:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN,
detail="Invalid authentication credentials",
else:
return None
return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
self, request: Request
) -> Optional[HTTPAuthorizationCredentials]:
authorization: str = request.headers.get("Authorization")
scheme, credentials = get_authorization_scheme_param(authorization)
if not (authorization and scheme and credentials):
if self.auto_error:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
else:
return None
if scheme.lower() != "digest":
raise HTTPException(
status_code=HTTP_403_FORBIDDEN,
detail="Invalid authentication credentials",
return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
def _get_authorization_header(
api_key: str = Security(RWAPIKeyHeader(name=HEADER_KEY)),
) -> str:
token_prefix, token = api_key.split(" ")
except ValueError:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail=strings.WRONG_TOKEN_PREFIX,
if token_prefix != JWT_TOKEN_PREFIX:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail=strings.WRONG_TOKEN_PREFIX,
return token
def _get_current_user(
users_repo: UsersRepository = Depends(get_repository(UsersRepository)),
token: str = Depends(_get_authorization_header_retriever()),
) -> User:
username = jwt.get_username_from_token(token, str(SECRET_KEY))
except ValueError:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail=strings.MALFORMED_PAYLOAD,
return await users_repo.get_user_by_username(username=username)
except EntityDoesNotExist:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail=strings.MALFORMED_PAYLOAD,
Example #5
def test_forbidden_exception():
detail = "You have no rights, peasant."
with pytest.raises(ForbiddenError) as excinfo:
raise ForbiddenError(
detail=detail
exc = excinfo.value
assert exc.error_code == status.HTTP_403_FORBIDDEN
assert exc.status_code == status.HTTP_403_FORBIDDEN
assert exc.detail == detail
error_code = 444
with pytest.raises(ForbiddenError) as excinfo:
raise ForbiddenError(
detail=detail,
error_code=error_code
exc = excinfo.value
assert exc.error_code == error_code
assert exc.status_code == status.HTTP_403_FORBIDDEN
assert exc.detail == detail
Example #6
def test_permissions_dependency_as_class(dumb_request):
class FailPermission(BasePermission):
def has_required_permisions(self, request: Request) -> bool:
return False
class AllowPermission(BasePermission):
def has_required_permisions(self, request: Request) -> bool:
return True
dependency = PermissionsDependency(permissions_classes=[AllowPermission])
dependency(request=dumb_request)
dependency = PermissionsDependency(
permissions_classes=[AllowPermission, FailPermission])
with pytest.raises(HTTPException) as excinfo:
dependency(request=dumb_request)
assert excinfo.value.status_code == status.HTTP_403_FORBIDDEN
assert excinfo.value.detail == "Forbidden."
def get_current_user(token: str = Security(reusable_oauth2)):
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
Example #8
self, request: Request
) -> Optional[HTTPAuthorizationCredentials]:
authorization: str = request.headers.get("Authorization")
scheme, credentials = get_authorization_scheme_param(authorization)
if not (authorization and scheme and credentials):
if self.auto_error:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
else:
return None
return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
def __call__(self, request: Request) -> Optional[str]:
authorization: str = request.headers.get("Authorization")
if not authorization:
if self.auto_error:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
else:
return None
return authorization
Example #10
def __call__(self, request: Request) -> Optional[str]:
authorization: str = request.headers.get("Authorization")
if not authorization:
if self.auto_error:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
else:
return None
return authorization
def __call__(self, request: Request) -> Optional[str]:
api_key: str = request.headers.get(self.model.name)
if not api_key:
if self.auto_error:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
else:
return None
return api_key
Example #12
def __call__(self, request: Request) -> Optional[str]:
api_key = request.cookies.get(self.model.name)
if not api_key:
if self.auto_error:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
else:
return None
return api_key
def check_article_modification_permissions(
current_article: Article = Depends(get_article_by_slug_from_path),
user: User = Depends(get_current_user_authorizer()),
) -> None:
if not check_user_can_modify_article(current_article, user):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=strings.USER_IS_NOT_AUTHOR_OF_ARTICLE,
Example #14
def test_base_permission_no_permission_raises_403(dumb_request):
class FailPermission(BasePermission):
def has_required_permisions(self, request: Request) -> bool:
return False
with pytest.raises(HTTPException) as excinfo:
FailPermission(request=dumb_request)
assert excinfo.value.status_code == status.HTTP_403_FORBIDDEN
assert excinfo.value.detail == "Forbidden."
def get_current_user(
db: Session = Depends(get_db), token: str = Security(reusable_oauth2)
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=400, detail="User not found")
return user
Example #16
def __call__(
self, request: Request, security_scopes: SecurityScopes, return_token=False
if not self.enabled:
return None
if security_scopes.scopes:
authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
else:
authenticate_value = f"Bearer"
token: str = await oauth2_scheme(request) if not self.token else self.token
data = (
await models.User.join(models.Token)
.select(models.Token.id == token)
.gino.load((models.User, models.Token))
.first()
if data is None:
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": authenticate_value},
user, token = data # first validate data, then unpack
forbidden_exception = HTTPException(
status_code=HTTP_403_FORBIDDEN,
detail="Not enough permissions",
headers={"WWW-Authenticate": authenticate_value},
if "full_control" not in token.permissions:
for scope in security_scopes.scopes:
if scope not in token.permissions and not check_selective_scopes(
request, scope, token
raise forbidden_exception
if "server_management" in security_scopes.scopes and not user.is_superuser:
raise forbidden_exception
if return_token:
return user, token
return user
Example #17
def check_comment_modification_permissions(
comment: Comment = Depends(get_comment_by_id_from_path),
user: User = Depends(authentication.get_current_user_authorizer()),
) -> None:
if not check_user_can_modify_comment(comment, user):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=strings.USER_IS_NOT_AUTHOR_OF_ARTICLE,