Coverage for pephubclient/pephub_oauth/pephub_oauth.py: 57%

49 statements  

« prev     ^ index     » next       coverage.py v7.15.3, created at 2026-08-04 18:15 +0000

1import json 

2import time 

3from typing import Optional, Type, Union 

4 

5import requests 

6from pydantic import BaseModel 

7 

8from pephubclient.constants import DEFAULT_BASE_URL 

9from pephubclient.helpers import MessageHandler, RequestManager 

10from pephubclient.pephub_oauth.const import ( 

11 DEVICE_INIT_PATH, 

12 DEVICE_TOKEN_PATH, 

13) 

14from pephubclient.pephub_oauth.exceptions import ( 

15 PEPHubResponseException, 

16 PEPHubTokenExchangeException, 

17) 

18from pephubclient.pephub_oauth.models import ( 

19 InitializeDeviceCodeResponse, 

20 PEPHubDeviceTokenResponse, 

21) 

22 

23 

24class PEPHubAuth(RequestManager): 

25 """ 

26 Class responsible for authorization to PEPhub. 

27 """ 

28 

29 def login_to_pephub(self, base_url: Optional[str] = None): 

30 self._base_url = (base_url or DEFAULT_BASE_URL).rstrip("/") + "/" 

31 pephub_response = self._request_pephub_for_device_code() 

32 print( 

33 f"User verification code: {pephub_response.device_code}, please go to the website: " 

34 f"{pephub_response.auth_url} to authenticate." 

35 ) 

36 

37 # Sleep 2 minutes and then try 3 times exchange device code on token 

38 time.sleep(2) 

39 

40 number_of_token_exchange_attempts = 3 

41 for i in range(number_of_token_exchange_attempts): 

42 try: 

43 user_token = self._exchange_device_code_on_token( 

44 pephub_response.device_code 

45 ) 

46 except PEPHubTokenExchangeException: 

47 time.sleep(2) 

48 else: 

49 print("Successfully logged in!") 

50 return user_token 

51 

52 # If you didn't log in press enter to try again. 

53 input("If you logged in, press enter to continue...") 

54 try: 

55 user_token = self._exchange_device_code_on_token( 

56 pephub_response.device_code 

57 ) 

58 except PEPHubTokenExchangeException: 

59 MessageHandler.print_warning("You are not logged in") 

60 else: 

61 MessageHandler.print_success("Successfully logged in!") 

62 return user_token 

63 

64 def _request_pephub_for_device_code(self) -> InitializeDeviceCodeResponse: 

65 """ 

66 Requests device code from pephub 

67 """ 

68 response = PEPHubAuth.send_request( 

69 method="POST", 

70 url=f"{self._base_url}{DEVICE_INIT_PATH}", 

71 params=None, 

72 headers=None, 

73 ) 

74 return self._handle_pephub_response(response, InitializeDeviceCodeResponse) 

75 

76 def _exchange_device_code_on_token(self, device_code: str) -> str: 

77 """ 

78 Send request with device dode to pephub in order to exchange it on JWT 

79 :param device_code: device code that was generated by pephub 

80 """ 

81 response = PEPHubAuth.send_request( 

82 method="POST", 

83 url=f"{self._base_url}{DEVICE_TOKEN_PATH}", 

84 params=None, 

85 headers={"device-code": device_code}, 

86 ) 

87 pephub_token_response = self._handle_pephub_response( 

88 response, PEPHubDeviceTokenResponse 

89 ) 

90 return pephub_token_response.jwt_token 

91 

92 @staticmethod 

93 def _handle_pephub_response( 

94 response: requests.Response, model: Type[BaseModel] 

95 ) -> Union[BaseModel, InitializeDeviceCodeResponse, PEPHubDeviceTokenResponse]: 

96 """ 

97 Decode the response from GitHub and pack the returned data into appropriate model. 

98 :param response: Response from pephub 

99 :param model: Model that the data will be packed to. 

100 

101 :return: Response data as an instance of correct model. 

102 """ 

103 if response.status_code == 401: 

104 raise PEPHubTokenExchangeException() 

105 if response.status_code != 200: 

106 raise PEPHubResponseException() 

107 try: 

108 content = json.loads(PEPHubAuth.decode_response(response)) 

109 except json.JSONDecodeError: 

110 raise Exception("Something went wrong with GitHub response") 

111 

112 return model(**content)