forked from Neufal777/api-mlh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
103 lines (85 loc) · 2.94 KB
/
main.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
from fastapi import FastAPI, HTTPException, Security, Depends
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from pydantic import BaseModel
import uuid
import time
app = FastAPI()
class PerformanceMiddleware:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
start_time = time.time()
await self.app(scope, receive, send)
end_time = time.time()
print(f"Request processed in {end_time - start_time} seconds")
app.add_middleware(PerformanceMiddleware)
users = [
{"id": str(uuid.uuid4()),"username": "Pranav", "email": "[email protected]", "password":"pass", "role":"admin"},
{"id": str(uuid.uuid4()),"username": "Kosu", "email": "[email protected]", "password":"pass", "role":"user"},
]
#Pydantic model
class UserCreate(BaseModel):
username: str
email: str
password: str
class UserResponse(BaseModel):
id: str
username: str
email: str
class UserUpdate(BaseModel):
username: str
email: str
security = HTTPBasic()
# Check if user is authenticated
def authenticate(credentials: HTTPBasicCredentials = Security(security)):
user = None
for u in users:
if u["username"] == credentials.username and u["password"] == credentials.password:
user = u
return user
if user is None:
raise HTTPException(status_code=401, detail="User is not authenticated must be registered first")
return None
# authorize user
def authorize(user: dict = Depends(authenticate)):
if user["role"] != "admin":
raise HTTPException(status_code=403, detail="Permission denied")
return None
# Get all users if the user is authenticated and haave admin role
@app.get("/users", response_model=list[UserResponse])
def get_users(user: dict = Depends(authorize)):
return users
# Get user by id if the user is authenticated and haave admin roles
@app.get("/users/{user_id}", response_model=UserResponse)
def get_user(user_id: str, user: dict = Depends(authorize)):
for u in users:
if u["id"] == user_id:
return u
return {"message": "User not found"}
@app.post("/users")
def create_user(user: UserResponse):
new_user = {
"id": str(uuid.uuid4()),
"username": user.username,
"email": user.email
}
users.append(new_user)
return new_user, 201
@app.put("/users/{user_id}")
def update_user(user_id: str, user: UserResponse):
for u in users:
if u["id"] == user_id:
u["username"] = user.username
u["email"] = user.email
return u
return {"message": "User not found"}
@app.delete("/users/{user_id}")
def delete_user(user_id: str):
for i, user in enumerate(users):
if user["id"] == user_id:
users.pop(i)
return {"message": "User deleted successfully"}
return {"message": "User not found"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="localhost" , port=8000)