-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
359 lines (292 loc) · 12.1 KB
/
api.py
File metadata and controls
359 lines (292 loc) · 12.1 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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
import json
import boto3
from flask import Flask, request, Response, jsonify
from flask_cors import CORS, cross_origin
from botocore.exceptions import ClientError
from boto3.dynamodb.conditions import Key, Attr
from decimal import Decimal
app = Flask(__name__)
CORS(app)
cognito_client = boto3.client('cognito-idp')
user_pool_id = 'us-east-1_k1xovBg3P'
dynamodb = boto3.resource('dynamodb')
user_table = dynamodb.Table('User-Table')
advisor_table = dynamodb.Table('Advisor-Table')
advisor_application_table = dynamodb.Table('Advisor-Application-Table')
#http://127.0.0.1:5000/
@app.route('/')
@cross_origin()
def hello():
return "Health Check!"
def email_exists(email):
try:
response = cognito_client.list_users(
UserPoolId=user_pool_id,
Filter=f'email = "{email}"',
)
return bool(response.get('Users'))
except ClientError as e:
print(f"An error occurred when checking the email: {e}")
return False
#http://127.0.0.1:5000/users/register/<username>/<password>
@app.route('/users/register/<username>/<password>/<email>', methods = ['POST'])
@cross_origin()
def register_user(username, password, email):
try:
if not username or not password:
return "Username, email, and password are required", 401
if email_exists(email):
return "Email already exists", 401
cognito_client.sign_up(
ClientId='73tr5iabe4sulif3qnqn0gthsu',
Username=username,
Password=password,
UserAttributes=[
{'Name': 'email', 'Value': email},
]
)
user_table.put_item(Item={'username': username})
return "User registered successfully", 200
except cognito_client.exceptions.UsernameExistsException as e:
return "Username already exists", 401
except cognito_client.exceptions.InvalidPasswordException as e:
return "Password does not meet requirements", 401
except ClientError as e:
return Response(response=json.dumps({"error": str(e)}), content_type='application/json', status=400)
#http://127.0.0.1:5000/advisors/register/<username>/<password>
@app.route('/advisors/register/<username>/<password>/<email>/<number>/<address>', methods = ['POST'])
@cross_origin()
def register_advisor_account(username, password, email, number, address):
try:
if not username or not password:
return "Username, email, and password are required", 401
if email_exists(email):
return "Email already exists", 401
cognito_client.sign_up(
ClientId='73tr5iabe4sulif3qnqn0gthsu',
Username=username,
Password=password,
UserAttributes=[
{'Name': 'email', 'Value': email},
]
)
item = {
'username': username,
'phone_number': number,
'address': address
}
advisor_application_table.put_item(Item = item)
return "User registered successfully", 200
except cognito_client.exceptions.UsernameExistsException as e:
return "Username already exists", 401
except cognito_client.exceptions.InvalidPasswordException as e:
return "Password does not meet requirements", 401
except ClientError as e:
return "Method Not Allowed", 405
#http://127.0.0.1:5000/advisors/registerinformation/<username>/<password>
@app.route('/advisors/registerinformation/<username>/<number>/<address>', methods = ['POST'])
@cross_origin()
def register_advisor_information(username, number, address):
data = request.json
languages_set = set(data.get('languages', []))
interests_set = set(data.get('interests', []))
location = data.get('location')
item = {
'username': username,
'phone_number': number,
'address': address,
'languages': list(languages_set),
'interests': list(interests_set),
'location': location
}
advisor_application_table.put_item(Item = item)
return "Advisor Updated", 200
#http://127.0.0.1:5000/users/verify/<username>/<password>
@app.route('/users/verify/<username>/<password>', methods = ['GET'])
@cross_origin()
def user_login(username, password):
if not username or not password:
return "Username and password are required", 401
try:
response = cognito_client.initiate_auth(
ClientId= '73tr5iabe4sulif3qnqn0gthsu',
AuthFlow='USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': username,
'PASSWORD': password,
}
)
dynamo_response = user_table.query(KeyConditionExpression=boto3.dynamodb.conditions.Key('username').eq(username))
items = dynamo_response.get('Items', [])
if len(items) > 0:
return "User exists and password is correct", 200
else:
return "User not yet approved", 404
except cognito_client.exceptions.UserNotFoundException as e:
return "User not found", 404
except cognito_client.exceptions.NotAuthorizedException as e:
return "Password is Incorrect", 402
except ClientError as e:
return "Method Not Allowed", 405
#http://127.0.0.1:5000/advisor/verify/<username>/<password>
@app.route('/advisors/verify/<username>/<password>', methods = ['GET'])
@cross_origin()
def advisor_login(username, password):
if not username or not password:
return "Username and password are required", 401
try:
response = cognito_client.initiate_auth(
ClientId= '73tr5iabe4sulif3qnqn0gthsu',
AuthFlow='USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': username,
'PASSWORD': password,
}
)
dynamo_response = advisor_table.query(KeyConditionExpression=boto3.dynamodb.conditions.Key('username').eq(username))
items = dynamo_response.get('Items', [])
if len(items) > 0:
return "User exists and password is correct", 200
else:
return "User not yet approved", 404
except cognito_client.exceptions.UserNotFoundException as e:
return "User not found", 404
except cognito_client.exceptions.NotAuthorizedException as e:
return "Password is Incorrect", 402
except ClientError as e:
return "Method Not Allowed", 405
#http://127.0.0.1:5000/advisors/query
@app.route('/advisors/query', methods=['GET'])
@cross_origin()
def query_advisors():
languages = request.args.get('languages')
location = request.args.get('location')
interests = request.args.get('interests')
try:
# Initial query with all filters
scan_args = {
'FilterExpression': Attr('location').eq(location)
}
if languages:
scan_args['FilterExpression'] = scan_args['FilterExpression'] & Attr('languages').contains(languages)
if interests:
for interest in interests.split(','):
scan_args['FilterExpression'] = scan_args['FilterExpression'] & Attr('interests').contains(interest)
response = advisor_table.scan(**scan_args)
items = response.get('Items', [])
# Check if response is empty and location is set
if not items and location:
print("Requerying without interests")
scan_args.pop('FilterExpression', None)
scan_args['FilterExpression'] = Attr('location').eq(location)
if languages:
scan_args['FilterExpression'] = scan_args['FilterExpression'] & Attr('languages').contains(languages)
response = advisor_table.scan(**scan_args)
items = response.get('Items', [])
sorted_items = sorted(
items,
key=lambda x: (
float(x.get('rating', 0)) / float(x['rating_num']) if x.get('rating_num', 1) != 0 else float(x.get('rating', 0))
),reverse=True
)
for item in sorted_items:
for key, value in item.items():
if isinstance(value, Decimal):
item[key] = str(value)
return jsonify(sorted_items)
except ClientError as e:
print(f"An error occurred: {e}")
return jsonify({"error": str(e)}), 500
#http://127.0.0.1:5000/advisors/rating/<username>
@app.route('/advisors/rating/<username>', methods=['GET'])
@cross_origin()
def get_advisor_rating(username):
try:
response = advisor_table.get_item(
Key={'username': username},
AttributesToGet=['rating', 'rating_num']
)
item = response.get('Item', None)
if not item:
return jsonify({
'username': username,
'average_rating': None,
'message': 'No User Found'
}), 404
if item['rating_num'] == 0:
return jsonify({
'username': username,
'average_rating': None,
'message': 'No Rating'
}), 200
# Convert Decimal to float for JSON serialization
average_rating = float(item['rating']) / int(item['rating_num'])
return jsonify({
'username': username,
'average_rating': average_rating
}), 200
except Exception as e:
print(f"An error occurred: {e}")
return jsonify({
'error': str(e)
}), 500
#http://127.0.0.1:5000/advisors/rate/<username>/<int:rating>
@app.route('/advisors/rate/<username>/<int:rating>', methods=['POST'])
@cross_origin()
def rate_advisor(username, rating):
if not username or rating not in range(1, 6):
return jsonify({'message': 'Username and valid rating (1-5) are required'}), 400
try:
# Fetch the current rating data for the advisor
response = advisor_table.get_item(Key={'username': username})
item = response.get('Item', None)
if not item:
return jsonify({'message': 'Advisor not found'}), 404
# Update the rating and rating number
new_rating_num = int(item.get('rating_num', 0)) + 1
new_rating_total = int(item.get('rating', 0)) + rating
new_average_rating = new_rating_total / new_rating_num
if new_average_rating < 3 and new_rating_num > 10:
# Delete the advisor from the table if the average rating is less than 3
advisor_table.delete_item(Key={'username': username})
return jsonify({'message': 'Advisor deleted due to low rating'}), 200
else:
# Update the item in the DynamoDB table
advisor_table.update_item(
Key={'username': username},
UpdateExpression='SET rating = :r, rating_num = :rn',
ExpressionAttributeValues={
':r': new_rating_total,
':rn': new_rating_num
}
)
return jsonify({'message': 'Rating updated successfully'}), 200
except Exception as e:
print(f"An error occurred: {e}")
return jsonify({'error': str(e)}), 500
#http://127.0.0.1:5000/advisors/getall
@app.route('/advisors/getall', methods = ['GET'])
@cross_origin()
def get_advisors():
try:
# Just get top 10 advisors
response = advisor_table.scan(AttributesToGet=['username', 'location', 'interests', 'languages', 'rating', 'rating_num'], Limit = 10)
items = response.get('Items', [])
sorted_items = sorted(
items,
key=lambda x: (
float(x.get('rating', 0)) / float(x['rating_num']) if x.get('rating_num', 1) != 0 else float(x.get('rating', 0))
),
reverse=True # For descending order
)
for item in sorted_items:
for key, value in item.items():
if isinstance(value, Decimal):
item[key] = str(value)
#advisor_response = json.dumps(usernames)
#return Response(response=advisor_response, content_type='application/json', status=200)
return jsonify(sorted_items)
except Exception as e:
return Response(response=json.dumps({"error": str(e)}), content_type='application/json', status=500)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)