-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutes.py
324 lines (222 loc) · 9.26 KB
/
routes.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
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
import secrets
from datetime import timedelta
from fastapi import Depends, FastAPI, HTTPException, status, UploadFile
from fastapi import Depends, FastAPI, HTTPException, Request, status, UploadFile
from logger import logger, error_logger
from os import path
from PIL import Image
from fastapi.responses import HTMLResponse
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from passlib.context import CryptContext
from config.auth import authenticate_user, ACCESS_TOKEN_EXPIRE_MINUTES, create_access_token, get_current_active_user
from config.db import session
from models.models import delete_posts, fetch_posts, fetch_post, initiate, insert_user, insert_posts, save_picture, update_posts, user_posts
from schema.schema import PostSchema, Token, User, User#
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
logger.info("Starting Blog APIs...")
@app.on_event("startup")
async def initiate_tables():
if initiate():
logger.info("Database Populated with dummy values")
@app.get("/home", response_class=HTMLResponse)
async def home(request: Request):
return templates.TemplateResponse(request=request, name="layout.html", context={"id": 1})
@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
"""
Endpoint to generate access token for user login.
Args:
form_data (OAuth2PasswordRequestForm): Form data containing username and password.
Returns:
Token: Access token.
"""
exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username/password",
headers={"WWW-Authenticate": "Bearer"})
logger.info("Parsing the csrf token to user")
user = authenticate_user(form_data.username, form_data.password)
if not user:
error_logger.error("User is trying to login but is not authenticated.")
raise exception
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(data={"sub": user.username}, expires_delta=access_token_expires)
return {"access_token": access_token, "token_type": "bearer"}
@app.get("/users-me", response_model=User)
async def read_users_me(current_user: User = Depends(get_current_active_user)):
"""
Endpoint to read user details.
Args:
current_user (User): Current authenticated user.
Returns:
User: User details.
"""
logger.info(f"Reading credentials of user {current_user.username}")
return current_user
@app.get("/users-items")
async def read_own_items(current_user: User = Depends(get_current_active_user)):
"""
Get all items owned by the current user.
Args:
current_user (User): Current authenticated user.
Returns:
list: List of items owned by the current user.
"""
logger.info(f"Reading all posts printed by {current_user.username}")
return [{"item_id": 1, "owner": current_user}]
@app.post("/#")
async def #(user: User#):
"""
Create a new user.
Args:
user (User#): User details from the # form.
Returns:
dict: Details of the created user.
Raises:
HTTPException: If unable to create a user.
"""
exception = HTTPException(status_code=status.HTTP_406_NOT_ACCEPTABLE, detail="Either user already exist or you're entering a wrong data")
inserted = insert_user(user)
if inserted:
logger.info(f"Creating a new user with username: {user.username}")
return { "Details": "User is created successfully!"}
error_logger.error("Unable to create a user.")
raise exception
@app.get("/posts")
async def posts(current_user: User = Depends(get_current_active_user)):
"""
Get all posts.
Args:
current_user (User): Current authenticated user.
Returns:
dict: Details of all posts.
Raises:
HTTPException: If no posts are found.
"""
exception = HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Couldn't find any posts")
all_posts = fetch_posts()
try:
if all_posts:
logger.info("Displaying all posts")
return {"Posts": all_posts}
except FileNotFoundError:
error_logger.error("Couldn't fetch any posts from database")
raise exception
@app.post("/insert-post")
async def insert_post(post: PostSchema, current_user: User = Depends(get_current_active_user)):
"""
Insert a new post.
Args:
post (PostSchema): Details of the new post.
current_user (User): Current authenticated user.
Returns:
dict: Details of the inserted post.
Raises:
HTTPException: If the post format is invalid or insertion fails.
"""
exception = HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Invalid format")
inserted = insert_posts(post, current_user)
if inserted:
logger.info(f"Inserting a new posts by user: {current_user.username}")
return { "Details": current_user.id, "post": post }
error_logger.error("Coulnt insert a new post")
raise exception
@app.get("/user-posts")
async def user_post(current_user: User = Depends(get_current_active_user)):
"""
Get all posts associated with the current user.
Args:
current_user (User): Current authenticated user.
Returns:
dict: All posts of the current user.
Raises:
HTTPException: If no posts are found for the current user.
"""
exception = HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"post with user ID: {current_user.id} does not exists")
all_post = user_posts(current_user)
if all_post:
logger.info(f"Displaying all posts of user {current_user.username}")
return all_post
error_logger.error(f"Couldn't fine any user with username {current_user.username}")
raise exception
@app.get("/search-post/{p_id}")
async def search_post(p_id: int, current_user: User = Depends(get_current_active_user)):
"""
Search for a post by post ID.
Args:
p_id (int): Post ID to search.
current_user (User): Current authenticated user.
Returns:
dict: Details of the searched post.
Raises:
HTTPException: If the post with the given ID is not found.
"""
exception = HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="post does not exists")
post = fetch_post(p_id)
if post:
logger.info(f"Searching for a post with post ID {p_id}")
return {"Post": post}
error_logger.error(f"Couldn't search any post with post ID {p_id}")
raise exception
@app.put("/update-post/{p_id}")
async def update_post(p_id: int, post: PostSchema, current_user: User = Depends(get_current_active_user)):
"""
Update a post by post ID.
Args:
p_id (int): Post ID to update.
post (PostSchema): Updated post details.
current_user (User): Current authenticated user.
Returns:
dict: Details of the updated post.
Raises:
HTTPException: If the post with the given ID is not found.
"""
exception = HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="post does not exists")
updated = update_posts(p_id, post, current_user)
if updated:
logger.info(f"Updating a post with post ID {p_id}")
return { "Status": "Post Updated Successfully" }
error_logger.error(f"Couldn't Find any post with ID {p_id} to update")
raise exception
@app.delete("/delete-post/{p_id}")
async def delete_post(p_id: int, current_user: User = Depends(get_current_active_user)):
"""
Delete a post by post ID.
Args:
p_id (int): Post ID to delete.
current_user (User): Current authenticated user.
Returns:
dict: Details of the deleted post.
Raises:
HTTPException: If the post with the given ID is not found.
"""
exception = HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Either post doesn't exist or you dont have the right access to delete this post")
deleted = delete_posts(p_id, current_user.id)
if deleted:
logger.info(f"deleting a post with post ID {p_id}")
return {"status": "Post Deleted Successfully"}
error_logger.error(f"Unable to delete a post with post ID {p_id}")
raise exception
@app.post("/upload-file")
async def create_upload_file(file: UploadFile):
"""
Upload a file.
Args:
file (UploadFile): Uploaded file.
Returns:
dict: Details of the uploaded file.
"""
random_hex = secrets.token_hex(8)
_, f_ext = path.splitext(file.filename)
picture_fn = random_hex + f_ext
picture_path = path.join(app.root_path, 'static/posts', picture_fn)
output_size = (150,150)
i = Image.open(file.file)
i.thumbnail(output_size)
i.save(picture_path)
save_picture(picture_fn)
return {"Details": "Picture Successfully Uploaded"}