File size: 10,730 Bytes
84c328d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
"""Authentication API endpoints.

[Task]: T017
[From]: specs/001-user-auth/contracts/openapi.yaml, specs/001-user-auth/plan.md
"""
import re
from typing import Optional
from datetime import datetime, timedelta

from fastapi import APIRouter, Depends, HTTPException, status, Cookie
from fastapi.responses import JSONResponse, Response
from sqlmodel import Session, select

from models.user import User, UserCreate, UserRead, UserLogin
from core.database import get_session
from core.security import get_password_hash, verify_password, create_access_token, decode_access_token
from core.config import get_settings
from api.deps import get_current_user

settings = get_settings()

router = APIRouter(prefix="/api/auth", tags=["Authentication"])


def validate_email_format(email: str) -> bool:
    """Validate email format.

    Check for @ symbol and domain part.

    [Task]: T019
    [From]: specs/001-user-auth/spec.md

    Args:
        email: Email address to validate

    Returns:
        True if email format is valid, False otherwise
    """
    if not email:
        return False

    # Basic email validation: must contain @ and at least one . after @
    pattern = r'^[^@]+@[^@]+\.[^@]+$'
    return re.match(pattern, email) is not None


def validate_password(password: str) -> bool:
    """Validate password length.

    Minimum 8 characters.

    [Task]: T020
    [From]: specs/001-user-auth/spec.md

    Args:
        password: Password to validate

    Returns:
        True if password meets requirements, False otherwise
    """
    return len(password) >= 8


@router.post("/sign-up", response_model=dict, status_code=status.HTTP_200_OK)
async def sign_up(
    user_data: UserCreate,
    session: Session = Depends(get_session)
):
    """Register a new user account.

    Validates email format and password length, checks email uniqueness,
    hashes password with bcrypt, creates user in database.

    [Task]: T018
    [From]: specs/001-user-auth/contracts/openapi.yaml

    Args:
        user_data: User registration data (email, password)
        session: Database session

    Returns:
        Success response with message and user data

    Raises:
        HTTPException 400: Invalid email format or password too short
        HTTPException 409: Email already registered
        HTTPException 500: Database error
    """
    # Validate email format
    if not validate_email_format(user_data.email):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Invalid email format"
        )

    # Validate password length
    if not validate_password(user_data.password):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Password must be at least 8 characters"
        )

    # Check if email already exists
    existing_user = session.exec(
        select(User).where(User.email == user_data.email)
    ).first()
    if existing_user:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="Email already registered"
        )

    # Hash password with bcrypt
    hashed_password = get_password_hash(user_data.password)

    # Create user
    user = User(
        email=user_data.email,
        hashed_password=hashed_password
    )

    try:
        session.add(user)
        session.commit()
        session.refresh(user)
    except Exception as e:
        session.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to create user account"
        )

    # Return user data (excluding password)
    user_dict = UserRead.model_validate(user).model_dump(mode='json')
    return {
        "success": True,
        "message": "Account created successfully",
        "user": user_dict
    }


def get_user_by_email(email: str, session: Session) -> Optional[User]:
    """Query database for user by email.

    [Task]: T030
    [From]: specs/001-user-auth/plan.md

    Args:
        email: User email address
        session: Database session

    Returns:
        User object if found, None otherwise
    """
    return session.exec(select(User).where(User.email == email)).first()


