Coverage for src/paperap/auth.py: 79%

28 statements  

« prev     ^ index     » next       coverage.py v7.6.12, created at 2025-03-11 21:37 -0400

1""" 

2---------------------------------------------------------------------------- 

3 

4 METADATA: 

5 

6 File: auth.py 

7 Project: paperap 

8 Created: 2025-03-04 

9 Version: 0.0.5 

10 Author: Jess Mann 

11 Email: jess@jmann.me 

12 Copyright (c) 2025 Jess Mann 

13 

14---------------------------------------------------------------------------- 

15 

16 LAST MODIFIED: 

17 

18 2025-03-04 By Jess Mann 

19 

20""" 

21 

22from __future__ import annotations 

23 

24from abc import ABC, abstractmethod 

25from typing import Any, override 

26 

27import pydantic 

28 

29 

30class AuthBase(pydantic.BaseModel): 

31 """Base authentication class.""" 

32 

33 @abstractmethod 

34 def get_auth_headers(self) -> dict[str, str]: 

35 """Get authentication headers.""" 

36 raise NotImplementedError("get_auth_headers must be implemented by subclasses") 

37 

38 @abstractmethod 

39 def get_auth_params(self) -> dict[str, Any]: 

40 """Get authentication parameters for requests.""" 

41 raise NotImplementedError("get_auth_params must be implemented by subclasses") 

42 

43 

44class TokenAuth(AuthBase): 

45 """Authentication using a token.""" 

46 

47 token: str 

48 

49 @override 

50 def get_auth_headers(self) -> dict[str, str]: 

51 """Get the authorization headers.""" 

52 return {"Authorization": f"Token {self.token}"} 

53 

54 @override 

55 def get_auth_params(self) -> dict[str, Any]: 

56 """Get authentication parameters for requests.""" 

57 return {} 

58 

59 

60class BasicAuth(AuthBase): 

61 """Authentication using username and password.""" 

62 

63 username: str 

64 password: str 

65 

66 @override 

67 def get_auth_headers(self) -> dict[str, str]: 

68 """ 

69 Get headers for basic auth. 

70 

71 Basic auth is handled by the requests library, so no headers are needed here. 

72 """ 

73 return {} 

74 

75 @override 

76 def get_auth_params(self) -> dict[str, Any]: 

77 """Get authentication parameters for requests.""" 

78 return {"auth": (self.username, self.password)}