|
| 1 | +""" |
| 2 | +Authentication module for Comps. |
| 3 | +Handles user authentication, invitation codes, and session management. |
| 4 | +""" |
| 5 | +import hashlib |
| 6 | +import secrets |
| 7 | +import sqlite3 |
| 8 | +import time |
| 9 | +from typing import Optional, Dict, Any |
| 10 | +from fastapi import Request, HTTPException, Depends, Cookie |
| 11 | +from fastapi.security import APIKeyCookie |
| 12 | +from jose import JWTError, jwt |
| 13 | +from datetime import datetime, timedelta |
| 14 | + |
| 15 | +# Constants |
| 16 | +DB_PATH = 'comparisons.db' |
| 17 | +SECRET_KEY = secrets.token_hex(32) # Generate a random secret key |
| 18 | +ALGORITHM = "HS256" |
| 19 | +ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 1 week |
| 20 | + |
| 21 | +# Cookie security |
| 22 | +cookie_sec = APIKeyCookie(name="session") |
| 23 | + |
| 24 | +def hash_invitation_code(code: str) -> str: |
| 25 | + """Hash an invitation code for secure storage""" |
| 26 | + return hashlib.sha256(code.encode()).hexdigest() |
| 27 | + |
| 28 | +def create_invitation_code(created_by_id: int) -> str: |
| 29 | + """Create a new invitation code""" |
| 30 | + # Generate a random code |
| 31 | + code = secrets.token_urlsafe(16) |
| 32 | + |
| 33 | + conn = sqlite3.connect(DB_PATH) |
| 34 | + c = conn.cursor() |
| 35 | + |
| 36 | + # Store the code |
| 37 | + c.execute( |
| 38 | + 'INSERT INTO invitation_codes (code, created_by) VALUES (?, ?)', |
| 39 | + (code, created_by_id) |
| 40 | + ) |
| 41 | + |
| 42 | + conn.commit() |
| 43 | + conn.close() |
| 44 | + |
| 45 | + return code |
| 46 | + |
| 47 | +def verify_invitation_code(code: str) -> bool: |
| 48 | + """Verify if an invitation code is valid and unused""" |
| 49 | + conn = sqlite3.connect(DB_PATH) |
| 50 | + c = conn.cursor() |
| 51 | + |
| 52 | + c.execute('SELECT is_used FROM invitation_codes WHERE code = ?', (code,)) |
| 53 | + result = c.fetchone() |
| 54 | + |
| 55 | + conn.close() |
| 56 | + |
| 57 | + # Code is valid if it exists and is not used |
| 58 | + return result is not None and not result[0] |
| 59 | + |
| 60 | +def register_user(username: str, invitation_code: str) -> Optional[Dict[str, Any]]: |
| 61 | + """Register a new user with an invitation code""" |
| 62 | + if not verify_invitation_code(invitation_code): |
| 63 | + return None |
| 64 | + |
| 65 | + # Hash the invitation code for storage |
| 66 | + code_hash = hash_invitation_code(invitation_code) |
| 67 | + |
| 68 | + conn = sqlite3.connect(DB_PATH) |
| 69 | + c = conn.cursor() |
| 70 | + |
| 71 | + try: |
| 72 | + # Check if username already exists |
| 73 | + c.execute('SELECT id FROM users WHERE username = ?', (username,)) |
| 74 | + if c.fetchone(): |
| 75 | + conn.close() |
| 76 | + return None |
| 77 | + |
| 78 | + # Create the user |
| 79 | + c.execute( |
| 80 | + 'INSERT INTO users (username, invitation_code_hash, never_expire_comparisons) VALUES (?, ?, ?)', |
| 81 | + (username, code_hash, 1) # All invited users get permanent comparisons |
| 82 | + ) |
| 83 | + user_id = c.lastrowid |
| 84 | + |
| 85 | + # Mark the invitation code as used |
| 86 | + c.execute( |
| 87 | + 'UPDATE invitation_codes SET is_used = 1, used_by = ? WHERE code = ?', |
| 88 | + (user_id, invitation_code) |
| 89 | + ) |
| 90 | + |
| 91 | + # Get the user data |
| 92 | + c.execute('SELECT id, username, is_admin, never_expire_comparisons FROM users WHERE id = ?', (user_id,)) |
| 93 | + user = c.fetchone() |
| 94 | + |
| 95 | + conn.commit() |
| 96 | + |
| 97 | + if user: |
| 98 | + return { |
| 99 | + "id": user[0], |
| 100 | + "username": user[1], |
| 101 | + "is_admin": bool(user[2]), |
| 102 | + "never_expire_comparisons": bool(user[3]) |
| 103 | + } |
| 104 | + return None |
| 105 | + except Exception as e: |
| 106 | + print(f"Error registering user: {e}") |
| 107 | + conn.rollback() |
| 108 | + return None |
| 109 | + finally: |
| 110 | + conn.close() |
| 111 | + |
| 112 | +def authenticate_user(username: str, invitation_code: str) -> Optional[Dict[str, Any]]: |
| 113 | + """Authenticate a user with their username and invitation code""" |
| 114 | + # Hash the invitation code for comparison |
| 115 | + code_hash = hash_invitation_code(invitation_code) |
| 116 | + |
| 117 | + conn = sqlite3.connect(DB_PATH) |
| 118 | + c = conn.cursor() |
| 119 | + |
| 120 | + c.execute( |
| 121 | + 'SELECT id, username, is_admin, never_expire_comparisons FROM users WHERE username = ? AND invitation_code_hash = ?', |
| 122 | + (username, code_hash) |
| 123 | + ) |
| 124 | + user = c.fetchone() |
| 125 | + |
| 126 | + conn.close() |
| 127 | + |
| 128 | + if user: |
| 129 | + return { |
| 130 | + "id": user[0], |
| 131 | + "username": user[1], |
| 132 | + "is_admin": bool(user[2]), |
| 133 | + "never_expire_comparisons": bool(user[3]) |
| 134 | + } |
| 135 | + return None |
| 136 | + |
| 137 | +def create_access_token(data: dict) -> str: |
| 138 | + """Create a JWT access token""" |
| 139 | + to_encode = data.copy() |
| 140 | + expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) |
| 141 | + to_encode.update({"exp": expire}) |
| 142 | + encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) |
| 143 | + return encoded_jwt |
| 144 | + |
| 145 | +def get_current_user(session: str = Depends(cookie_sec)) -> Optional[Dict[str, Any]]: |
| 146 | + """Get the current user from the session cookie""" |
| 147 | + try: |
| 148 | + payload = jwt.decode(session, SECRET_KEY, algorithms=[ALGORITHM]) |
| 149 | + user_id = payload.get("sub") |
| 150 | + if user_id is None: |
| 151 | + return None |
| 152 | + |
| 153 | + conn = sqlite3.connect(DB_PATH) |
| 154 | + c = conn.cursor() |
| 155 | + |
| 156 | + c.execute( |
| 157 | + 'SELECT id, username, is_admin, never_expire_comparisons FROM users WHERE id = ?', |
| 158 | + (user_id,) |
| 159 | + ) |
| 160 | + user = c.fetchone() |
| 161 | + |
| 162 | + conn.close() |
| 163 | + |
| 164 | + if user: |
| 165 | + return { |
| 166 | + "id": user[0], |
| 167 | + "username": user[1], |
| 168 | + "is_admin": bool(user[2]), |
| 169 | + "never_expire_comparisons": bool(user[3]) |
| 170 | + } |
| 171 | + return None |
| 172 | + except JWTError: |
| 173 | + return None |
| 174 | + except Exception as e: |
| 175 | + print(f"Error getting current user: {e}") |
| 176 | + return None |
| 177 | + |
| 178 | +def get_user_invitation_codes(user_id: int) -> list: |
| 179 | + """Get all invitation codes created by a user""" |
| 180 | + conn = sqlite3.connect(DB_PATH) |
| 181 | + c = conn.cursor() |
| 182 | + |
| 183 | + c.execute(''' |
| 184 | + SELECT ic.code, ic.is_used, u.username, ic.created_at |
| 185 | + FROM invitation_codes ic |
| 186 | + LEFT JOIN users u ON ic.used_by = u.id |
| 187 | + WHERE ic.created_by = ? |
| 188 | + ORDER BY ic.created_at DESC |
| 189 | + ''', (user_id,)) |
| 190 | + |
| 191 | + codes = [] |
| 192 | + for code, is_used, used_by, created_at in c.fetchall(): |
| 193 | + codes.append({ |
| 194 | + "code": code, |
| 195 | + "is_used": bool(is_used), |
| 196 | + "used_by": used_by, |
| 197 | + "created_at": created_at |
| 198 | + }) |
| 199 | + |
| 200 | + conn.close() |
| 201 | + return codes |
| 202 | + |
| 203 | +def is_admin(user: dict) -> bool: |
| 204 | + """Check if a user is an admin""" |
| 205 | + return user and user.get("is_admin", False) |
| 206 | + |
| 207 | +async def get_optional_user(request: Request) -> Optional[Dict[str, Any]]: |
| 208 | + """Get the current user if logged in, otherwise return None""" |
| 209 | + session = request.cookies.get("session") |
| 210 | + if not session: |
| 211 | + return None |
| 212 | + |
| 213 | + try: |
| 214 | + payload = jwt.decode(session, SECRET_KEY, algorithms=[ALGORITHM]) |
| 215 | + user_id = payload.get("sub") |
| 216 | + if user_id is None: |
| 217 | + return None |
| 218 | + |
| 219 | + conn = sqlite3.connect(DB_PATH) |
| 220 | + c = conn.cursor() |
| 221 | + |
| 222 | + c.execute( |
| 223 | + 'SELECT id, username, is_admin, never_expire_comparisons FROM users WHERE id = ?', |
| 224 | + (user_id,) |
| 225 | + ) |
| 226 | + user = c.fetchone() |
| 227 | + |
| 228 | + conn.close() |
| 229 | + |
| 230 | + if user: |
| 231 | + return { |
| 232 | + "id": user[0], |
| 233 | + "username": user[1], |
| 234 | + "is_admin": bool(user[2]), |
| 235 | + "never_expire_comparisons": bool(user[3]) |
| 236 | + } |
| 237 | + return None |
| 238 | + except JWTError: |
| 239 | + return None |
| 240 | + except Exception as e: |
| 241 | + print(f"Error getting optional user: {e}") |
| 242 | + return None |
0 commit comments