-
Notifications
You must be signed in to change notification settings - Fork 12
/
main.py
199 lines (166 loc) · 6.06 KB
/
main.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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
"""
Copyright 2013 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import config
import json
import jwt
import logging
import loyalty
import offer
import os
import string
import time
import urllib
import webapp2
import wob_payload
import httplib2
from apiclient.discovery import build_from_document
from apiclient.http import HttpMock
from google.appengine.ext.webapp import template
from oauth2client import crypt
from oauth2client.client import SignedJwtAssertionCredentials
# Load the key in PKCS 12 format that you downloaded from the Google API
# Console when you created your Service account.
f = file(config.SERVICE_ACCOUNT_PRIVATE_KEY, 'rb')
key = f.read()
f.close()
# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with the Credentials. Note that the first parameter, service_account_name,
# is the Email address created for the Service account. It must be the email
# address associated with the key that was created.
credentials = SignedJwtAssertionCredentials(
config.SERVICE_ACCOUNT_EMAIL_ADDRESS,
key,
scope='https://www.googleapis.com/auth/wallet_object.issuer')
http = httplib2.Http()
http = credentials.authorize(http)
f = file(config.DISCOVERY_JSON, 'rb')
disc_content = f.read()
f.close()
#service = build('walletobjects', 'v1', http=http)
service = build_from_document(disc_content,'walletobjects', http=http)
def displayIndex(request):
"""Serves the index page.
Args:
request: A HTTP request object.
Returns:
The index page.
"""
path = os.path.join(os.path.dirname(__file__), 'index.html')
template_values = {}
return webapp2.Response(template.render(path, template_values))
def handleJwt(request):
"""Serves JWT response of appropriate type.
Args:
request: A HTTP request object.
Returns:
An encoded JWT object as response.
"""
wob_payload_object = wob_payload.WOB_Payload()
jwt_type = request.GET.get('type', '')
if jwt_type == 'loyalty':
loyalty_obj = loyalty.generate_loyalty_object(
config.ISSUER_ID, config.LOYALTY_CLASS_ID, config.LOYALTY_OBJECT_ID)
wob_payload_object.addWalletObjects(loyalty_obj, 'LoyaltyObject')
elif jwt_type == 'offer':
offer_obj = offer.generate_offer_object(
config.ISSUER_ID, config.OFFER_CLASS_ID, config.OFFER_OBJECT_ID)
wob_payload_object.addWalletObjects(offer_obj, 'OfferObject')
payload = wob_payload_object.getSaveToWalletRequest()
signer = crypt.Signer.from_string(key)
signed_jwt = crypt.make_signed_jwt(signer, payload)
response = webapp2.Response(signed_jwt)
response.content_type = 'Application/JWT'
return response
def handleInsert(request):
"""Make API call to insert a new loyalty or offer class.
Args:
request: A HTTP request object.
Returns:
The result indicating success/failure of the API call to insert the class.
"""
insert_type = request.GET.get('type', '')
if insert_type == 'loyalty':
object_id = config.LOYALTY_CLASS_ID
api_object = loyalty.generate_loyalty_class(
config.ISSUER_ID, object_id)
collection = service.loyaltyclass()
elif insert_type == 'offer':
object_id = config.OFFER_CLASS_ID
api_object = offer.generate_offer_class(
config.ISSUER_ID, object_id)
collection = service.offerclass()
api_request = collection.insert(body=api_object)
api_response = api_request.execute()
response = webapp2.Response('Successfully inserted object')
if 'error' in api_response.keys():
response = webapp2.Response('Error inserting object %s' % object_id)
return response
def handleWebservice(request):
"""Creates wallet object according to webservice requests.
Args:
request: A HTTP request object.
Returns:
Returns object on success, or, error on failure.
"""
jsonobj = json.loads(request.body)
first_name = jsonobj['params']['walletUser']['firstName']
#using first_name to test different error codes
success = (first_name.startswith('SUCCESS'))
if success:
#possible success status codes:
#SUCCESS, SUCCESS_ACCOUNT_ALREADY_CREATED, SUCCESS_ACCOUNT_ALREADY_LINKED
jwt = {
'iss': config.SERVICE_ACCOUNT_EMAIL_ADDRESS,
'aud': config.AUDIENCE,
'typ': config.LOYALTY_WEB,
'iat': int(time.time()),
'payload': {
'loyaltyObjects': [],
'webserviceResponse': {
'status': 'SUCCESS'
},
}
}
linking_id = request.params.get('linkingId')
loyalty_object_id = linking_id if linking_id else config.LOYALTY_OBJECT_ID
loyalty_object = loyalty.generate_loyalty_object(
config.ISSUER_ID, config.LOYALTY_CLASS_ID, loyalty_object_id)
jwt['payload']['loyaltyObjects'].append(loyalty_object)
else:
#possible status error codes:
#ERROR_INVALID_DATA_FORMAT, ERROR_DATA_ON_MERCHANT_RECORD_DIFFERENT
#ERROR_INVALID_LINKING_ID, ERROR_PREEXISTING_ACCOUNT_REQUIRES_LINKING, ERROR_ACCOUNT_ALREADY_LINKED
error_action = 'link' if request.params.get('linkingId') else 'signup'
jwt = {
'iss': config.SERVICE_ACCOUNT_EMAIL_ADDRESS,
'aud': config.AUDIENCE,
'typ': config.LOYALTY_WEB,
'iat': int(time.time()),
'payload': {
'webserviceResponse': {
'status': 'ERROR_INVALID_DATA_FORMAT',
'invalidField': ['zipcode','phone']
},
}
}
signer = crypt.Signer.from_string(key)
signed_jwt = crypt.make_signed_jwt(signer, jwt)
response = webapp2.Response(signed_jwt)
response.content_type = 'Application/JWT'
return response
application = webapp2.WSGIApplication([
('/', displayIndex),
('/jwt', handleJwt),
('/insert', handleInsert),
('/webservice', handleWebservice)
])