-
Notifications
You must be signed in to change notification settings - Fork 14
/
oauth.py
175 lines (150 loc) · 5.13 KB
/
oauth.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
"""
Mercedes Me APIs
Author: G. Ravera
For more details about this component, please refer to the documentation at
https://github.com/xraver/mercedes_me_api/
"""
import base64
import json
import logging
import os
from const import *
from query import *
URL_OAUTH_BASE = "https://ssoalpha.dvb.corpinter.net/v1"
URL_OAUTH_AUTH = f"{URL_OAUTH_BASE}/auth?response_type=code"
URL_OAUTH_TOKEN = f"{URL_OAUTH_BASE}/token"
# Logger
_LOGGER = logging.getLogger(__name__)
class MercedesMeOauth:
########################
# Init
########################
def __init__(self, client_id, client_secret):
# Access Token
self.access_token = ""
# Refresh Token
self.refresh_token = ""
# Expiration Time
self.token_expires_in = ""
# Client ID
self.client_id = client_id
# Client Secret
self.client_secret = client_secret
# Token File
self.token_file = TOKEN_FILE
# Base64
b64_str = f"{client_id}:{client_secret}"
b64_bytes = base64.b64encode(b64_str.encode("ascii"))
self.base64 = b64_bytes.decode("ascii")
# Headers
self.headers = {
"Authorization": f"Basic {self.base64}",
"content-type": "application/x-www-form-urlencoded",
}
########################
# Read Token
########################
def ReadToken(self):
found = False
# Read Token
if not os.path.isfile(self.token_file):
# Token File not present
_LOGGER.error("Token File missing")
found = False
else:
with open(self.token_file, "r") as file:
try:
token = json.load(file)
if not self.CheckToken(token):
raise ValueError
else:
found = True
except ValueError:
_LOGGER.error("Error reading token file")
found = False
if found:
# Valid: just import
self.access_token = token["access_token"]
self.refresh_token = token["refresh_token"]
self.token_expires_in = token["expires_in"]
# Refreshing
if not self.RefreshToken():
_LOGGER.error("Error refreshing token")
return False
return True
########################
# Write Token
########################
def WriteToken(self, token):
with open(self.token_file, "w") as file:
json.dump(token, file)
########################
# Check Token
########################
def CheckToken(self, token):
if "reason" in token:
_LOGGER.error(
f"Error retrieving token - {token['reason']} ({token['code']})"
)
return False
if "error" in token:
if "error_description" in token:
_LOGGER.error(f"Error retrieving token: {token['error_description']}")
else:
_LOGGER.error(f"Error retrieving token: {token['error']}")
return False
if len(token) == 0:
_LOGGER.error("Empty token found.")
return False
if not "access_token" in token:
_LOGGER.error("Access token not present.")
return False
if not "refresh_token" in token:
_LOGGER.error("Refresh token not present.")
return False
return True
########################
# Create Token
########################
def CreateToken(self):
auth_url = (
f"{URL_OAUTH_AUTH}&"
+ f"client_id={self.client_id}&"
+ f"redirect_uri={REDIRECT_URL}&"
+ f"scope={SCOPE}"
)
print("Open the browser and insert this link:\n")
print(f"{auth_url}\n")
print("Copy the code in the url:")
auth_code = input()
data = f"grant_type=authorization_code&code={auth_code}&redirect_uri={REDIRECT_URL}"
token = GetToken(URL_OAUTH_TOKEN, self.headers, data, refresh=False)
# Check Token
if not self.CheckToken(token):
return False
else:
# Save Token
self.WriteToken(token)
self.access_token = token["access_token"]
self.refresh_token = token["refresh_token"]
self.token_expires_in = token["expires_in"]
return True
########################
# Refresh Token
########################
def RefreshToken(self):
if self.access_token == "":
_LOGGER.error("Error: Token not found or not valid")
return False
data = f"grant_type=refresh_token&refresh_token={self.refresh_token}"
token = GetToken(URL_OAUTH_TOKEN, self.headers, data, refresh=True)
# Check Token
if not self.CheckToken(token):
return False
else:
# Save Token
self.WriteToken(token)
self.access_token = token["access_token"]
self.refresh_token = token["refresh_token"]
self.token_expires_in = token["expires_in"]
return True