Commit a809b72c1f69607ed86db950e564b3edfc6cb731
- Diff rendering mode:
- inline
- side by side
swtr/server.py
(32 / 2)
  | |||
1 | #!/usr/bin/python | ||
1 | # -*- coding: utf8 -*- | ||
2 | 2 | ||
3 | 3 | import flask | |
4 | 4 | from flask import session | |
5 | 5 | import config | |
6 | 6 | import requests | |
7 | 7 | import json | |
8 | from datetime import datetime, timedelta | ||
8 | 9 | ||
10 | |||
9 | 11 | app = flask.Flask(__name__) | |
10 | 12 | app.config['SECRET_KEY'] = config.secret_key | |
11 | 13 | ||
… | … | ||
15 | 15 | @app.route('/', methods=['GET']) | |
16 | 16 | def index(): | |
17 | 17 | auth_tok = None | |
18 | # check if ?code param is there | ||
18 | 19 | if flask.request.args.get('code'): | |
20 | # prepare the payload | ||
19 | 21 | payload = { | |
20 | 22 | 'scopes': 'email sweet', | |
21 | 23 | 'client_secret': config.app_secret, | |
… | … | ||
30 | 30 | oauth_token_x_endpoint = config.swtstoreURL + '/oauth/token' | |
31 | 31 | resp = requests.post(oauth_token_x_endpoint, data=payload) | |
32 | 32 | auth_tok = json.loads(resp.text) | |
33 | print 'recvd auth token from swtstore' | ||
33 | 34 | print auth_tok | |
34 | 35 | ||
35 | 36 | if 'error' in auth_tok: | |
36 | 37 | print auth_tok['error'] | |
37 | 38 | return flask.make_response(auth_tok['error'], 200) | |
38 | 39 | ||
40 | # set sessions et al | ||
39 | 41 | session['auth_tok'] = auth_tok | |
42 | session['auth_tok']['issued'] = datetime.utcnow() | ||
40 | 43 | ||
44 | # else if session is already existing.. | ||
41 | 45 | if 'auth_tok' in session: | |
42 | 46 | auth_tok = session['auth_tok'] | |
47 | # check if it has expired | ||
48 | oauth_token_expires_in_endpoint = config.swtstoreURL +\ | ||
49 | '/oauth/token-expires-in' | ||
50 | resp = requests.get(oauth_token_expires_in_endpoint) | ||
51 | expires_in = json.loads(resp.text)['expires_in'] | ||
52 | # added for backwared compatibility. previous session stores did not | ||
53 | # have issued key | ||
54 | try: | ||
55 | check = datetime.utcnow() - auth_tok['issued'] | ||
56 | |||
57 | if check > timedelta(seconds=expires_in): | ||
58 | print 'access token expired' | ||
59 | # TODO: try to refresh the token before signing out the user | ||
60 | auth_tok = {'access_token': '', 'refresh_token': ''} | ||
61 | else: | ||
62 | print 'access token did not expire' | ||
63 | |||
64 | # if issued key is not there, reset the session | ||
65 | except KeyError: | ||
66 | auth_tok = {'access_token': '', 'refresh_token': ''} | ||
67 | |||
43 | 68 | else: | |
44 | 69 | auth_tok = {'access_token': '', 'refresh_token': ''} | |
45 | 70 | ||
46 | print auth_tok | ||
71 | #print 'existing tokens' | ||
72 | #print auth_tok | ||
47 | 73 | return flask.render_template('index.html', | |
48 | 74 | access_token=auth_tok['access_token'], | |
49 | 75 | refresh_token=auth_tok['refresh_token'], |