kamau1 commited on
Commit
57a7a21
·
verified ·
1 Parent(s): d4b70b5

Upload 12 files

Browse files
Files changed (2) hide show
  1. app/api/routes/auth_router.py +65 -5
  2. main.py +85 -1
app/api/routes/auth_router.py CHANGED
@@ -18,12 +18,14 @@ logger = logging.getLogger("auth-server")
18
  router = APIRouter()
19
 
20
  # Password hashing
 
21
  pwd_context = CryptContext(
22
  schemes=["argon2"],
23
- argon2__time_cost=4,
24
- argon2__memory_cost=102400,
25
- argon2__parallelism=8,
26
- argon2__salt_len=16
 
27
  )
28
 
29
  # JWT settings
@@ -165,8 +167,66 @@ async def register(request: Request, user: UserCreate):
165
  # Step 2: Hash the password
166
  logger.info(f"[{registration_id}] Hashing password")
167
  try:
 
168
  hashed_password = get_password_hash(user.password)
169
- logger.info(f"[{registration_id}] Password hashed successfully")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  except Exception as e:
171
  logger.error(f"[{registration_id}] Error hashing password: {str(e)}")
172
  raise HTTPException(
 
18
  router = APIRouter()
19
 
20
  # Password hashing
21
+ # Using a fixed configuration to ensure consistent hash lengths
22
  pwd_context = CryptContext(
23
  schemes=["argon2"],
24
+ argon2__time_cost=3,
25
+ argon2__memory_cost=65536,
26
+ argon2__parallelism=4,
27
+ argon2__salt_len=16,
28
+ argon2__hash_len=32
29
  )
30
 
31
  # JWT settings
 
167
  # Step 2: Hash the password
168
  logger.info(f"[{registration_id}] Hashing password")
169
  try:
170
+ # Use a fixed configuration to ensure consistent hash length
171
  hashed_password = get_password_hash(user.password)
172
+ logger.info(f"[{registration_id}] Password hashed successfully, length: {len(hashed_password)}")
173
+
174
+ # Check if we need to fix the database schema
175
+ if len(hashed_password) != 97:
176
+ logger.warning(f"[{registration_id}] Password hash length ({len(hashed_password)}) doesn't match expected length (97)")
177
+ logger.warning(f"[{registration_id}] This might cause issues if there's a CHECK constraint in the database")
178
+
179
+ # Try to fix the database schema by removing the constraint
180
+ try:
181
+ # First, check if the users table exists with a simple query
182
+ db_http.execute_query(
183
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='users'",
184
+ operation_id=f"{registration_id}_check_table"
185
+ )
186
+
187
+ # Create a temporary table without the constraint
188
+ db_http.execute_query(
189
+ """
190
+ CREATE TABLE IF NOT EXISTS users_temp (
191
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
192
+ email TEXT NOT NULL UNIQUE,
193
+ hashed_password TEXT NOT NULL,
194
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
195
+ last_login DATETIME,
196
+ is_admin INTEGER DEFAULT 0
197
+ )
198
+ """,
199
+ operation_id=f"{registration_id}_create_temp"
200
+ )
201
+
202
+ # Copy data from users to users_temp if users exists
203
+ try:
204
+ db_http.execute_query(
205
+ """
206
+ INSERT INTO users_temp (id, email, hashed_password, created_at, last_login, is_admin)
207
+ SELECT id, email, hashed_password, created_at, last_login, is_admin FROM users
208
+ """,
209
+ operation_id=f"{registration_id}_copy_data"
210
+ )
211
+ except Exception as e:
212
+ logger.warning(f"[{registration_id}] Error copying data: {str(e)}")
213
+
214
+ # Drop the original users table
215
+ db_http.execute_query(
216
+ "DROP TABLE IF EXISTS users",
217
+ operation_id=f"{registration_id}_drop_users"
218
+ )
219
+
220
+ # Rename users_temp to users
221
+ db_http.execute_query(
222
+ "ALTER TABLE users_temp RENAME TO users",
223
+ operation_id=f"{registration_id}_rename_table"
224
+ )
225
+
226
+ logger.info(f"[{registration_id}] Fixed users table schema")
227
+ except Exception as e:
228
+ logger.error(f"[{registration_id}] Error fixing users table: {str(e)}")
229
+ # Continue with registration anyway
230
  except Exception as e:
231
  logger.error(f"[{registration_id}] Error hashing password: {str(e)}")
232
  raise HTTPException(
main.py CHANGED
@@ -488,7 +488,7 @@ async def startup_db_client():
488
  """
489
  id INTEGER PRIMARY KEY AUTOINCREMENT,
490
  email TEXT NOT NULL UNIQUE,
491
- hashed_password TEXT NOT NULL CHECK(LENGTH(hashed_password) = 97),
492
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
493
  last_login DATETIME,
494
  is_admin BOOLEAN DEFAULT 0
@@ -2040,6 +2040,90 @@ app.include_router(auth_router.router, prefix="/api/auth", tags=["Authentication
2040
  app.include_router(projects_router.router, prefix="/api/projects", tags=["Projects"])
2041
  app.include_router(journals_router.router, prefix="/api/journals", tags=["Journals"])
2042
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2043
  # Test database with HTTP API endpoint
2044
  @app.get("/test-db-http", tags=["General"])
2045
  async def test_db_http():
 
488
  """
489
  id INTEGER PRIMARY KEY AUTOINCREMENT,
490
  email TEXT NOT NULL UNIQUE,
491
+ hashed_password TEXT NOT NULL,
492
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
493
  last_login DATETIME,
494
  is_admin BOOLEAN DEFAULT 0
 
2040
  app.include_router(projects_router.router, prefix="/api/projects", tags=["Projects"])
2041
  app.include_router(journals_router.router, prefix="/api/journals", tags=["Journals"])
2042
 
2043
+ # Fix users table endpoint
2044
+ @app.get("/fix-users-table", tags=["General"])
2045
+ async def fix_users_table():
2046
+ """
2047
+ Fix the users table by recreating it without the CHECK constraint on hashed_password.
2048
+ This endpoint is for fixing database issues.
2049
+
2050
+ Returns:
2051
+ dict: Information about the operation.
2052
+ """
2053
+ logger.info("Fix users table endpoint accessed")
2054
+ operation_id = f"fix_users_table_{int(time.time())}"
2055
+
2056
+ try:
2057
+ # Import the HTTP API utility
2058
+ from app.utils import db_http
2059
+
2060
+ # Step 1: Check if users table exists
2061
+ logger.info(f"[{operation_id}] Checking if users table exists")
2062
+
2063
+ # Step 2: Create a temporary table without the constraint
2064
+ logger.info(f"[{operation_id}] Creating temporary table")
2065
+ db_http.execute_query(
2066
+ """
2067
+ CREATE TABLE IF NOT EXISTS users_temp (
2068
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2069
+ email TEXT NOT NULL UNIQUE,
2070
+ hashed_password TEXT NOT NULL,
2071
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
2072
+ last_login DATETIME,
2073
+ is_admin INTEGER DEFAULT 0
2074
+ )
2075
+ """,
2076
+ operation_id=f"{operation_id}_create_temp"
2077
+ )
2078
+
2079
+ # Step 3: Copy data from users to users_temp if users exists
2080
+ logger.info(f"[{operation_id}] Copying data to temporary table")
2081
+ try:
2082
+ db_http.execute_query(
2083
+ """
2084
+ INSERT INTO users_temp (id, email, hashed_password, created_at, last_login, is_admin)
2085
+ SELECT id, email, hashed_password, created_at, last_login, is_admin FROM users
2086
+ """,
2087
+ operation_id=f"{operation_id}_copy_data"
2088
+ )
2089
+ logger.info(f"[{operation_id}] Data copied successfully")
2090
+ except Exception as e:
2091
+ logger.warning(f"[{operation_id}] Error copying data: {str(e)}")
2092
+ # This is expected if the users table doesn't exist or is empty
2093
+
2094
+ # Step 4: Drop the original users table
2095
+ logger.info(f"[{operation_id}] Dropping original users table")
2096
+ db_http.execute_query(
2097
+ "DROP TABLE IF EXISTS users",
2098
+ operation_id=f"{operation_id}_drop_users"
2099
+ )
2100
+
2101
+ # Step 5: Rename users_temp to users
2102
+ logger.info(f"[{operation_id}] Renaming temporary table to users")
2103
+ db_http.execute_query(
2104
+ "ALTER TABLE users_temp RENAME TO users",
2105
+ operation_id=f"{operation_id}_rename_table"
2106
+ )
2107
+
2108
+ # Step 6: Create indexes
2109
+ logger.info(f"[{operation_id}] Creating indexes")
2110
+ db_http.execute_query(
2111
+ "CREATE INDEX IF NOT EXISTS idx_users_email ON users(email)",
2112
+ operation_id=f"{operation_id}_create_index"
2113
+ )
2114
+
2115
+ logger.info(f"[{operation_id}] Users table fixed successfully")
2116
+ return {
2117
+ "success": True,
2118
+ "message": "Users table fixed successfully"
2119
+ }
2120
+ except Exception as e:
2121
+ logger.error(f"[{operation_id}] Error fixing users table: {str(e)}")
2122
+ return {
2123
+ "success": False,
2124
+ "error": str(e)
2125
+ }
2126
+
2127
  # Test database with HTTP API endpoint
2128
  @app.get("/test-db-http", tags=["General"])
2129
  async def test_db_http():