Coverage for nexios\auth\exceptions.py: 100%

1 from nexios.exceptions import HTTPException

2 from typing import Dict, Any, Optional

3 from nexios.http import Request

4 from nexios.http.response import NexiosResponse

5

6 HeadersType = Dict[str, Any] # Alias for better readability

7

8

9 class AuthException(HTTPException):

10 """

11 Base class for all authentication-related exceptions.

12 """

13

14 def __init__(

15 self, status_code: int, detail: str, headers: Optional[HeadersType] = None

16 ) -> None:

17 """

18 Initialize an authentication exception.

19

20 Args:

21 status_code (int): The HTTP status code.

22 detail (str): A description of the error.

23 headers (Optional[Dict[str, Any]]): Optional headers for the response.

24 """

25 super().__init__(status_code, detail, headers or {})

26

27

28 class AuthenticationFailed(AuthException):

29 """

30 Raised when authentication fails.

31 """

32

33 def __init__(

34 self,

35 detail: str = "Authentication failed",

36 headers: Optional[HeadersType] = None,

37 ) -> None:

38 super().__init__(401, detail, headers)

39

40

41 async def AuthErrorHandler(

42 req: Request, res: NexiosResponse, exc: HTTPException

43) -> Any:

44 """

45 Handle authentication exceptions and return a JSON response.

46

47 Args:

48 req (Request): The incoming HTTP request.

49 res (Response): The outgoing HTTP response.

50 exc (HTTPException): The raised HTTP exception.

51

52 Returns:

53 Response: JSON-formatted error response.

54 """

55 return res.json(exc.detail, status_code=exc.status_code, headers=exc.headers)