File size: 6,585 Bytes
12ccf36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d2dad3
 
 
 
 
87b35fd
12ccf36
7ffe51d
 
687894b
 
9d2dad3
687894b
7ffe51d
9d2dad3
87b35fd
9d2dad3
 
0ff84fe
 
 
 
 
687894b
9d2dad3
7ffe51d
87b35fd
7ffe51d
87b35fd
 
12ccf36
87b35fd
7ffe51d
 
12ccf36
9d2dad3
87b35fd
9d2dad3
87b35fd
7ffe51d
 
9d2dad3
 
ae8175d
9d2dad3
dcd08d5
ae8175d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ff84fe
 
 
9d2dad3
 
 
 
 
 
 
 
 
 
 
7ffe51d
 
 
 
 
 
12ccf36
7ffe51d
 
 
 
 
 
 
 
 
 
12ccf36
7ffe51d
9d2dad3
7ffe51d
9d2dad3
 
 
 
 
7ffe51d
9d2dad3
7ffe51d
9d2dad3
 
 
 
7ffe51d
9d2dad3
 
 
 
687894b
0ff84fe
9d2dad3
 
 
687894b
 
 
 
 
9d2dad3
687894b
 
706bb54
687894b
706bb54
 
 
 
 
 
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
# """Security utilities for authentication and authorization."""
# import jwt
# from datetime import datetime, timedelta
# from passlib.context import CryptContext
# from fastapi import HTTPException, status
# from typing import Optional

# # Password hashing context
# pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


# def hash_password(password: str) -> str:
#     if len(password.encode("utf-8")) > 72:
#         raise HTTPException(
#             status_code=status.HTTP_400_BAD_REQUEST,
#             detail="Password must be at most 72 characters"
#         )
#     return pwd_context.hash(password)


# def verify_password(plain_password: str, hashed_password: str) -> bool:
#     """
#     Verify a password against its hash.

#     Args:
#         plain_password: Plain text password to verify
#         hashed_password: Hashed password to compare against

#     Returns:
#         True if password matches, False otherwise
#     """
#     return pwd_context.verify(plain_password, hashed_password)


# def create_jwt_token(user_id: int, email: str, secret: str, expiration_days: int = 7) -> str:
#     """
#     Create a JWT token for a user.

#     Args:
#         user_id: User's unique identifier
#         email: User's email address
#         secret: Secret key for signing the token
#         expiration_days: Number of days until token expires (default: 7)

#     Returns:
#         Encoded JWT token string
#     """
#     now = datetime.utcnow()
#     payload = {
#         "sub": str(user_id),
#         "email": email,
#         "iat": now,
#         "exp": now + timedelta(days=expiration_days),
#         "iss": "better-auth"
#     }
#     return jwt.encode(payload, secret, algorithm="HS256")


# def verify_jwt_token(token: str, secret: str) -> dict:
#     """
#     Verify and decode a JWT token.

#     Args:
#         token: JWT token string to verify
#         secret: Secret key used to sign the token

#     Returns:
#         Decoded token payload as dictionary

#     Raises:
#         HTTPException: 401 if token is expired or invalid
#     """
#     try:
#         payload = jwt.decode(
#             token,
#             secret,
#             algorithms=["HS256"],
#             options={
#                 "verify_signature": True,
#                 "verify_exp": True,
#                 "require": ["sub", "email", "iat", "exp", "iss"]
#             }
#         )

#         # Validate issuer
#         if payload.get("iss") != "better-auth":
#             raise HTTPException(
#                 status_code=status.HTTP_401_UNAUTHORIZED,
#                 detail="Invalid token issuer",
#                 headers={"WWW-Authenticate": "Bearer"}
#             )

#         return payload

#     except jwt.ExpiredSignatureError:
#         raise HTTPException(
#             status_code=status.HTTP_401_UNAUTHORIZED,
#             detail="Token has expired",
#             headers={"WWW-Authenticate": "Bearer"}
#         )
#     except jwt.InvalidTokenError:
#         raise HTTPException(
#             status_code=status.HTTP_401_UNAUTHORIZED,
#             detail="Invalid token",
#             headers={"WWW-Authenticate": "Bearer"}
#         )
"""
Security utilities for authentication and authorization.
"""
from datetime import datetime, timedelta
from typing import Dict, Any
import hashlib

import jwt
from passlib.context import CryptContext
from fastapi import HTTPException, status, Depends
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

from src.core.config import settings

# =========================
# Password hashing (bcrypt-safe FINAL)
# =========================

pwd_context = CryptContext(
    schemes=["bcrypt"],
    deprecated="auto"
)

security = HTTPBearer()


def _normalize_password(password: str) -> bytes:
    """
    Convert password to fixed-length digest.
    This COMPLETELY avoids bcrypt 72-byte crashes.
    """
    return hashlib.sha256(password.encode("utf-8")).digest()


def hash_password(password: str) -> str:
    """
    Hash password safely (SHA256 → bcrypt).
    """
    return pwd_context.hash(_normalize_password(password))


def verify_password(plain_password: str, hashed_password: str) -> bool:
    """
    Verify password with AUTO migration from legacy hashes.
    """
    try:
        # New method (SHA256 → bcrypt)
        normalized = hashlib.sha256(
            plain_password.encode("utf-8")
        ).digest()

        if pwd_context.verify(normalized, hashed_password):
            return True

    except Exception:
        pass

    # 🔁 Legacy fallback (OLD system)
    try:
        legacy = hashlib.sha256(
            plain_password.encode("utf-8")
        ).hexdigest()

        return pwd_context.verify(legacy, hashed_password)

    except Exception:
        return False


# =========================
# JWT utilities
# =========================

def create_jwt_token(
    user_id: int,
    email: str,
    secret: str,
    expiration_days: int = 7
) -> str:
    now = datetime.utcnow()
    payload = {
        "sub": str(user_id),
        "email": email,
        "iat": now,
        "exp": now + timedelta(days=expiration_days),
        "iss": "better-auth",
    }
    return jwt.encode(payload, secret, algorithm="HS256")


def verify_jwt_token(token: str, secret: str) -> dict:
    try:
        payload = jwt.decode(
            token,
            secret,
            algorithms=["HS256"],
            options={"verify_exp": True},
        )

        if payload.get("iss") != "better-auth":
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Invalid token issuer"
            )

        return payload

    except jwt.ExpiredSignatureError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Token expired"
        )
    except jwt.InvalidTokenError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid token"
        )


# =========================
# FastAPI dependency
# =========================

def get_current_user(
    credentials: HTTPAuthorizationCredentials = Depends(security)
) -> Dict[str, Any]:
    """
    Extract and validate JWT token from Authorization header.
    """
    token = credentials.credentials
    payload = verify_jwt_token(token, settings.BETTER_AUTH_SECRET)

    return {
        "id": int(payload["sub"]),
        "email": payload.get("email"),
        "iat": payload.get("iat"),
        "exp": payload.get("exp"),
    }