Coverage for app/utils/check_token.py: 81%

16 statements  

« prev     ^ index     » next       coverage.py v7.9.2, created at 2026-02-19 12:46 +0000

1import requests 

2from app.config.config import POSTGRES_HOSTNAME 

3 

4from app.utils.response_format import generate_error_response 

5 

6constellation_check_error = { 

7 401: { 

8 "description": "Unauthorized", 

9 "content": { 

10 "application/json": { 

11 "example": { 

12 "success": False, 

13 "data": None, 

14 "message": "Could not validate credentials", 

15 "error": { 

16 "code": "INVALID_CREDENTIALS", 

17 "message": "Could not validate credentials" 

18 } 

19 } 

20 } 

21 } 

22 }, 

23 403: { 

24 "description": "Forbidden: Insufficient permissions", 

25 "content": { 

26 "application/json": { 

27 "example": { 

28 "success": False, 

29 "data": None, 

30 "message": "Forbidden: Insufficient permissions", 

31 "error": { 

32 "code": "INSUFFICIENT_PERMISSIONS", 

33 "message": "Forbidden: Insufficient permissions" 

34 } 

35 } 

36 } 

37 } 

38 }, 

39 404: { 

40 "description": "Not Found", 

41 "content": { 

42 "application/json": { 

43 "example": { 

44 "success": False, 

45 "data": None, 

46 "message": "... not found", 

47 "error": { 

48 "code": "NOT_FOUND", 

49 "message": "... not found" 

50 } 

51 } 

52 } 

53 } 

54 } 

55} 

56 

57data_permissions = [ 

58 "READ", 

59 "COMMENT", 

60 "WRITE", 

61 "ADMIN", 

62 "OWNER" 

63] 

64 

65def check_constellation_access(token: str, constellation_uuid: str, asked_permission: str = "READ"): 

66 try: 

67 response = requests.get(f"{POSTGRES_HOSTNAME}/me/constellations/{constellation_uuid}/access", headers={"Authorization": f"Bearer {token}"}) 

68 if response.status_code != 200: 

69 return generate_error_response( 

70 status_code=response.status_code, 

71 error_code="INVALID_CREDENTIALS", 

72 error_message="Could not validate credentials", 

73 message="Could not validate credentials" 

74 ) 

75 data = response.json() 

76 if data_permissions.index(data["access"]) < data_permissions.index(asked_permission): 

77 return generate_error_response( 

78 status_code=403, 

79 error_code="INSUFFICIENT_PERMISSIONS", 

80 error_message="Forbidden: Insufficient permissions", 

81 message="Forbidden: Insufficient permissions" 

82 ) 

83 except requests.exceptions.RequestException as e: 

84 return generate_error_response( 

85 status_code=500, 

86 error_code="INTERNAL_SERVER_ERROR", 

87 error_message="Error while checking token", 

88 message="Error while checking token" 

89 ) 

90 return True