Commit a809b72c1f69607ed86db950e564b3edfc6cb731

Fix user forced to clear cookies after access tokens gets expired

  Previously after access tokens were expired, the application was not checking
that. As a result users were forced to manually delete their cookies. Adding
checking of expiry of the tokens on the server side.
  
1#!/usr/bin/python
1# -*- coding: utf8 -*-
22
33import flask
44from flask import session
55import config
66import requests
77import json
8from datetime import datetime, timedelta
89
10
911app = flask.Flask(__name__)
1012app.config['SECRET_KEY'] = config.secret_key
1113
1515@app.route('/', methods=['GET'])
1616def index():
1717 auth_tok = None
18 # check if ?code param is there
1819 if flask.request.args.get('code'):
20 # prepare the payload
1921 payload = {
2022 'scopes': 'email sweet',
2123 'client_secret': config.app_secret,
3030 oauth_token_x_endpoint = config.swtstoreURL + '/oauth/token'
3131 resp = requests.post(oauth_token_x_endpoint, data=payload)
3232 auth_tok = json.loads(resp.text)
33 print 'recvd auth token from swtstore'
3334 print auth_tok
3435
3536 if 'error' in auth_tok:
3637 print auth_tok['error']
3738 return flask.make_response(auth_tok['error'], 200)
3839
40 # set sessions et al
3941 session['auth_tok'] = auth_tok
42 session['auth_tok']['issued'] = datetime.utcnow()
4043
44 # else if session is already existing..
4145 if 'auth_tok' in session:
4246 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
4368 else:
4469 auth_tok = {'access_token': '', 'refresh_token': ''}
4570
46 print auth_tok
71 #print 'existing tokens'
72 #print auth_tok
4773 return flask.render_template('index.html',
4874 access_token=auth_tok['access_token'],
4975 refresh_token=auth_tok['refresh_token'],