@router.post("/sign-in", response_model=dict, status_code=status.HTTP_200_OK)
async def sign_in(
    user_data: UserLogin,
    session: Session = Depends(get_session)
):
    """Authenticate user and generate JWT token.

    Verifies credentials, generates JWT token, sets httpOnly cookie,
    returns token and user data.

    [Task]: T027
    [From]: specs/001-user-auth/contracts/openapi.yaml

    Args:
        user_data: User login credentials (email, password)
        session: Database session

    Returns:
        Login response with JWT token, user data, and expiration time

    Raises:
        HTTPException 401: Invalid credentials
        HTTPException 500: Database or JWT generation error
    """
    # Get user by email
    user = get_user_by_email(user_data.email, session)
    if not user:
        # Generic error message (don't reveal if email exists)
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid email or password"
        )

    # Verify password
    if not verify_password(user_data.password, user.hashed_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid email or password"
        )

    # Generate JWT token
    access_token = create_access_token(
        data={"sub": str(user.id)},
        expires_delta=timedelta(days=settings.jwt_expiration_days)
    )

    # Calculate expiration time
    expires_at = datetime.utcnow() + timedelta(days=settings.jwt_expiration_days)

    # Create response
    response_data = {
        "success": True,
        "token": access_token,
        "user": UserRead.model_validate(user).model_dump(mode='json'),
        "expires_at": expires_at.isoformat() + "Z"
    }

    # Create response with httpOnly cookie
    response = JSONResponse(content=response_data)

    # Set httpOnly cookie with JWT token
    response.set_cookie(
        key="auth_token",
        value=access_token,
        httponly=True,
        secure=settings.environment == "production",  # Only send over HTTPS in production
        samesite="lax",  # CSRF protection
        max_age=settings.jwt_expiration_days * 24 * 60 * 60,  # Convert days to seconds
        path="/"
    )

    return response


@router.get("/session", response_model=dict, status_code=status.HTTP_200_OK)
async def get_session(
    response: Response,
    Authorization: Optional[str] = None,
    auth_token: Optional[str] = Cookie(None),
    session: Session = Depends(get_session)
):
    """Verify JWT token and return user session data.

    Checks JWT token from Authorization header or httpOnly cookie,
    verifies signature, returns user data if authenticated.

    [Task]: T026
    [From]: specs/001-user-auth/contracts/openapi.yaml

    Args:
        response: FastAPI response object
        Authorization: Bearer token from Authorization header
        auth_token: JWT token from httpOnly cookie
        session: Database session

    Returns:
        Session response with authentication status and user data

    Raises:
        HTTPException 401: Invalid, expired, or missing token
    """
    # Extract token from Authorization header or cookie
    token = None

    # Try Authorization header first
    if Authorization:
        try:
            scheme, header_token = Authorization.split()
            if scheme.lower() == "bearer":
                token = header_token
        except ValueError:
            pass  # Fall through to cookie

    # If no token in header, try cookie
    if not token and auth_token:
        token = auth_token

    if not token:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Not authenticated"
        )

    try:
        # Decode and verify token
        payload = decode_access_token(token)
        user_id = payload.get("sub")

        if not user_id:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Invalid token: user_id missing"
            )

        # Query user from database
        user = session.get(User, user_id)
        if not user:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="User not found"
            )

        # Calculate expiration time
        exp = payload.get("exp")
        expires_at = None
        if exp:
            expires_at = datetime.fromtimestamp(exp).isoformat() + "Z"

        return {
            "authenticated": True,
            "user": UserRead.model_validate(user).model_dump(mode='json'),
            "expires_at": expires_at
        }

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Could not validate credentials"
        )


@router.get("/users/me")
async def get_users_me(
    current_user: User = Depends(get_current_user)
):
    """Get current authenticated user information.

    Example protected endpoint that requires JWT authentication.
    Returns user data for authenticated user.

    [Task]: T038
    [From]: specs/001-user-auth/plan.md

    Args:
        current_user: Authenticated user from dependency

    Returns:
        User data for current user

    Raises:
        HTTPException 401: If not authenticated
    """
    return UserRead.model_validate(current_user).model_dump(mode='json')


@router.post("/sign-out", status_code=status.HTTP_200_OK)
async def sign_out(
    response: Response,
    current_user: User = Depends(get_current_user)
):
    """Logout current user.

    Client-side logout (clears httpOnly cookie).
    Server-side token is stateless (JWT), so no server storage to clear.

    [Task]: T043
    [From]: specs/001-user-auth/contracts/openapi.yaml

    Args:
        response: FastAPI response object
        current_user: Authenticated user (for validation only)

    Returns:
        Success message

    Raises:
        HTTPException 401: If not authenticated
    """
    # Create response with success message
    response_data = {
        "success": True,
        "message": "Logged out successfully"
    }

    # Create response with cleared httpOnly cookie
    response_obj = JSONResponse(content=response_data)

    # Clear the httpOnly cookie by setting it to expire
    response_obj.delete_cookie(
        key="auth_token",
        path="/",
        samesite="lax"
    )

    return response_obj