-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
252 lines (191 loc) · 10.8 KB
/
Copy pathserver.py
File metadata and controls
252 lines (191 loc) · 10.8 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
from fastapi import FastAPI, Request , HTTPException
from fastapi.responses import HTMLResponse , RedirectResponse , JSONResponse
from dotenv import load_dotenv
import os
import threading
import traceback
from logger import log_error, log_info
from db_operations import read_admin_user , read_all_quotes , block_account , Quote , write_quote , read_quotes_by_author , delete_quote_by_id
from password_hashing import verify_password
from jwt_token_operations import create_access_token, read_access_token
SESSION = {}
load_dotenv()
app = FastAPI()
@app.get('/health', response_class=JSONResponse)
async def health_check():
return JSONResponse(content={"status": "ok"}, status_code=200)
@app.post('/login',response_class=JSONResponse)
async def login(request: Request):
try:
request_data = await request.json()
username = request_data.get("username")
password = request_data.get("password")
if not username or not password:
if username in SESSION:
del SESSION[username]
return JSONResponse(content={"message": "Username and password are required"}, status_code=200)
response , status = read_admin_user(username)
response_data = {
"status": False,
"account_blocked": False,
"reason": "",
"attempts_left": max(0, 3 - SESSION[username]["attempts"]) if username in SESSION else 3
}
if not status:
response_data["reason"] = "User not found"
if username in SESSION:
del SESSION[username]
return JSONResponse(content=response_data, status_code=200)
if response.blocked:
response_data['account_blocked'] = True
response_data['reason'] = "Your account has been blocked due to multiple failed login attempts. Please contact support."
response_data['attempts_left'] = 0
if username in SESSION:
del SESSION[username]
return JSONResponse(content=response_data, status_code=200)
correct_password = verify_password(password, response.password)
if not correct_password:
if username in SESSION:
SESSION[username]["attempts"] += 1
else:
SESSION[username] = {"attempts": 1, "blocked": False}
if SESSION[username]["attempts"] >= 3:
blocked = block_account(username)
if blocked:
log_error(f"blocked account for username: {username}")
SESSION[username]["blocked"] = True
response_data["account_blocked"] = SESSION[username]["blocked"] if username in SESSION else False
response_data["reason"] = "Invalid username or password"
response_data["attempts_left"] = max(0, 3 - SESSION[username]["attempts"]) if username in SESSION else 3
if SESSION[username]["blocked"]:
response_data["reason"] = "Your account has been blocked due to multiple failed login attempts. Please contact support."
return JSONResponse(content=response_data, status_code=200)
response_data["reason"] = "Login successful"
response_data["attempts_left"] = SESSION[username]["attempts"] if username in SESSION else 0
response_data["account_blocked"] = False
response_data["status"] = True
if username in SESSION:
del SESSION[username]
response = JSONResponse(content=response_data, status_code=200)
access_token = create_access_token(username=username)
if access_token:
response.set_cookie(key="access_token", value=access_token, httponly=True, secure=True, samesite="None",max_age=900)
return response
except Exception as e:
exception_traceback = traceback.format_exc()
error_name = type(e).__name__
log_error(message=f"Location : login - file : server.py : Error Name - {error_name}",exc_info=exception_traceback)
return JSONResponse(content={
"status": False,
"account_blocked": SESSION[username]["blocked"] if username in SESSION else False,
"reason": "Internal server error your account is not blocked but you can try again after sometime",
"attempts_left": max(0, 3 - SESSION[username]["attempts"]) if username in SESSION else 0
}, status_code=200)
@app.get('/auth_check',response_class=JSONResponse)
async def auth_check(request: Request):
try:
access_token = request.cookies.get("access_token")
if not access_token:
return JSONResponse(content={"logged_in":False},status_code=200)
token_data = read_access_token(access_token)
if not token_data.get("success"):
response = JSONResponse(content={"logged_in":False},status_code=200)
response.delete_cookie("access_token")
return response
return JSONResponse(content={"logged_in":True,"username":token_data["username"]},status_code=200)
except Exception as e:
exception_traceback = traceback.format_exc()
error_name = type(e).__name__
log_error(message=f"Location : auth_check - file : server.py : Error Name - {error_name}",exc_info=exception_traceback)
return JSONResponse(content={"logged_in": False}, status_code=200)
@app.get('/quote_fetch',response_class=JSONResponse)
async def quote_fetch(request: Request):
try:
quotes , status = read_all_quotes()
if not status:
return JSONResponse(content={"quote_available": False },status_code=200)
if isinstance(quotes, list) and len(quotes) > 0:
return JSONResponse(content={"quote_available": True,"quotes":quotes},status_code=200)
return JSONResponse(content={"quote_available": False},status_code=200)
except Exception as e:
exception_traceback = traceback.format_exc()
error_name = type(e).__name__
log_error(message=f"Location : quote_fetch - file : server.py : Error Name - {error_name}",exc_info=exception_traceback)
return JSONResponse(content={"quote_available": False },status_code=200)
@app.post('/quote_post',response_class=JSONResponse)
async def quote_post(request: Request):
try:
access_token = request.cookies.get("access_token")
if not access_token:
return JSONResponse(content={"status": False, "reason": "Unauthorized"}, status_code=200)
token_data = read_access_token(access_token)
if not token_data.get("success"):
response = JSONResponse(content={"status": False, "reason": "Unauthorized"}, status_code=200)
response.delete_cookie("access_token")
return response
request_data = await request.json()
quote = Quote(**request_data)
quote , status = write_quote(quote)
if not status:
return JSONResponse(content={"status": False, "reason": quote}, status_code=200)
return JSONResponse(content={"status": True, "quote": quote.model_dump() if isinstance(quote, Quote) else None}, status_code=200)
except Exception as e:
exception_traceback = traceback.format_exc()
error_name = type(e).__name__
log_error(message=f"Location : quote_post - file : server.py : Error Name - {error_name}",exc_info=exception_traceback)
return JSONResponse(content={ "status": False, "reason": "Internal server error"}, status_code=200)
@app.post('/logout',response_class=JSONResponse)
async def logout(request: Request):
response = JSONResponse(content={"status": True, "message": "Logged out successfully"}, status_code=200)
response.delete_cookie("access_token")
return response
@app.post('/admin_quote_get',response_class=JSONResponse)
async def admin_quote_get(request: Request):
try:
access_token = request.cookies.get("access_token")
if not access_token:
return JSONResponse(content={"status": False, "reason": "Unauthorized"}, status_code=200)
token_data = read_access_token(access_token)
if not token_data.get("success"):
response = JSONResponse(content={"status": False, "reason": "Unauthorized"}, status_code=200)
response.delete_cookie("access_token")
return response
author = token_data["username"]
quotes , status = read_quotes_by_author(author)
if not status:
return JSONResponse(content={"quote_available": False , "reason": "Failed to fetch quotes"},status_code=200)
if isinstance(quotes, list) and len(quotes) > 0:
return JSONResponse(content={"quote_available": True,"quotes":quotes},status_code=200)
return JSONResponse(content={"quote_available": False , "reason": "No quotes found for the specified author"},status_code=200)
except Exception as e:
exception_traceback = traceback.format_exc()
error_name = type(e).__name__
log_error(message=f"Location : admin_quote_get - file : server.py : Error Name - {error_name}",exc_info=exception_traceback)
return JSONResponse(content={"quote_available": False , "reason": "An error occurred while fetching quotes"},status_code=200)
@app.post('/quote_delete',response_class=JSONResponse)
async def quote_delete(request: Request):
try:
access_token = request.cookies.get("access_token")
if not access_token:
return JSONResponse(content={"status": False, "reason": "Unauthorized"}, status_code=200)
token_data = read_access_token(access_token)
if not token_data.get("success"):
response = JSONResponse(content={"status": False, "reason": "Unauthorized"}, status_code=200)
response.delete_cookie("access_token")
return response
request_data = await request.json()
quote_id = request_data.get("quote_id")
if not quote_id:
return JSONResponse(content={"deleted": False, "reason": "Quote ID is required"}, status_code=200)
message , status = delete_quote_by_id(quote_id)
if not status:
return JSONResponse(content={"deleted": False, "reason": message}, status_code=200)
if message is None:
return JSONResponse(content={"deleted": True, "message": "Quote deleted successfully"}, status_code=200)
else:
return JSONResponse(content={"deleted": False, "reason": message}, status_code=200)
except Exception as e:
exception_traceback = traceback.format_exc()
error_name = type(e).__name__
log_error(message=f"Location : quote_delete - file : server.py : Error Name - {error_name}",exc_info=exception_traceback)
return JSONResponse(content={"deleted": False, "reason": "An error occurred while deleting the quote"}, status_code=200)