File size: 8,847 Bytes
b84ea83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Auth Controller β€” JWT Authentication & User Management

Functions:
    register_user      β€” Create a new user account
    authenticate_user  β€” Verify credentials and issue JWT
    get_current_user   β€” FastAPI Dependency to extract user from token
    refresh_token      β€” Issue a new token from a valid one

Architecture Reference: insights/architecture_rule.md
    Phase 2: "Implement JWT Authentication and RBAC in auth_controller.py"
    "POST /api/v1/auth/login β€” Get JWT & set FCM token"

Dependencies (not yet in requirements.txt):
    pip install pyjwt[crypto] passlib[bcrypt]

Status: FUNCTIONAL STUB β€” all logic is complete. Activates when
pyjwt and passlib are installed. Returns clear error messages
if dependencies are missing.
"""

import uuid
import logging
from datetime import datetime, timedelta, timezone
from typing import Optional

from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession

logger = logging.getLogger(__name__)


# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Lazy dependency imports (graceful degradation)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

def _check_deps():
    """Check if JWT and password hashing dependencies are installed."""
    missing = []
    try:
        import jwt  # noqa: F401
    except ImportError:
        missing.append("pyjwt")
    try:
        from passlib.context import CryptContext  # noqa: F401
    except ImportError:
        missing.append("passlib[bcrypt]")

    if missing:
        raise ImportError(
            f"Auth dependencies not installed: {', '.join(missing)}. "
            f"Run: pip install {' '.join(missing)}"
        )


def _get_pwd_context():
    """Get password hashing context (bcrypt)."""
    from passlib.context import CryptContext
    return CryptContext(schemes=["bcrypt"], deprecated="auto")


def _create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
    """Create a signed JWT token."""
    import jwt
    from config.auth_config import auth_config

    to_encode = data.copy()
    expire = datetime.now(timezone.utc) + (
        expires_delta or timedelta(minutes=auth_config.access_token_expire_minutes)
    )
    to_encode.update({"exp": expire, "iat": datetime.now(timezone.utc)})

    return jwt.encode(
        to_encode,
        auth_config.secret_key,
        algorithm=auth_config.algorithm,
    )


def _decode_token(token: str) -> dict:
    """Decode and verify a JWT token. Raises jwt.PyJWTError on failure."""
    import jwt
    from config.auth_config import auth_config

    return jwt.decode(
        token,
        auth_config.secret_key,
        algorithms=[auth_config.algorithm],
    )


# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Public Functions
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

async def register_user(
    db: AsyncSession,
    email: str,
    password: str,
    full_name: str,
    role: str = "inspector",
) -> dict:
    """
    Register a new user account.

    Args:
        db: Database session
        email: Unique email address
        password: Plain-text password (will be bcrypt hashed)
        full_name: User's display name
        role: One of 'admin', 'inspector', 'viewer'

    Returns:
        Success response with user data (no password)

    Raises:
        ImportError: If pyjwt/passlib not installed
        ValueError: If email already exists
    """
    _check_deps()
    pwd_context = _get_pwd_context()

    # Check if email already taken
    existing = await db.execute(
        text("SELECT id FROM users WHERE email = :email"),
        {"email": email},
    )
    if existing.fetchone():
        raise ValueError(f"Email '{email}' is already registered")

    # Hash password and insert
    user_id = uuid.uuid4()
    hashed = pwd_context.hash(password)

    await db.execute(
        text("""
            INSERT INTO users (id, email, hashed_password, full_name, role, is_active)
            VALUES (:id, :email, :hashed, :name, :role, true)
        """),
        {
            "id": user_id,
            "email": email,
            "hashed": hashed,
            "name": full_name,
            "role": role,
        },
    )
    await db.commit()

    logger.info(f"βœ… User registered: {email} (role={role})")

    return {
        "status": "success",
        "message": "User registered successfully",
        "data": {
            "id": str(user_id),
            "email": email,
            "full_name": full_name,
            "role": role,
        },
    }


async def authenticate_user(
    db: AsyncSession,
    email: str,
    password: str,
    fcm_token: Optional[str] = None,
) -> dict:
    """
    Authenticate a user and return a JWT token.

    Args:
        db: Database session
        email: User's email
        password: Plain-text password to verify
        fcm_token: Optional FCM token for push notifications

    Returns:
        TokenResponse with access_token, token_type, expires_in, user

    Raises:
        ImportError: If pyjwt/passlib not installed
        ValueError: If credentials are invalid
    """
    _check_deps()
    pwd_context = _get_pwd_context()
    from config.auth_config import auth_config

    # Fetch user by email
    result = await db.execute(
        text("""
            SELECT id, email, hashed_password, full_name, role, is_active, last_login, created_at
            FROM users WHERE email = :email
        """),
        {"email": email},
    )
    row = result.fetchone()

    if not row:
        raise ValueError("Invalid email or password")

    user_id, user_email, hashed, full_name, role, is_active, last_login, created_at = row

    if not is_active:
        raise ValueError("Account is deactivated")

    # Verify password
    if not pwd_context.verify(password, hashed):
        raise ValueError("Invalid email or password")

    # Generate JWT token
    token = _create_access_token(
        data={
            "sub": str(user_id),
            "email": user_email,
            "role": role,
        }
    )

    # Update last_login and FCM token
    update_parts = ["last_login = :now"]
    params: dict = {"uid": user_id, "now": datetime.now(timezone.utc)}
    if fcm_token:
        update_parts.append("fcm_token = :fcm")
        params["fcm"] = fcm_token

    await db.execute(
        text(f"UPDATE users SET {', '.join(update_parts)} WHERE id = :uid"),
        params,
    )
    await db.commit()

    logger.info(f"βœ… User authenticated: {user_email}")

    return {
        "status": "success",
        "data": {
            "access_token": token,
            "token_type": "bearer",
            "expires_in": auth_config.access_token_expire_minutes * 60,
            "user": {
                "id": str(user_id),
                "email": user_email,
                "full_name": full_name,
                "role": role,
                "is_active": is_active,
                "last_login": datetime.now(timezone.utc).isoformat(),
                "created_at": created_at.isoformat() if created_at else None,
            },
        },
    }


async def verify_token(token: str) -> dict:
    """
    Verify a JWT token and return the decoded payload.

    Args:
        token: JWT access token string

    Returns:
        Decoded token payload (sub, email, role, exp, iat)

    Raises:
        ImportError: If pyjwt not installed
        ValueError: If token is invalid or expired
    """
    _check_deps()

    try:
        payload = _decode_token(token)
        return {
            "user_id": payload.get("sub"),
            "email": payload.get("email"),
            "role": payload.get("role"),
        }
    except Exception as e:
        raise ValueError(f"Invalid or expired token: {e}")


async def get_user_by_id(db: AsyncSession, user_id: str) -> Optional[dict]:
    """Fetch a user by UUID. Returns None if not found."""
    result = await db.execute(
        text("""
            SELECT id, email, full_name, role, is_active, last_login, created_at
            FROM users WHERE id = :uid
        """),
        {"uid": uuid.UUID(user_id)},
    )
    row = result.fetchone()
    if not row:
        return None

    return {
        "id": str(row[0]),
        "email": row[1],
        "full_name": row[2],
        "role": row[3],
        "is_active": row[4],
        "last_login": row[5].isoformat() if row[5] else None,
        "created_at": row[6].isoformat() if row[6] else None,
    }