Spaces:
Running
Running
Feat: Implement password change endpoint for already authenticated users
Browse files- backend/app/routes/auth.py +23 -2
backend/app/routes/auth.py
CHANGED
|
@@ -9,7 +9,7 @@ from sqlalchemy import select
|
|
| 9 |
from app.database import get_db
|
| 10 |
from app.models import User
|
| 11 |
from app.schemas import UserRegister, UserLogin, TokenResponse, UserResponse, RefreshRequest, UserUpdate, \
|
| 12 |
-
UserUpdateResponse
|
| 13 |
from app.auth import hash_password, verify_password, create_access_token, create_refresh_token, get_current_user, decode_token
|
| 14 |
|
| 15 |
router = APIRouter(prefix="/auth", tags=["Authentication"])
|
|
@@ -138,4 +138,25 @@ def update_user_info(payload:UserUpdate,
|
|
| 138 |
|
| 139 |
raise HTTPException(status_code=400, detail="Database error")
|
| 140 |
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
from app.database import get_db
|
| 10 |
from app.models import User
|
| 11 |
from app.schemas import UserRegister, UserLogin, TokenResponse, UserResponse, RefreshRequest, UserUpdate, \
|
| 12 |
+
UserUpdateResponse, UpdatePassword, UpdatePasswordResponse
|
| 13 |
from app.auth import hash_password, verify_password, create_access_token, create_refresh_token, get_current_user, decode_token
|
| 14 |
|
| 15 |
router = APIRouter(prefix="/auth", tags=["Authentication"])
|
|
|
|
| 138 |
|
| 139 |
raise HTTPException(status_code=400, detail="Database error")
|
| 140 |
|
| 141 |
+
@router.put("/password")
|
| 142 |
+
def update_password(payload:UpdatePassword,
|
| 143 |
+
user: User = Depends(get_current_user),
|
| 144 |
+
db: Session = Depends(get_db))-> UpdatePasswordResponse:
|
| 145 |
+
"""Update user password."""
|
| 146 |
+
if not payload.password and not payload.confirm_password:
|
| 147 |
+
raise HTTPException(status_code=400, detail="Password and confirm_password are required")
|
| 148 |
+
if len(payload.password) == 0 and len(payload.confirm_password) == 0:
|
| 149 |
+
raise HTTPException(status_code=400, detail="Password and confirm_password are required")
|
| 150 |
+
if payload.password != payload.confirm_password:
|
| 151 |
+
raise HTTPException(status_code=400, detail="Password and confirm_password are different")
|
| 152 |
+
try:
|
| 153 |
+
hashed_password = hash_password(payload.password)
|
| 154 |
+
user.hashed_password = hashed_password
|
| 155 |
+
db.commit()
|
| 156 |
+
db.refresh(user)
|
| 157 |
+
return user
|
| 158 |
+
except HTTPException:
|
| 159 |
+
raise
|
| 160 |
+
except SQLAlchemyError:
|
| 161 |
+
db.rollback()
|
| 162 |
+
raise HTTPException(status_code=400, detail="Database error")
|