@@ -0,0 +1,613 @@ |
| | 1 | +import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'; |
| | 2 | +import bcrypt from 'bcrypt'; |
| | 3 | +import { z } from 'zod'; |
| | 4 | +import { randomBytes, randomUUID } from 'crypto'; |
| | 5 | +import { getDatabase, toCamelCase } from '../database/connection.js'; |
| | 6 | +import { EmailService } from '../services/email.js'; |
| | 7 | +import type { |
| | 8 | + RegisterRequest, |
| | 9 | + LoginRequest, |
| | 10 | + AuthResponse, |
| | 11 | + PublicUser, |
| | 12 | + EmailVerificationRequest, |
| | 13 | + PasswordResetRequest, |
| | 14 | + PasswordResetConfirmRequest, |
| | 15 | + OnboardingUpdateRequest, |
| | 16 | +} from '../database/types.js'; |
| | 17 | + |
| | 18 | +// Validation schemas |
| | 19 | +const registerSchema = z.object({ |
| | 20 | + email: z.string().email('Invalid email address'), |
| | 21 | + username: z.string().min(3).max(30).optional(), |
| | 22 | + password: z.string().min(8, 'Password must be at least 8 characters'), |
| | 23 | + userType: z.enum(['backup', 'volunteer'], { |
| | 24 | + required_error: 'Please select whether you want to backup files or volunteer storage', |
| | 25 | + }), |
| | 26 | +}); |
| | 27 | + |
| | 28 | +const loginSchema = z.object({ |
| | 29 | + email: z.string().email().optional(), |
| | 30 | + username: z.string().optional(), |
| | 31 | + password: z.string().optional(), |
| | 32 | + token: z.string().optional(), |
| | 33 | +}).refine( |
| | 34 | + (data) => (data.email || data.username) && data.password || data.token, |
| | 35 | + 'Email/username and password, or token required' |
| | 36 | +); |
| | 37 | + |
| | 38 | +const emailVerificationSchema = z.object({ |
| | 39 | + token: z.string().min(1, 'Verification token required'), |
| | 40 | +}); |
| | 41 | + |
| | 42 | +const passwordResetSchema = z.object({ |
| | 43 | + email: z.string().email('Invalid email address'), |
| | 44 | +}); |
| | 45 | + |
| | 46 | +const passwordResetConfirmSchema = z.object({ |
| | 47 | + token: z.string().min(1, 'Reset token required'), |
| | 48 | + newPassword: z.string().min(8, 'Password must be at least 8 characters'), |
| | 49 | +}); |
| | 50 | + |
| | 51 | +const onboardingUpdateSchema = z.object({ |
| | 52 | + step: z.string().min(1), |
| | 53 | + data: z.record(z.any()).optional(), |
| | 54 | + completed: z.boolean().optional(), |
| | 55 | +}); |
| | 56 | + |
| | 57 | +let emailService: EmailService; |
| | 58 | + |
| | 59 | +export async function authV2Routes(fastify: FastifyInstance) { |
| | 60 | + const db = getDatabase(); |
| | 61 | + |
| | 62 | + // Initialize email service |
| | 63 | + emailService = new EmailService({ |
| | 64 | + host: process.env.SMTP_HOST || 'smtp.ethereal.email', |
| | 65 | + port: parseInt(process.env.SMTP_PORT || '587'), |
| | 66 | + secure: process.env.SMTP_SECURE === 'true', |
| | 67 | + auth: process.env.SMTP_USER && process.env.SMTP_PASS ? { |
| | 68 | + user: process.env.SMTP_USER, |
| | 69 | + pass: process.env.SMTP_PASS, |
| | 70 | + } : undefined, |
| | 71 | + from: process.env.SMTP_FROM || 'ZephyrFS <noreply@zephyrfs.org>', |
| | 72 | + }); |
| | 73 | + |
| | 74 | + // Helper function to create public user object |
| | 75 | + const toPublicUser = (user: any): PublicUser => ({ |
| | 76 | + id: user.id, |
| | 77 | + email: user.email, |
| | 78 | + username: user.username, |
| | 79 | + userType: user.userType || user.user_type, |
| | 80 | + emailVerified: user.emailVerified || user.email_verified, |
| | 81 | + githubUsername: user.githubUsername || user.github_username, |
| | 82 | + githubAvatarUrl: user.githubAvatarUrl || user.github_avatar_url, |
| | 83 | + createdAt: new Date(user.createdAt || user.created_at), |
| | 84 | + }); |
| | 85 | + |
| | 86 | + // User registration |
| | 87 | + fastify.post<{ |
| | 88 | + Body: RegisterRequest; |
| | 89 | + }>('/auth/register', { |
| | 90 | + schema: { body: registerSchema }, |
| | 91 | + }, async (request: FastifyRequest, reply: FastifyReply) => { |
| | 92 | + const { email, username, password, userType } = request.body as RegisterRequest; |
| | 93 | + |
| | 94 | + try { |
| | 95 | + // Check if user already exists |
| | 96 | + const existingUser = await db |
| | 97 | + .selectFrom('users') |
| | 98 | + .selectAll() |
| | 99 | + .where((eb) => eb.or([ |
| | 100 | + eb('email', '=', email), |
| | 101 | + ...(username ? [eb('username', '=', username)] : []) |
| | 102 | + ])) |
| | 103 | + .executeTakeFirst(); |
| | 104 | + |
| | 105 | + if (existingUser) { |
| | 106 | + if (existingUser.email === email) { |
| | 107 | + throw fastify.httpErrors.conflict('Email already registered'); |
| | 108 | + } |
| | 109 | + if (existingUser.username === username) { |
| | 110 | + throw fastify.httpErrors.conflict('Username already taken'); |
| | 111 | + } |
| | 112 | + } |
| | 113 | + |
| | 114 | + // Hash password |
| | 115 | + const passwordHash = await bcrypt.hash(password, 12); |
| | 116 | + |
| | 117 | + // Generate verification token |
| | 118 | + const verificationToken = randomBytes(32).toString('hex'); |
| | 119 | + const verificationExpiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24 hours |
| | 120 | + |
| | 121 | + // Create user |
| | 122 | + const userId = randomUUID(); |
| | 123 | + await db |
| | 124 | + .insertInto('users') |
| | 125 | + .values({ |
| | 126 | + id: userId, |
| | 127 | + email, |
| | 128 | + username, |
| | 129 | + password_hash: passwordHash, |
| | 130 | + user_type: userType, |
| | 131 | + email_verified: false, |
| | 132 | + email_verification_token: verificationToken, |
| | 133 | + email_verification_expires_at: verificationExpiresAt.toISOString(), |
| | 134 | + created_at: new Date().toISOString(), |
| | 135 | + updated_at: new Date().toISOString(), |
| | 136 | + }) |
| | 137 | + .execute(); |
| | 138 | + |
| | 139 | + // Create email verification record |
| | 140 | + await db |
| | 141 | + .insertInto('email_verifications') |
| | 142 | + .values({ |
| | 143 | + id: randomUUID(), |
| | 144 | + user_id: userId, |
| | 145 | + email, |
| | 146 | + token: verificationToken, |
| | 147 | + attempts: 0, |
| | 148 | + expires_at: verificationExpiresAt.toISOString(), |
| | 149 | + created_at: new Date().toISOString(), |
| | 150 | + }) |
| | 151 | + .execute(); |
| | 152 | + |
| | 153 | + // Send verification email |
| | 154 | + try { |
| | 155 | + await emailService.sendEmailVerification(email, verificationToken, username); |
| | 156 | + } catch (emailError) { |
| | 157 | + fastify.log.error(emailError, 'Failed to send verification email'); |
| | 158 | + // Don't fail registration if email fails |
| | 159 | + } |
| | 160 | + |
| | 161 | + // Initialize onboarding steps |
| | 162 | + const onboardingSteps = userType === 'volunteer' |
| | 163 | + ? ['user-type-selection', 'storage-setup', 'desktop-app', 'node-configuration'] |
| | 164 | + : ['user-type-selection', 'backup-setup', 'first-upload']; |
| | 165 | + |
| | 166 | + for (const step of onboardingSteps) { |
| | 167 | + await db |
| | 168 | + .insertInto('user_onboarding') |
| | 169 | + .values({ |
| | 170 | + id: randomUUID(), |
| | 171 | + user_id: userId, |
| | 172 | + step, |
| | 173 | + completed: step === 'user-type-selection', // First step completed |
| | 174 | + data: step === 'user-type-selection' ? JSON.stringify({ userType }) : null, |
| | 175 | + completed_at: step === 'user-type-selection' ? new Date().toISOString() : null, |
| | 176 | + created_at: new Date().toISOString(), |
| | 177 | + }) |
| | 178 | + .execute(); |
| | 179 | + } |
| | 180 | + |
| | 181 | + return { |
| | 182 | + success: true, |
| | 183 | + message: 'Registration successful! Please check your email to verify your account.', |
| | 184 | + userId, |
| | 185 | + }; |
| | 186 | + } catch (error) { |
| | 187 | + if (error.statusCode) { |
| | 188 | + throw error; |
| | 189 | + } |
| | 190 | + fastify.log.error(error, 'Registration failed'); |
| | 191 | + throw fastify.httpErrors.internalServerError('Registration failed'); |
| | 192 | + } |
| | 193 | + }); |
| | 194 | + |
| | 195 | + // Email verification |
| | 196 | + fastify.post<{ |
| | 197 | + Body: EmailVerificationRequest; |
| | 198 | + }>('/auth/verify-email', { |
| | 199 | + schema: { body: emailVerificationSchema }, |
| | 200 | + }, async (request: FastifyRequest, reply: FastifyReply) => { |
| | 201 | + const { token } = request.body as EmailVerificationRequest; |
| | 202 | + |
| | 203 | + try { |
| | 204 | + // Find verification record |
| | 205 | + const verification = await db |
| | 206 | + .selectFrom('email_verifications') |
| | 207 | + .selectAll() |
| | 208 | + .where('token', '=', token) |
| | 209 | + .where('verified_at', 'is', null) |
| | 210 | + .executeTakeFirst(); |
| | 211 | + |
| | 212 | + if (!verification) { |
| | 213 | + throw fastify.httpErrors.badRequest('Invalid or expired verification token'); |
| | 214 | + } |
| | 215 | + |
| | 216 | + if (new Date() > new Date(verification.expires_at)) { |
| | 217 | + throw fastify.httpErrors.badRequest('Verification token has expired'); |
| | 218 | + } |
| | 219 | + |
| | 220 | + // Update verification record |
| | 221 | + await db |
| | 222 | + .updateTable('email_verifications') |
| | 223 | + .set({ |
| | 224 | + verified_at: new Date().toISOString(), |
| | 225 | + attempts: verification.attempts + 1, |
| | 226 | + }) |
| | 227 | + .where('id', '=', verification.id) |
| | 228 | + .execute(); |
| | 229 | + |
| | 230 | + // Update user |
| | 231 | + const user = await db |
| | 232 | + .updateTable('users') |
| | 233 | + .set({ |
| | 234 | + email_verified: true, |
| | 235 | + email_verification_token: null, |
| | 236 | + email_verification_expires_at: null, |
| | 237 | + updated_at: new Date().toISOString(), |
| | 238 | + }) |
| | 239 | + .where('id', '=', verification.user_id) |
| | 240 | + .returningAll() |
| | 241 | + .executeTakeFirstOrThrow(); |
| | 242 | + |
| | 243 | + // Send welcome email |
| | 244 | + try { |
| | 245 | + await emailService.sendWelcomeEmail( |
| | 246 | + user.email, |
| | 247 | + user.user_type as 'backup' | 'volunteer', |
| | 248 | + user.username || undefined |
| | 249 | + ); |
| | 250 | + } catch (emailError) { |
| | 251 | + fastify.log.error(emailError, 'Failed to send welcome email'); |
| | 252 | + } |
| | 253 | + |
| | 254 | + return { |
| | 255 | + success: true, |
| | 256 | + message: 'Email verified successfully! Welcome to ZephyrFS!', |
| | 257 | + user: toPublicUser(user), |
| | 258 | + }; |
| | 259 | + } catch (error) { |
| | 260 | + if (error.statusCode) { |
| | 261 | + throw error; |
| | 262 | + } |
| | 263 | + fastify.log.error(error, 'Email verification failed'); |
| | 264 | + throw fastify.httpErrors.internalServerError('Email verification failed'); |
| | 265 | + } |
| | 266 | + }); |
| | 267 | + |
| | 268 | + // Enhanced login |
| | 269 | + fastify.post<{ |
| | 270 | + Body: LoginRequest; |
| | 271 | + }>('/auth/login', { |
| | 272 | + schema: { body: loginSchema }, |
| | 273 | + }, async (request: FastifyRequest, reply: FastifyReply) => { |
| | 274 | + const { email, username, password, token } = request.body as LoginRequest; |
| | 275 | + |
| | 276 | + try { |
| | 277 | + let user: any; |
| | 278 | + |
| | 279 | + if (token) { |
| | 280 | + // Token-based authentication |
| | 281 | + try { |
| | 282 | + const decoded = fastify.jwt.verify(token) as { userId: string; username: string }; |
| | 283 | + user = await db |
| | 284 | + .selectFrom('users') |
| | 285 | + .selectAll() |
| | 286 | + .where('id', '=', decoded.userId) |
| | 287 | + .executeTakeFirst(); |
| | 288 | + |
| | 289 | + if (!user) { |
| | 290 | + throw new Error('User not found'); |
| | 291 | + } |
| | 292 | + } catch (error) { |
| | 293 | + throw fastify.httpErrors.unauthorized('Invalid token'); |
| | 294 | + } |
| | 295 | + } else if ((email || username) && password) { |
| | 296 | + // Password-based authentication |
| | 297 | + user = await db |
| | 298 | + .selectFrom('users') |
| | 299 | + .selectAll() |
| | 300 | + .where((eb) => eb.or([ |
| | 301 | + ...(email ? [eb('email', '=', email)] : []), |
| | 302 | + ...(username ? [eb('username', '=', username)] : []) |
| | 303 | + ])) |
| | 304 | + .executeTakeFirst(); |
| | 305 | + |
| | 306 | + if (!user || !user.password_hash) { |
| | 307 | + throw fastify.httpErrors.unauthorized('Invalid credentials'); |
| | 308 | + } |
| | 309 | + |
| | 310 | + const validPassword = await bcrypt.compare(password, user.password_hash); |
| | 311 | + if (!validPassword) { |
| | 312 | + throw fastify.httpErrors.unauthorized('Invalid credentials'); |
| | 313 | + } |
| | 314 | + |
| | 315 | + // Check if email is verified for new registrations |
| | 316 | + if (!user.email_verified) { |
| | 317 | + throw fastify.httpErrors.forbidden('Please verify your email address before logging in'); |
| | 318 | + } |
| | 319 | + } else { |
| | 320 | + throw fastify.httpErrors.badRequest('Email/username and password, or token required'); |
| | 321 | + } |
| | 322 | + |
| | 323 | + // Create session |
| | 324 | + const sessionId = randomUUID(); |
| | 325 | + const sessionToken = randomBytes(32).toString('hex'); |
| | 326 | + const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000); // 30 days |
| | 327 | + |
| | 328 | + await db |
| | 329 | + .insertInto('user_sessions') |
| | 330 | + .values({ |
| | 331 | + id: sessionId, |
| | 332 | + user_id: user.id, |
| | 333 | + session_token: sessionToken, |
| | 334 | + expires_at: expiresAt.toISOString(), |
| | 335 | + created_at: new Date().toISOString(), |
| | 336 | + last_access_at: new Date().toISOString(), |
| | 337 | + ip_address: request.ip, |
| | 338 | + user_agent: request.headers['user-agent'], |
| | 339 | + }) |
| | 340 | + .execute(); |
| | 341 | + |
| | 342 | + // Update last login |
| | 343 | + await db |
| | 344 | + .updateTable('users') |
| | 345 | + .set({ |
| | 346 | + last_login_at: new Date().toISOString(), |
| | 347 | + updated_at: new Date().toISOString(), |
| | 348 | + }) |
| | 349 | + .where('id', '=', user.id) |
| | 350 | + .execute(); |
| | 351 | + |
| | 352 | + // Generate tokens |
| | 353 | + const accessToken = fastify.jwt.sign( |
| | 354 | + { userId: user.id, username: user.username, sessionId }, |
| | 355 | + { expiresIn: fastify.config.jwtExpiresIn } |
| | 356 | + ); |
| | 357 | + |
| | 358 | + const refreshToken = fastify.jwt.sign( |
| | 359 | + { userId: user.id, sessionId, type: 'refresh' }, |
| | 360 | + { expiresIn: fastify.config.jwtRefreshExpiresIn } |
| | 361 | + ); |
| | 362 | + |
| | 363 | + const response: AuthResponse = { |
| | 364 | + token: accessToken, |
| | 365 | + refreshToken, |
| | 366 | + expiresIn: 24 * 60 * 60, // 24 hours in seconds |
| | 367 | + user: toPublicUser(user), |
| | 368 | + }; |
| | 369 | + |
| | 370 | + return response; |
| | 371 | + } catch (error) { |
| | 372 | + if (error.statusCode) { |
| | 373 | + throw error; |
| | 374 | + } |
| | 375 | + fastify.log.error(error, 'Login failed'); |
| | 376 | + throw fastify.httpErrors.internalServerError('Login failed'); |
| | 377 | + } |
| | 378 | + }); |
| | 379 | + |
| | 380 | + // Password reset request |
| | 381 | + fastify.post<{ |
| | 382 | + Body: PasswordResetRequest; |
| | 383 | + }>('/auth/password-reset', { |
| | 384 | + schema: { body: passwordResetSchema }, |
| | 385 | + }, async (request: FastifyRequest, reply: FastifyReply) => { |
| | 386 | + const { email } = request.body as PasswordResetRequest; |
| | 387 | + |
| | 388 | + try { |
| | 389 | + const user = await db |
| | 390 | + .selectFrom('users') |
| | 391 | + .selectAll() |
| | 392 | + .where('email', '=', email) |
| | 393 | + .executeTakeFirst(); |
| | 394 | + |
| | 395 | + // Always return success to prevent email enumeration |
| | 396 | + if (!user) { |
| | 397 | + return { |
| | 398 | + success: true, |
| | 399 | + message: 'If an account with that email exists, we\'ve sent a password reset link.', |
| | 400 | + }; |
| | 401 | + } |
| | 402 | + |
| | 403 | + // Generate reset token |
| | 404 | + const resetToken = randomBytes(32).toString('hex'); |
| | 405 | + const resetExpiresAt = new Date(Date.now() + 60 * 60 * 1000); // 1 hour |
| | 406 | + |
| | 407 | + // Update user with reset token |
| | 408 | + await db |
| | 409 | + .updateTable('users') |
| | 410 | + .set({ |
| | 411 | + password_reset_token: resetToken, |
| | 412 | + password_reset_expires_at: resetExpiresAt.toISOString(), |
| | 413 | + updated_at: new Date().toISOString(), |
| | 414 | + }) |
| | 415 | + .where('id', '=', user.id) |
| | 416 | + .execute(); |
| | 417 | + |
| | 418 | + // Create password reset record |
| | 419 | + await db |
| | 420 | + .insertInto('password_resets') |
| | 421 | + .values({ |
| | 422 | + id: randomUUID(), |
| | 423 | + user_id: user.id, |
| | 424 | + token: resetToken, |
| | 425 | + attempts: 0, |
| | 426 | + expires_at: resetExpiresAt.toISOString(), |
| | 427 | + created_at: new Date().toISOString(), |
| | 428 | + }) |
| | 429 | + .execute(); |
| | 430 | + |
| | 431 | + // Send reset email |
| | 432 | + try { |
| | 433 | + await emailService.sendPasswordReset(email, resetToken, user.username || undefined); |
| | 434 | + } catch (emailError) { |
| | 435 | + fastify.log.error(emailError, 'Failed to send password reset email'); |
| | 436 | + } |
| | 437 | + |
| | 438 | + return { |
| | 439 | + success: true, |
| | 440 | + message: 'If an account with that email exists, we\'ve sent a password reset link.', |
| | 441 | + }; |
| | 442 | + } catch (error) { |
| | 443 | + fastify.log.error(error, 'Password reset request failed'); |
| | 444 | + throw fastify.httpErrors.internalServerError('Password reset request failed'); |
| | 445 | + } |
| | 446 | + }); |
| | 447 | + |
| | 448 | + // Password reset confirmation |
| | 449 | + fastify.post<{ |
| | 450 | + Body: PasswordResetConfirmRequest; |
| | 451 | + }>('/auth/password-reset/confirm', { |
| | 452 | + schema: { body: passwordResetConfirmSchema }, |
| | 453 | + }, async (request: FastifyRequest, reply: FastifyReply) => { |
| | 454 | + const { token, newPassword } = request.body as PasswordResetConfirmRequest; |
| | 455 | + |
| | 456 | + try { |
| | 457 | + // Find reset record |
| | 458 | + const reset = await db |
| | 459 | + .selectFrom('password_resets') |
| | 460 | + .selectAll() |
| | 461 | + .where('token', '=', token) |
| | 462 | + .where('used_at', 'is', null) |
| | 463 | + .executeTakeFirst(); |
| | 464 | + |
| | 465 | + if (!reset) { |
| | 466 | + throw fastify.httpErrors.badRequest('Invalid or expired reset token'); |
| | 467 | + } |
| | 468 | + |
| | 469 | + if (new Date() > new Date(reset.expires_at)) { |
| | 470 | + throw fastify.httpErrors.badRequest('Reset token has expired'); |
| | 471 | + } |
| | 472 | + |
| | 473 | + // Hash new password |
| | 474 | + const passwordHash = await bcrypt.hash(newPassword, 12); |
| | 475 | + |
| | 476 | + // Update user |
| | 477 | + await db |
| | 478 | + .updateTable('users') |
| | 479 | + .set({ |
| | 480 | + password_hash: passwordHash, |
| | 481 | + password_reset_token: null, |
| | 482 | + password_reset_expires_at: null, |
| | 483 | + updated_at: new Date().toISOString(), |
| | 484 | + }) |
| | 485 | + .where('id', '=', reset.user_id) |
| | 486 | + .execute(); |
| | 487 | + |
| | 488 | + // Mark reset as used |
| | 489 | + await db |
| | 490 | + .updateTable('password_resets') |
| | 491 | + .set({ |
| | 492 | + used_at: new Date().toISOString(), |
| | 493 | + attempts: reset.attempts + 1, |
| | 494 | + }) |
| | 495 | + .where('id', '=', reset.id) |
| | 496 | + .execute(); |
| | 497 | + |
| | 498 | + // Invalidate all sessions for this user |
| | 499 | + await db |
| | 500 | + .deleteFrom('user_sessions') |
| | 501 | + .where('user_id', '=', reset.user_id) |
| | 502 | + .execute(); |
| | 503 | + |
| | 504 | + return { |
| | 505 | + success: true, |
| | 506 | + message: 'Password updated successfully! Please log in with your new password.', |
| | 507 | + }; |
| | 508 | + } catch (error) { |
| | 509 | + if (error.statusCode) { |
| | 510 | + throw error; |
| | 511 | + } |
| | 512 | + fastify.log.error(error, 'Password reset confirmation failed'); |
| | 513 | + throw fastify.httpErrors.internalServerError('Password reset confirmation failed'); |
| | 514 | + } |
| | 515 | + }); |
| | 516 | + |
| | 517 | + // Get user onboarding status |
| | 518 | + fastify.get('/auth/onboarding', { |
| | 519 | + preHandler: fastify.authenticate, |
| | 520 | + }, async (request: FastifyRequest) => { |
| | 521 | + const user = request.user as { userId: string }; |
| | 522 | + |
| | 523 | + const onboardingSteps = await db |
| | 524 | + .selectFrom('user_onboarding') |
| | 525 | + .selectAll() |
| | 526 | + .where('user_id', '=', user.userId) |
| | 527 | + .orderBy('created_at', 'asc') |
| | 528 | + .execute(); |
| | 529 | + |
| | 530 | + return { |
| | 531 | + steps: onboardingSteps.map(toCamelCase), |
| | 532 | + completed: onboardingSteps.filter(step => step.completed).length, |
| | 533 | + total: onboardingSteps.length, |
| | 534 | + }; |
| | 535 | + }); |
| | 536 | + |
| | 537 | + // Update onboarding progress |
| | 538 | + fastify.post<{ |
| | 539 | + Body: OnboardingUpdateRequest; |
| | 540 | + }>('/auth/onboarding/update', { |
| | 541 | + preHandler: fastify.authenticate, |
| | 542 | + schema: { body: onboardingUpdateSchema }, |
| | 543 | + }, async (request: FastifyRequest) => { |
| | 544 | + const user = request.user as { userId: string }; |
| | 545 | + const { step, data, completed } = request.body as OnboardingUpdateRequest; |
| | 546 | + |
| | 547 | + await db |
| | 548 | + .updateTable('user_onboarding') |
| | 549 | + .set({ |
| | 550 | + completed: completed || false, |
| | 551 | + data: data ? JSON.stringify(data) : null, |
| | 552 | + completed_at: completed ? new Date().toISOString() : null, |
| | 553 | + }) |
| | 554 | + .where('user_id', '=', user.userId) |
| | 555 | + .where('step', '=', step) |
| | 556 | + .execute(); |
| | 557 | + |
| | 558 | + return { success: true }; |
| | 559 | + }); |
| | 560 | + |
| | 561 | + // Get current user info (enhanced) |
| | 562 | + fastify.get('/auth/me', { |
| | 563 | + preHandler: fastify.authenticate, |
| | 564 | + }, async (request: FastifyRequest) => { |
| | 565 | + const authUser = request.user as { userId: string; sessionId: string }; |
| | 566 | + |
| | 567 | + // Get user details |
| | 568 | + const user = await db |
| | 569 | + .selectFrom('users') |
| | 570 | + .selectAll() |
| | 571 | + .where('id', '=', authUser.userId) |
| | 572 | + .executeTakeFirstOrThrow(); |
| | 573 | + |
| | 574 | + // Update session last access |
| | 575 | + await db |
| | 576 | + .updateTable('user_sessions') |
| | 577 | + .set({ last_access_at: new Date().toISOString() }) |
| | 578 | + .where('id', '=', authUser.sessionId) |
| | 579 | + .execute(); |
| | 580 | + |
| | 581 | + return toPublicUser(user); |
| | 582 | + }); |
| | 583 | + |
| | 584 | + // Enhanced logout (cleanup sessions) |
| | 585 | + fastify.post('/auth/logout', { |
| | 586 | + preHandler: fastify.authenticate, |
| | 587 | + }, async (request: FastifyRequest) => { |
| | 588 | + const user = request.user as { sessionId: string }; |
| | 589 | + |
| | 590 | + // Remove session |
| | 591 | + await db |
| | 592 | + .deleteFrom('user_sessions') |
| | 593 | + .where('id', '=', user.sessionId) |
| | 594 | + .execute(); |
| | 595 | + |
| | 596 | + return { success: true }; |
| | 597 | + }); |
| | 598 | + |
| | 599 | + // Logout from all devices |
| | 600 | + fastify.post('/auth/logout-all', { |
| | 601 | + preHandler: fastify.authenticate, |
| | 602 | + }, async (request: FastifyRequest) => { |
| | 603 | + const user = request.user as { userId: string }; |
| | 604 | + |
| | 605 | + // Remove all sessions for user |
| | 606 | + await db |
| | 607 | + .deleteFrom('user_sessions') |
| | 608 | + .where('user_id', '=', user.userId) |
| | 609 | + .execute(); |
| | 610 | + |
| | 611 | + return { success: true }; |
| | 612 | + }); |
| | 613 | +} |