4
from social_core.backends.oauth import BaseOAuth2
5
from django.conf import settings
8
class BungieOAuth2(BaseOAuth2):
11
ID_KEY = 'membership_id'
12
AUTHORIZATION_URL = 'https://www.bungie.net/en/oauth/authorize/'
13
ACCESS_TOKEN_URL = 'https://www.bungie.net/platform/app/oauth/token/'
14
REFRESH_TOKEN_URL = 'https://www.bungie.net/platform/app/oauth/token/'
15
ACCESS_TOKEN_METHOD = 'POST'
16
REDIRECT_STATE = False
18
('refresh_token', 'refresh_token', True),
19
('access_token', 'access_token', True),
20
('expires_in', 'expires'),
21
('membership_id', 'membership_id'),
22
('refresh_expires_in', 'refresh_expires_in')
26
"""Abstract Method Inclusion"""
29
def auth_headers(self):
30
"""Adds X-API-KEY and Origin"""
31
return {'X-API-KEY': settings.SOCIAL_AUTH_BUNGIE_API_KEY,
32
'Content-Type': 'application/x-www-form-urlencoded',
33
'Origin': settings.SOCIAL_AUTH_BUNGIE_ORIGIN,
34
'Accept': 'application/json'
37
def make_bungie_request(self, url, access_token, kwargs):
38
"""Helper function to get username data keyed off displayName"""
39
print('ENTERING MAKE BUNGIE REQUEST')
40
headers = self.auth_headers()
42
auth_header = {'Authorization': 'Bearer ' + access_token}
43
headers.update(auth_header)
44
import requests as python_requests
45
r = python_requests.get(url, headers=headers)
49
def auth_complete(self, *args, **kwargs):
50
"""Completes login process, must return user instance"""
51
self.process_error(self.data)
52
state = self.validate_state()
53
response = self.request_access_token(
54
self.access_token_url(),
55
data=self.auth_complete_params(state),
56
headers=self.auth_headers(),
57
auth=self.auth_complete_credentials(),
58
method=self.ACCESS_TOKEN_METHOD
60
self.process_error(response)
61
return self.do_auth(response['access_token'], response=response, *args, **kwargs)
63
def do_auth(self, access_token, *args, **kwargs):
64
"""Finish the auth process once the access_token was retrieved"""
65
data = self.user_data(access_token, *args, **kwargs)
66
response = kwargs.get('response') or {}
67
response.update(data or {})
68
if 'access_token' not in response:
69
response['Response']['access_token']['value'] = access_token
70
kwargs.update({'response': response, 'backend': self})
71
return self.strategy.authenticate(*args, **kwargs)
73
def user_data(self, access_token, *args, **kwargs):
74
"""Grab user profile information from Bunige"""
75
membership_id = kwargs['response']['membership_id']
76
url = 'https://www.bungie.net/Platform/User/GetBungieNetUser/'
77
this_json = self.make_bungie_request(url, access_token, kwargs)
78
username = this_json['Response']['user']['displayName']
79
return {'username': username, 'uid': membership_id}
81
def get_user_details(self, response, *args, **kwargs):
82
"""Return user details from Bungie account"""
83
username = response['username']
85
bnId = response['bnId']
87
'first_name': username,