-
Notifications
You must be signed in to change notification settings - Fork 0
/
connect.py
143 lines (109 loc) · 4.71 KB
/
connect.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import os
import webapp2
import jinja2
import datetime
import time
import random
import string
import logging
import json
from google.appengine.ext import ndb
from google.appengine.api import users
from gaesessions import get_current_session
import httplib2
from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
class SignIn(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
self.apikey = ""
#Try to get the apiKey from a session cookie
session = get_current_session()
# if the session is active
if session.is_active() and session.has_key('APIKey') :
self.apikey = session['APIKey']
# if the session is not active, create it and store the empty api key
else :
session.regenerate_id()
# Create a state token to prevent request forgery.
# Store it in the session for later validation.
state = ''.join(random.choice(string.ascii_uppercase + string.digits)
for x in xrange(32))
session['state'] = state
template_values = {
'state' : state
}
template = JINJA_ENVIRONMENT.get_template('connect.html')
self.response.write(template.render(template_values))
class GoogleSignIn(webapp2.RequestHandler) :
def get(self):
user = users.get_current_user()
self.apikey = ""
#Try to get the apiKey from a session cookie
session = get_current_session()
# if the session is active
if session.is_active() and session.has_key('APIKey') :
self.apikey = session['APIKey']
# if the session is not active, create it and store the empty api key
else :
session.regenerate_id()
# Create a state token to prevent request forgery.
# Store it in the session for later validation.
state = ''.join(random.choice(string.ascii_uppercase + string.digits)
for x in xrange(32))
session['state'] = state
template_values = {
'state' : state
}
template = JINJA_ENVIRONMENT.get_template('connect.html')
self.response.write(template.render(template_values))
def post(self):
#Try to get the apiKey from a session cookie
session = get_current_session()
# Ensure that the request is not a forgery and that the user sending
# this connect request is the expected user.
if self.request.get('state', '') != session['state']:
self.response.write(json.dumps('Invalid state parmeter'))
self.response.status = 401
return
code = self.request.POST
logging.info(code)
try:
# Upgrade the authorization code into a credentials object
oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='', redirect_uri = 'postmessage')
credentials = oauth_flow.step2_exchange(code)
except FlowExchangeError:
self.response.write(json.dumps('Failed to upgrade the authorization code.'))
self.response.status=401
self.response.headers['Content-Type'] = 'application/json'
return
# Check that the access token is valid.
access_token = credentials.access_token
url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={0}'.format(access_token))
h = httplib2.Http()
result = json.loads(h.request(url, 'GET')[1])
# If there was an error in the access token info, abort.
if result.get('error') is not None:
self.response.write(json.dumps('Error in access token info'))
self.response.status=500
return
# Verify that the access token is valid for this app.
if result['issued_to'] != CLIENT_ID:
self.response.write(json.dumps('Client token does not match app'))
self.response.status=401
return
stored_credentials = session.get('credentials')
stored_gplus_id = session.get('gplus_id')
if stored_credentials is not None and gplus_id == stored_gplus_id:
logging.info("Current user is already connected")
self.response.write(json.dumps('Current user is already connected.'))
self.response.status=200
# Store the access token in the session for later use.
session['credentials'] = credentials
session['gplus_id'] = gplus_id
logging.info('Successfully connected {0}'.format())