forked from CityofSantaMonica/mds-provider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.py
46 lines (37 loc) · 1.29 KB
/
auth.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
"""
Authentication module for MDS API calls.
"""
import requests
from requests import Session
class AuthorizationToken():
"""
Mixin implementing an Authorization token header of the type specified by
the provider.
"""
def auth_token_session(self, provider):
"""
Establishes a session with the `Authorization: :auth_type: :token:` header.
"""
session = Session()
session.headers.update({ "Authorization": f"{provider.auth_type} {provider.token}" })
headers = getattr(provider, "headers", None)
if headers:
session.headers.update(headers)
return session
class OAuthClientCredentialsAuth(AuthorizationToken):
"""
Mixin implementing OAuth 2.0 client_credentials grant flow.
"""
def oauth_session(self, provider):
"""
Acquires a Bearer token before establishing a session with the provider.
"""
payload = {
"client_id": provider.client_id,
"client_secret": provider.client_secret,
"grant_type": "client_credentials",
"scope": provider.scope.split(",")
}
r = requests.post(provider.token_url, data=payload)
provider.token = r.json()["access_token"]
return self.auth_token_session(provider)