-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
265 lines (210 loc) · 7.57 KB
/
Copy pathmain.py
File metadata and controls
265 lines (210 loc) · 7.57 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
253
254
255
256
257
258
259
260
261
262
263
264
265
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from typing import List
import models
import schemas
import auth
from database import engine, get_db
# Create database tables
models.Base.metadata.create_all(bind=engine)
# Initialize FastAPI app
app = FastAPI(
title="Task Manager API",
description="A task management API with JWT authentication",
version="1.0.0"
)
# ROOT ENDPOINT
@app.get("/", tags=["Root"])
def root():
"""Welcome endpoint"""
return {
"message": "Welcome to Task Manager API!",
"docs": "/docs",
"endpoints": {
"register": "POST /register",
"login": "POST /login",
"my_info": "GET /users/me",
"create_task": "POST /tasks/",
"get_tasks": "GET /tasks/",
"update_task": "PUT /tasks/{task_id}",
"delete_task": "DELETE /tasks/{task_id}"
}
}
# AUTHENTICATION ENDPOINTS
@app.post("/register", response_model=schemas.UserResponse, status_code=status.HTTP_201_CREATED, tags=["Auth"])
def register(user: schemas.UserCreate, db: Session = Depends(get_db)):
"""
Register a new user
- **username**: Must be unique, 3-50 characters
- **email**: Must be unique, valid email format
- **password**: Minimum 6 characters
Password is automatically hashed before storing!
"""
# Check if username already exists
db_user = db.query(models.User).filter(models.User.username == user.username).first()
if db_user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Username already registered"
)
# Check if email already exists
db_user = db.query(models.User).filter(models.User.email == user.email).first()
if db_user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Email already registered"
)
# Hash the password
hashed_password = auth.get_password_hash(user.password)
# Create new user
new_user = models.User(
username=user.username,
email=user.email,
hashed_password=hashed_password
)
db.add(new_user)
db.commit()
db.refresh(new_user)
return new_user
@app.post("/login", response_model=schemas.Token, tags=["Auth"])
def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
"""
Login to get access token
- **username**: Your username
- **password**: Your password
Returns a JWT token that expires in 30 minutes.
Use this token in the Authorization header for protected endpoints!
"""
# Find user by username
user = db.query(models.User).filter(models.User.username == form_data.username).first()
# Check if user exists and password is correct
if not user or not auth.verify_password(form_data.password, user.hashed_password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
# Create access token
access_token = auth.create_access_token(data={"sub": user.username})
return {"access_token": access_token, "token_type": "bearer"}
# USER ENDPOINTS t
@app.get("/users/me", response_model=schemas.UserResponse, tags=["Users"])
def get_current_user_info(current_user: models.User = Depends(auth.get_current_user)):
"""
Get current logged-in user's information
Protected endpoint - requires valid JWT token!
"""
return current_user
# ==================== TASK ENDPOINTS (ALL PROTECTED!) ====================
@app.post("/tasks/", response_model=schemas.TaskResponse, status_code=status.HTTP_201_CREATED, tags=["Tasks"])
def create_task(
task: schemas.TaskCreate,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(get_db)
):
"""
Create a new task (Protected - requires login!)
- **title**: Task title (required)
- **description**: Task description (optional)
- **status**: todo, in_progress, or done (default: todo)
- **priority**: low, medium, or high (default: medium)
Task is automatically assigned to the logged-in user!
"""
# Create new task with current user's ID
new_task = models.Task(
**task.model_dump(),
user_id=current_user.id # ← Automatically use logged-in user's ID!
)
db.add(new_task)
db.commit()
db.refresh(new_task)
return new_task
@app.get("/tasks/", response_model=List[schemas.TaskResponse], tags=["Tasks"])
def get_my_tasks(
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(get_db)
):
"""
Get all tasks for the current logged-in user (Protected!)
You can only see YOUR OWN tasks!
Other users' tasks are hidden from you.
"""
# Only return tasks belonging to current user
tasks = db.query(models.Task).filter(
models.Task.user_id == current_user.id
).all()
return tasks
@app.get("/tasks/{task_id}", response_model=schemas.TaskResponse, tags=["Tasks"])
def get_task(
task_id: int,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(get_db)
):
"""
Get a specific task by ID (Protected!)
You can only access YOUR OWN tasks!
"""
# Find task that belongs to current user
task = db.query(models.Task).filter(
models.Task.id == task_id,
models.Task.user_id == current_user.id # ← Security check!
).first()
if not task:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Task not found (or doesn't belong to you)"
)
return task
@app.put("/tasks/{task_id}", response_model=schemas.TaskResponse, tags=["Tasks"])
def update_task(
task_id: int,
task_update: schemas.TaskUpdate,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(get_db)
):
"""
Update a task (Protected!)
Only update the fields you provide - others remain unchanged.
You can only update YOUR OWN tasks!
"""
# Find task that belongs to current user
task = db.query(models.Task).filter(
models.Task.id == task_id,
models.Task.user_id == current_user.id # ← Security check!
).first()
if not task:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Task not found (or doesn't belong to you)"
)
# Update only provided fields
update_data = task_update.model_dump(exclude_unset=True)
for key, value in update_data.items():
setattr(task, key, value)
db.commit()
db.refresh(task)
return task
@app.delete("/tasks/{task_id}", status_code=status.HTTP_204_NO_CONTENT, tags=["Tasks"])
def delete_task(
task_id: int,
current_user: models.User = Depends(auth.get_current_user),
db: Session = Depends(get_db)
):
"""
Delete a task (Protected!)
You can only delete YOUR OWN tasks!
"""
# Find task that belongs to current user
task = db.query(models.Task).filter(
models.Task.id == task_id,
models.Task.user_id == current_user.id # ← Security check!
).first()
if not task:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Task not found (or doesn't belong to you)"
)
db.delete(task)
db.commit()
return None