This repository has been archived by the owner on Mar 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 71
/
sample_flask.py
63 lines (54 loc) · 2.38 KB
/
sample_flask.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
"""Flask-OAuthlib sample for Microsoft Graph"""
# Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license.
# See LICENSE in the project root for license information.
import uuid
import flask
from flask_oauthlib.client import OAuth
import config
APP = flask.Flask(__name__, template_folder='static/templates')
APP.debug = True
APP.secret_key = 'development'
OAUTH = OAuth(APP)
MSGRAPH = OAUTH.remote_app(
'microsoft', consumer_key=config.CLIENT_ID, consumer_secret=config.CLIENT_SECRET,
request_token_params={'scope': config.SCOPES},
base_url=config.RESOURCE + config.API_VERSION + '/',
request_token_url=None, access_token_method='POST',
access_token_url=config.AUTHORITY_URL + config.TOKEN_ENDPOINT,
authorize_url=config.AUTHORITY_URL + config.AUTH_ENDPOINT)
@APP.route('/')
def homepage():
"""Render the home page."""
return flask.render_template('homepage.html', sample='Flask-OAuthlib')
@APP.route('/login')
def login():
"""Prompt user to authenticate."""
flask.session['state'] = str(uuid.uuid4())
return MSGRAPH.authorize(callback=config.REDIRECT_URI, state=flask.session['state'])
@APP.route('/login/authorized')
def authorized():
"""Handler for the application's Redirect Uri."""
if str(flask.session['state']) != str(flask.request.args['state']):
raise Exception('state returned to redirect URL does not match!')
response = MSGRAPH.authorized_response()
flask.session['access_token'] = response['access_token']
return flask.redirect('/graphcall')
@APP.route('/graphcall')
def graphcall():
"""Confirm user authentication by calling Graph and displaying some data."""
endpoint = 'me'
headers = {'SdkVersion': 'sample-python-flask',
'x-client-SKU': 'sample-python-flask',
'client-request-id': str(uuid.uuid4()),
'return-client-request-id': 'true'}
graphdata = MSGRAPH.get(endpoint, headers=headers).data
return flask.render_template('graphcall.html',
graphdata=graphdata,
endpoint=config.RESOURCE + config.API_VERSION + '/' + endpoint,
sample='Flask-OAuthlib')
@MSGRAPH.tokengetter
def get_token():
"""Called by flask_oauthlib.client to retrieve current access token."""
return (flask.session.get('access_token'), '')
if __name__ == '__main__':
APP.run()