-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLFEditProfile.py
More file actions
209 lines (186 loc) · 6.89 KB
/
Copy pathLFEditProfile.py
File metadata and controls
209 lines (186 loc) · 6.89 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
import json
import boto3
from opensearchpy import OpenSearch, RequestsHttpConnection
from requests_aws4auth import AWS4Auth
from botocore.exceptions import ClientError
from boto3.dynamodb.conditions import Key
from datetime import datetime, timedelta
import json
REGION = 'us-east-1'
HOST = 'search-cuthen-temp-5fyo5fvs7x7t2myle4ztwa7swa.us-east-1.es.amazonaws.com'
INDEX1 = 'max_id'
INDEX2 = 'user_to_inv'
INDEX3 = 'user_to_group'
def lambda_handler(event, context):
# uni is the primary/paritition key
# note they all have unique attributes
print(event)
user_data = event['body']
user_data = json.loads(user_data)
print(f"{user_data}")
# mock
# user_data = {
# "user_id": 1,
# "first_name": "Timothy",
# "last_name": "Wang",
# "uni": "tjw2145",
# "email": "tjw2145@columbia.edu",
# "hobbies": "none",
# "major": "none",
# "school": "none",
# "academic_interests": "none",
# "class_schedule": "none",
# "exam_schedule": "none",
# "phone_number": "none",
# "zipcode": "12345"
# }
if 'is_login' in user_data:
print("user is logging in")
user_email = ''
for feature_dict in user_data["newFeatures"]:
feature_name, feature = list(feature_dict.items())[0]
if feature_name == "email":
user_email = feature
break
print(f"querying users with the email {user_email}")
orginal = query_data(attribute='email',key=user_email, table="user_table")
if orginal == None:
print("user does not exist, creating a new one")
new_id = create_user(user_data["newFeatures"], table="user_table")
print(f"new_id: {new_id}")
updated_Data = lookup_data({'user_id': new_id}, table="user_table")
response = {"message": "new user created","input": user_data , "updated_Data":updated_Data}
resp = {
'statusCode': 200,
"headers": {"Access-Control-Allow-Origin": "*"},
'body': json.dumps(response)
}
return resp
else:
print("user exists")
response = {"message": "user exists", "input": user_data , "updated_Data":orginal}
resp = {
'statusCode': 200,
"headers": {"Access-Control-Allow-Origin": "*"},
'body': json.dumps(response)
}
return resp
else:
update_item_list({'user_id': int(user_data["currentUser"])},user_data["newFeatures"],table="user_table")
updated_Data = lookup_data({'user_id': user_data["currentUser"]}, table="user_table")
response = {"message":"update success","input": user_data , "updated_Data":updated_Data}
resp = {
'statusCode': 200,
"headers": {"Access-Control-Allow-Origin": "*"},
'body': json.dumps(response)
}
return resp
def lookup_data(key, db=None, table='6998Demo'):
if not db:
db = boto3.resource('dynamodb')
table = db.Table(table)
try:
response = table.get_item(Key=key)
except ClientError as e:
print('Error', e.response['Error']['Message'])
else:
# if user not in table
if 'Item' not in response:
return None
res = response['Item']
res['user_id'] = int(res['user_id'])
print(f"{res =}")
return res
def query_data(attribute, key, db=None, table='6998Demo'):
if not db:
db = boto3.resource('dynamodb')
table = db.Table(table)
try:
response = table.query(IndexName='email-index', KeyConditionExpression=Key(attribute).eq(key))
except ClientError as e:
print('Error', e.response['Error']['Message'])
return None
else:
# if user not in table
if 'Items' not in response or response['Items'] == []:
return None
res = response['Items'][0]
res['user_id'] = int(res['user_id'])
print(f"{res =}")
return res
def update_item_list(key, feature_dict_list, db=None, table='6998Demo'):
if not db:
db = boto3.resource('dynamodb')
table = db.Table(table)
for feature_dict in feature_dict_list:
feature_name, feature = list(feature_dict.items())[0]
print(f"feature_name: {feature_name}, feature: {feature}")
if feature_name == "user_id":
continue
print(f"Key: {key}")
response = table.update_item(
Key=key,
UpdateExpression="set #feature=:f",
ExpressionAttributeValues={
':f': feature
},
ExpressionAttributeNames={
"#feature": feature_name
},
ReturnValues="UPDATED_NEW"
)
return
def get_awsauth(region, service):
cred = boto3.Session().get_credentials()
return AWS4Auth(cred.access_key,
cred.secret_key,
region,
service,
session_token=cred.token)
def query(client, index, field, term):
q = {"query": {
"bool": {
"must": {
"match": {
field: term
}
}
}
}
}
res = client.search(index=index, body=q)
print(res)
hits = res['hits']['hits']
print(f"hits on max user id: {hits[0]['_source']}")
return hits[0]['_source']
def create_user(features, db=None, table='6998Demo'):
if not db:
db = boto3.resource('dynamodb')
table = db.Table(table)
os_client = OpenSearch(hosts=[{
'host': HOST,
'port': 443
}],
http_auth=get_awsauth(REGION, 'es'),
use_ssl=True,
verify_certs=True,
connection_class=RequestsHttpConnection)
# get max user id
max_id = int(query(client=os_client, index=INDEX1, field='type', term='user_id')['max'])
item = {}
for feature_dict in features:
feature_name, feature = list(feature_dict.items())[0]
item[feature_name] = str(feature)
item['user_id'] = max_id + 1
print(f"item to be inserted into dynamodb: {item}")
response = table.put_item(Item = item)
print("user created and inserted into dynamodb")
# update max user id
max_id_document = {"max": max_id + 1, "type": "user_id"}
os_client.index(index=INDEX1, id = 2, body=max_id_document, refresh=True)
# create new user_to_inv and user_to_group entry
inv_document = {"user_id": max_id + 1, "pending_inv_ids": []}
os_client.index(index=INDEX2, id = max_id + 1, body=inv_document, refresh=True)
group_document = {"user_id": max_id + 1, "group_id": []}
os_client.index(index=INDEX3, id = max_id + 1, body=group_document, refresh=True)
return max_id + 1