Skip to content

Commit b7f3d79

Browse files
committed
First commit
1 parent c5c69f4 commit b7f3d79

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

microsoftgraph/__init__.py

Whitespace-only changes.

microsoftgraph/client.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import requests
2+
from urllib.parse import urlencode, urlparse
3+
4+
5+
class Client(object):
6+
AUTHORITY_URL = 'https://login.microsoftonline.com/'
7+
AUTH_ENDPOINT = '/oauth2/v2.0/authorize?'
8+
TOKEN_ENDPOINT = '/oauth2/v2.0/token'
9+
10+
RESOURCE = 'https://graph.microsoft.com/'
11+
12+
def __init__(self, client_id, client_secret, api_version='v1.0', account_type='common'):
13+
self.client_id = client_id
14+
self.client_secret = client_secret
15+
self.api_version = api_version
16+
self.account_type = account_type
17+
18+
self.base_url = self.RESOURCE + self.api_version + '/'
19+
self.token = None
20+
21+
def authorization_url(self, redirect_uri, scope):
22+
"""
23+
24+
Args:
25+
redirect_uri:
26+
scope:
27+
28+
Returns:
29+
30+
"""
31+
params = {
32+
'client_id': self.client_id,
33+
'redirect_uri': redirect_uri,
34+
'scope': ' '.join(scope),
35+
'response_type': 'code'
36+
}
37+
url = self.AUTHORITY_URL + self.account_type + self.AUTH_ENDPOINT + urlencode(params)
38+
return url
39+
40+
def exchange_code(self, redirect_uri, code, scope):
41+
"""Exchanges a code for a Token.
42+
43+
Args:
44+
redirect_uri: A string with the redirect_uri set in the app config.
45+
code: A string containing the code to exchange.
46+
47+
Returns:
48+
A dict.
49+
50+
"""
51+
params = {
52+
'client_id': self.client_id,
53+
'redirect_uri': redirect_uri,
54+
'client_secret': self.client_secret,
55+
'code': code,
56+
'grant_type': 'authorization_code',
57+
}
58+
return requests.post(self.AUTHORITY_URL + self.account_type + self.TOKEN_ENDPOINT, data=params).json()
59+
60+
def set_token(self, token):
61+
"""Sets the Access Token for its use in this library.
62+
63+
Args:
64+
token: A string with the Access Token.
65+
66+
"""
67+
self.token = token
68+
69+
def get_me(self):
70+
return self._get('me')
71+
72+
def _get(self, endpoint, params=None):
73+
headers = {'Authorization': 'Bearer ' + self.token['access_token']}
74+
response = requests.get(self.base_url + endpoint, params=params, headers=headers)
75+
return self._parse(response)
76+
77+
def _post(self, endpoint, params=None, data=None):
78+
response = requests.post(self.base_url + endpoint, params=params, data=data)
79+
return self._parse(response)
80+
81+
def _delete(self, endpoint, params=None):
82+
response = requests.delete(self.base_url + endpoint, params=params)
83+
return self._parse(response)
84+
85+
def _parse(self, response):
86+
return response.json()
87+

0 commit comments

Comments
 (0)