This repository has been archived by the owner on Jun 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
240 lines (167 loc) · 5.49 KB
/
api.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
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
import os
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import hashlib
import mysql.connector
import time
app = FastAPI()
origins = [
"https://messenger.yajatkumar.com",
"http://localhost:3000",
"http://messenger.local",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def get_connection():
appDb = mysql.connector.connect(
host=os.environ['DB_HOST'],
user=os.environ['DB_USER'],
password=os.environ['DB_PASS'],
database=os.environ['DB_NAME']
)
return appDb
@app.post('/api/v1/users/add')
async def add_user(user: str = None, pwd: str = None):
# Add a new user to UsersAuth database with passed username and sha256 encrypted password
if user == None or pwd == None:
return 'user/pwdMissing'
exists = await valid_username(user)
if exists:
return 'alreadyExists'
else:
appDb = get_connection()
appCursor = appDb.cursor()
sql = "INSERT INTO UsersAuth (username, password) VALUES (%s, %s)"
val = (user, sha256(pwd))
appCursor.execute(sql, val)
appDb.commit()
appCursor.close()
appDb.close()
return 'addedUser'
@app.post('/api/v1/users/user')
async def valid_username(user: str = None):
# Returns true if user exists
if user == None:
return 'userMissing'
appDb = get_connection()
appCursor = appDb.cursor()
sql = "SELECT * FROM UsersAuth WHERE username=%s"
val = (user,)
appCursor.execute(sql, val)
result = appCursor.fetchone()
appDb.commit()
appCursor.close()
appDb.close()
return result != None
@app.post('/api/v1/users/login')
async def valid_login(user: str = None, pwd: str = None):
# Returns true if user and pwd credentials are correct
if user == None or pwd == None:
return 'user/pwdMissing'
appDb = get_connection()
appCursor = appDb.cursor()
sql = "SELECT * FROM UsersAuth WHERE username=%s AND password=%s"
val = (user, sha256(pwd))
appCursor.execute(sql, val)
result = appCursor.fetchone()
appDb.commit()
appCursor.close()
appDb.close()
return result != None
@app.post('/api/v1/messages/add')
async def add_message(frm: str = None, to: str = None, msg: str = None):
# Add a new message with ids of from and to. Also the current time
if frm == None or to == None or msg == None:
return 'frm/to/msgMissing'
appDb = get_connection()
appCursor = appDb.cursor()
currentTime = time.strftime('%Y-%m-%d %H:%M:%S')
sql = "INSERT INTO Messages (msgFrom, msgTo, message, msgTime) VALUES (%s, %s, %s, %s)"
val = (int(frm), int(to), msg, currentTime)
appCursor.execute(sql, val)
appDb.commit()
appCursor.close()
appDb.close()
return 'addedMessage'
@app.post('/api/v1/users/find')
async def search_users(user: str = None):
# Returns users which contain the user str
if user == None:
return 'userMissing'
appDb = get_connection()
appCursor = appDb.cursor()
sql = "SELECT id, username FROM UsersAuth WHERE username LIKE '%" + user + "%'"
appCursor.execute(sql)
result = appCursor.fetchall()
appDb.commit()
appCursor.close()
appDb.close()
users = []
for x in result:
users.append({"id": x[0], "name": x[1]})
return users
@app.post('/api/v1/messages/list')
async def fetch_messages(frm: str = None, to: str = None):
# Returns messages which were sent to or from userId
if frm == None or to == None:
return 'frm/toMissing'
if not frm.isdigit():
return 'frmNotInt'
if not to.isdigit():
return 'toNotInt'
appDb = get_connection()
appCursor = appDb.cursor()
sql = "SELECT * FROM Messages WHERE (msgFrom=%s AND msgTo=%s) OR (msgFrom=%s AND msgTo=%s) ORDER BY msgTime"
val = (frm, to, to, frm)
appCursor.execute(sql, val)
result = appCursor.fetchall()
appDb.commit()
appCursor.close()
appDb.close()
messages = []
# Return the array with an additional parameter of sent
for x in result:
messages.append({"msg": x[3], "sent": x[1] == int(frm)})
return messages
@app.post('/api/v1/users/id')
async def fetch_id(user: str = None):
# Returns id from username
if user == None:
return 'userMissing'
appDb = get_connection()
appCursor = appDb.cursor()
sql = "SELECT id FROM UsersAuth WHERE username=%s"
val = (user,)
appCursor.execute(sql, val)
result = appCursor.fetchone()
appDb.commit()
appCursor.close()
appDb.close()
return result
@app.post('/api/v1/users/contacts')
async def fetch_contacts(user: str = None):
# Returns users who were contacted by user or the contacts who contacted user
if user == None:
return 'userMissing'
appDb = get_connection()
appCursor = appDb.cursor()
sql = "SELECT id, username FROM UsersAuth WHERE id IN (SELECT msgTo FROM Messages WHERE msgFrom=%s)\
OR id IN (SELECT msgFrom FROM Messages WHERE msgTo=%s)"
val = (user, user)
appCursor.execute(sql, val)
result = appCursor.fetchall()
appDb.commit()
appCursor.close()
appDb.close()
contacts = []
for x in result:
contacts.append({"id": x[0], "name": x[1]})
return contacts
def sha256(hash: str):
# Util function to return sha256 hash of the passed argument
return hashlib.sha256(hash.encode()).hexdigest()