|
2 | 2 | # ruff: noqa: B904 |
3 | 3 |
|
4 | 4 | import logging |
| 5 | +import uuid |
5 | 6 | from importlib.metadata import version |
6 | 7 |
|
7 | | -from fastapi import FastAPI, Request |
| 8 | +from fastapi import FastAPI, HTTPException, Request |
8 | 9 | from fastapi.middleware.cors import CORSMiddleware |
| 10 | +from pydantic import BaseModel |
9 | 11 | from strawberry.fastapi import GraphQLRouter |
10 | 12 |
|
| 13 | +from alphatrion.server.auth import ( |
| 14 | + create_access_token, |
| 15 | + decode_access_token, |
| 16 | + hash_password, |
| 17 | + verify_password, |
| 18 | +) |
11 | 19 | from alphatrion.server.graphql.context import get_context |
12 | 20 | from alphatrion.server.graphql.schema import schema |
| 21 | +from alphatrion.storage import runtime |
13 | 22 |
|
14 | 23 | # Configure logging |
15 | 24 | logger = logging.getLogger(__name__) |
@@ -117,3 +126,133 @@ def health_check(): |
117 | 126 | @app.get("/version") |
118 | 127 | def get_version(): |
119 | 128 | return {"version": version("alphatrion"), "status": "ok"} |
| 129 | + |
| 130 | + |
| 131 | +# Auth endpoints |
| 132 | +class LoginRequest(BaseModel): |
| 133 | + email: str |
| 134 | + password: str |
| 135 | + |
| 136 | + |
| 137 | +class LoginResponse(BaseModel): |
| 138 | + access_token: str |
| 139 | + token_type: str |
| 140 | + user: dict |
| 141 | + |
| 142 | + |
| 143 | +@app.post("/api/auth/login", response_model=LoginResponse) |
| 144 | +async def login(credentials: LoginRequest): |
| 145 | + """Authenticate user and return JWT token with user information.""" |
| 146 | + try: |
| 147 | + metadb = runtime.storage_runtime().metadb |
| 148 | + |
| 149 | + # Find user by email |
| 150 | + user = metadb.get_user_by_email(email=credentials.email) |
| 151 | + |
| 152 | + if not user: |
| 153 | + raise HTTPException(status_code=401, detail="Invalid email or password") |
| 154 | + |
| 155 | + # Verify password |
| 156 | + if not verify_password(credentials.password, user.password_hash): |
| 157 | + raise HTTPException(status_code=401, detail="Invalid email or password") |
| 158 | + |
| 159 | + # Get user's teams |
| 160 | + team_members = metadb.get_team_members_by_user_id(user_id=user.uuid) |
| 161 | + teams = [] |
| 162 | + for member in team_members: |
| 163 | + team = metadb.get_team(team_id=member.team_id) |
| 164 | + if team: |
| 165 | + teams.append( |
| 166 | + { |
| 167 | + "id": str(team.uuid), |
| 168 | + "name": team.name, |
| 169 | + "description": team.description, |
| 170 | + } |
| 171 | + ) |
| 172 | + |
| 173 | + # Create JWT token with user claims |
| 174 | + # Note: team_id is NOT included - users can belong to multiple teams |
| 175 | + # Team selection is handled in the UI |
| 176 | + token_data = { |
| 177 | + "sub": str(user.uuid), # subject = user_id |
| 178 | + "user_id": str(user.uuid), |
| 179 | + "org_id": str(user.org_id), |
| 180 | + "email": user.email, |
| 181 | + } |
| 182 | + |
| 183 | + access_token = create_access_token(data=token_data) |
| 184 | + |
| 185 | + # Return token and user info |
| 186 | + return { |
| 187 | + "access_token": access_token, |
| 188 | + "token_type": "bearer", |
| 189 | + "user": { |
| 190 | + "id": str(user.uuid), |
| 191 | + "name": user.name, |
| 192 | + "email": user.email, |
| 193 | + "avatarUrl": user.avatar_url, |
| 194 | + "meta": user.meta, |
| 195 | + "createdAt": user.created_at.isoformat(), |
| 196 | + "updatedAt": user.updated_at.isoformat(), |
| 197 | + "teams": teams, |
| 198 | + }, |
| 199 | + } |
| 200 | + |
| 201 | + except HTTPException: |
| 202 | + raise |
| 203 | + except Exception as e: |
| 204 | + logger.error(f"Login failed: {e}") |
| 205 | + raise HTTPException(status_code=500, detail="Internal server error") |
| 206 | + |
| 207 | + |
| 208 | +class ChangePasswordRequest(BaseModel): |
| 209 | + current_password: str |
| 210 | + new_password: str |
| 211 | + |
| 212 | + |
| 213 | +@app.post("/api/auth/change-password") |
| 214 | +async def change_password(request: Request, password_data: ChangePasswordRequest): |
| 215 | + """Change user's password.""" |
| 216 | + try: |
| 217 | + # Extract token from Authorization header |
| 218 | + auth_header = request.headers.get("Authorization") |
| 219 | + if not auth_header or not auth_header.startswith("Bearer "): |
| 220 | + raise HTTPException( |
| 221 | + status_code=401, detail="Missing or invalid authorization header" |
| 222 | + ) |
| 223 | + |
| 224 | + token = auth_header.replace("Bearer ", "") |
| 225 | + |
| 226 | + # Decode token to get user_id |
| 227 | + payload = decode_access_token(token) |
| 228 | + if not payload: |
| 229 | + raise HTTPException(status_code=401, detail="Invalid or expired token") |
| 230 | + |
| 231 | + user_id = payload.get("user_id") |
| 232 | + if not user_id: |
| 233 | + raise HTTPException(status_code=401, detail="Invalid token payload") |
| 234 | + |
| 235 | + metadb = runtime.storage_runtime().metadb |
| 236 | + |
| 237 | + # Get user from database |
| 238 | + user = metadb.get_user(user_id=uuid.UUID(user_id)) |
| 239 | + if not user: |
| 240 | + raise HTTPException(status_code=404, detail="User not found") |
| 241 | + |
| 242 | + # Verify current password |
| 243 | + if not verify_password(password_data.current_password, user.password_hash): |
| 244 | + raise HTTPException(status_code=401, detail="Current password is incorrect") |
| 245 | + |
| 246 | + # Hash new password |
| 247 | + new_password_hash = hash_password(password_data.new_password) |
| 248 | + |
| 249 | + # Update password in database |
| 250 | + metadb.update_user(user_id=uuid.UUID(user_id), password_hash=new_password_hash) |
| 251 | + |
| 252 | + return {"message": "Password changed successfully"} |
| 253 | + |
| 254 | + except HTTPException: |
| 255 | + raise |
| 256 | + except Exception as e: |
| 257 | + logger.error(f"Password change failed: {e}") |
| 258 | + raise HTTPException(status_code=500, detail="Internal server error") |
0 commit comments