-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_function.py
More file actions
315 lines (250 loc) · 12.5 KB
/
lambda_function.py
File metadata and controls
315 lines (250 loc) · 12.5 KB
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
import json
from auth import *
from util import buildResponse, renderHtmlResponse
from user import *
from restaurants import *
from promotions import *
from donation import *
from verification import *
from payment import *
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
#default headers:
headers = {
'Content-Type' :'application/json',
'Access-Control-Allow-Origin' : '*'
}
def lambda_handler(event, context):
## setting logging for cloudwatch
logger.info(event)
##creating things i have to access
message = event['body']
event_headers = event['headers'] ##headers of the event
queryParams = event['queryStringParameters'] ##url parameters
multiqueryParams = event['multiValueQueryStringParameters'] ## url multi parameters
pathParams = event['pathParameters']
sourceIp = event_headers['X-Forwarded-For'] #ip source request
path = event['resource'] ##event path like /user/register or /user
httpMethod = event['httpMethod'] ##request httpMethod
##method to test that the api is working and a connection to the database has been established
if httpMethod == 'GET' and path == '/health':
response = buildResponse(200, headers, {'message': 'Health Check', 'queryParams': queryParams,'pathParams': pathParams})
elif httpMethod == 'POST' and path == '/user/register':
if message is None:
return buildResponse(401, headers, {'message':'Empty body'})
data = json.loads(message) ##message is the body of the api request
if 'user_name' in data and 'user_email' in data and 'user_password' in data:
nombre = data['user_name']
email = data['user_email']
contraseña = data['user_password']
else:
return buildResponse(401,headers,{'message' :'All fields requiered'})
if getUserByEmail(email):
return buildResponse(403,headers,{'message' :'Email is already in use'})
#parte de verificacion
verification_token = createVerifyToken(email,sourceIp)
sendVerificationEmail(email,verification_token)
response = createUser(nombre,email,contraseña,headers)
elif httpMethod == 'POST' and path == '/user/login':
if message is None:
return buildResponse(400, headers, {'message':'Empty body'})
data = json.loads(message) ##message is the body of the api request
if 'user_email' in data and 'user_password' in data:
email = data['user_email']
contraseña = data['user_password']
else:
return buildResponse(400,headers,{'message' :'All fields requiered'})
try:
with conn.cursor() as cur:
cur.execute("SELECT contraseña_usuario FROM usuarios WHERE email_usuario = %s", (email,))
stored_password_hash = cur.fetchone()
contraseña_bytes = contraseña.encode('utf-8')
if stored_password_hash:
stored_password_hash = stored_password_hash[0]
if hashlib.blake2b(contraseña_bytes).hexdigest() == stored_password_hash:
del stored_password_hash
user = getUserByEmail(email)
accessToken = generateToken(user[1],user[0],user[2],sourceIp)
if user[5] == 1:
response = buildResponse(200,headers, {'access-token': accessToken, 'verified': user[5]})
else:
response = buildResponse(403,headers, {'verified': user[5],'message':'email not verified' })
else:
return buildResponse(401,headers,{'message': 'Invalid Credentials'})
else:
return buildResponse(401,headers,{'message': 'Invalid Credentials'})
except Exception as e:
return buildResponse(500,headers,{'message': "DB Server Error :("})
elif httpMethod == 'GET' and path == '/verify':
if queryParams is not None and 'token' in queryParams:
token = queryParams['token']
result = verifyEmail(token,sourceIp)
else:
return buildResponse(401,headers,{'message': "No token"})
if result['verified'] == True:
return renderHtmlResponse("Verificación Exitosa", "Tu correo electrónico ha sido verificado con éxito.")
else:
return renderHtmlResponse("Error de Verificación", result['message'])
elif httpMethod == 'POST' and path == '/verify':
if message is None:
return buildResponse(401, headers, {'message':'Empty body'})
data = json.loads(message) ##message is the body of the api request
if 'user_email' in data:
email = data['user_email']
else:
return buildResponse(401,headers,{'message' :'All fields requiered'})
verification_token = createVerifyToken(email,sourceIp)
sendVerificationEmail(email,verification_token)
elif httpMethod == 'PATCH' and path == '/user':
if message is None:
return buildResponse(401, headers, {'message':'Empty body'})
data = json.loads(message) ##message is the body of the api request
if 'access-token' in event_headers:
token = event_headers['access-token']
if 'user_name' in data and 'user_email' in data:
nombre = data['user_name']
nuevo_email = data['user_email']
else:
return buildResponse(401,headers,{'message':'All fields requiered'})
result = authenticateToken(token,sourceIp)
id = result['id']
if result['verified'] == True:
new_token = generateToken(nuevo_email,id,nombre,sourceIp)
headers['access-token'] = new_token
user = getUserByEmail(result['email'])
if user is None:
return buildResponse(404,headers,{'message' :'Not Found in Database'})
if 'user_password' in data and data['user_password'] != "":
contraseña = data['user_password']
response = updateUserById(nombre,nuevo_email,contraseña,id,headers)
else:
response = updateUserByIdNoPassword(nombre,nuevo_email,id,headers)
else:
response = buildResponse(403,headers,{'message' : result['message']})
elif httpMethod == 'DELETE' and path == '/user':
if 'access-token' in event_headers:
token = event_headers['access-token']
else:
return buildResponse(401,headers,{'message' :'No JWT Token'})
result = authenticateToken(token,sourceIp)
if result['verified'] == True:
response = deleteUser(result['email'],headers)
else:
response = buildResponse(403,headers,{'message' : result['message']})
elif httpMethod == 'PATCH' and path == '/user/addPoints/{points}':
points = pathParams['points']
if 'access-token' in event_headers:
token = event_headers['access-token']
else:
return buildResponse(401,headers,{'message' :'No JWT Token'})
result = authenticateToken(token,sourceIp)
token = result['accessToken']
headers['access-token'] = token
id = result['id']
if result['verified'] == True:
response = addPoints(id,points,headers)
else:
response = buildResponse(403,headers,{'message' : result['message']})
elif httpMethod == 'POST' and path =='/webhook':
if 'access-token' in event_headers:
token = event_headers['access-token']
else:
return buildResponse(401,headers,{'message' :'No JWT Token'})
if message is None:
return buildResponse(401, headers, {'message':'Empty body'})
data = json.loads(message) ##message is the body of the api request
if 'amount' in data:
amount = data['amount']
else:
return buildResponse(401,headers,{'message' :'All fields requiered'})
result = authenticateToken(token,sourceIp)
token = result['accessToken']
headers['access-token'] = token
id = result['id']
if result['verified'] == True:
addPoints(id,amount,headers)
response = createDonation(id,amount,headers)
else:
response = buildResponse(403,headers, {'message': result['message']})
elif httpMethod == 'POST' and path == '/payment-sheet':
if 'access-token' in event_headers:
token = event_headers['access-token']
else:
return buildResponse(401,headers,{'message' :'No JWT Token'})
if message is None:
return buildResponse(401, headers, {'message':'Empty body'})
data = json.loads(message) ##message is the body of the api request
if 'amount' in data:
amount = data['amount']
else:
return buildResponse(401,headers,{'message' :'All fields requiered'})
result = authenticateToken(token,sourceIp)
token = result['accessToken']
email = result['email']
headers['access-token'] = token
if result['verified'] == True:
response = payment_sheet(headers,amount,email)
else:
response = buildResponse(403,headers, {'message': result['message']})
elif httpMethod == 'GET' and path == '/user':
if 'access-token' in event_headers:
token = event_headers['access-token']
else:
return buildResponse(401,headers,{'message' :'No JWT Token'})
result = authenticateToken(token,sourceIp)
token = result['accessToken']
headers['access-token'] = token
if result['verified'] == True:
user = getUserByEmail(result['email'])
if user is None:
response = buildResponse(404, headers,{'message': 'User Not Found'})
else:
response = buildResponse(200,headers,{'user_id':user[0],'user_name':user[2],'user_email':user[1],'user_points':user[3]})
else:
response = buildResponse(403,headers,{'message' : result['message']})
elif httpMethod == 'GET' and path == '/restaurants':
if 'access-token' in event_headers:
token = event_headers['access-token']
else:
return buildResponse(401,headers,{'message' :'No JWT Token'})
result = authenticateToken(token,sourceIp)
token = result['accessToken']
headers['access-token'] = token
if result['verified'] == True:
response = getRestaurants(headers)
else:
response = buildResponse(403,headers,{'message' : result['message']})
elif httpMethod == 'GET' and path == '/promotions':
if 'access-token' in event_headers:
token = event_headers['access-token']
else:
return buildResponse(401,headers,{'message' :'No JWT Token'})
result = authenticateToken(token,sourceIp)
token = result['accessToken']
headers['access-token'] = token
if result['verified'] == True:
if queryParams is not None and'id' in queryParams:
id = queryParams['id']
promotions = getRestaurantPromotions(int(id),headers)
response = promotions
else:
response = getPromotions(headers)
else:
response = buildResponse(403,headers,{'message' : result['message']})
elif httpMethod == 'GET' and path == '/donations':
if 'access-token' in event_headers:
token = event_headers['access-token']
else:
return buildResponse(401,headers,{'message' :'No JWT Token'})
result = authenticateToken(token,sourceIp)
token = result['accessToken']
id = result['id']
headers['access-token'] = token
if result['verified'] == True:
response = getDonationsByUserId(id,headers)
else:
response = buildResponse(403,headers,{'message' : result['message']})
else:
response = buildResponse(404, headers,{'message': 'Not Found'})
return response