All files / routes/user profile.routes.ts

97.64% Statements 249/255
100% Branches 116/116
100% Functions 11/11
97.64% Lines 249/255

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659                                          1x   1x     1x 4x 4x 4x 1x     3x 3x 2x 1x     1x                 1x         1x 15x 15x 15x 1x     14x       14x   14x     14x 7x 7x 3x       4x       11x 7x 2x   5x 5x 2x         3x   3x 3x 1x             2x       8x 1x     7x 7x 1x     6x               6x         1x 12x 12x 12x 1x     11x 11x   11x 11x   11x 1x     10x     10x 8x 5x 5x             8x 12x   12x 8x         8x   8x         3x         1x 5x 5x 5x 1x     4x 4x   4x 3x 2x 2x           3x   3x   1x         1x 5x 5x 5x 1x     4x 4x   4x 5x 2x           2x     2x 2x 1x                 1x 1x 1x     1x 1x 1x     1x       1x               1x 1x   1x   2x         1x 9x 9x 9x 1x     8x 8x 8x   8x 9x   9x 1x       7x     9x 7x           7x 7x 1x       6x 1x     1x         5x 5x             5x 2x 2x 1x 1x   1x     1x       3x 3x 1x     1x                 2x               2x       2x               1x               1x 6x 6x 6x 1x     5x 5x   5x 6x 2x       3x 1x       2x 2x 1x                 1x 1x 1x     1x 1x 1x     1x       1x               1x 1x 1x                         1x   3x         1x 7x 7x 7x 1x     6x 6x 6x   6x 7x   7x 1x       5x 5x           5x 5x 1x       4x 1x     1x         3x 3x                             1x     1x       2x 2x 1x     1x                 1x                     1x       1x               1x         1x 10x 10x 10x 1x     9x 9x   9x 1x   8x 4x     4x 4x     4x           4x 3x     4x 1x       3x 3x 3x   3x               3x   5x         1x   1x 7x 7x 7x 1x     6x     6x   6x   6x 5x 1x       4x     5x 1x     4x 4x 1x     3x       2x          
// User Profile Routes - Manage personal account settings
import { Hono } from "hono";
import type { Dal } from "../../dal";
import type { Services } from "../../services";
import type { getDb } from "../../db";
import { eq } from "drizzle-orm";
import { success, error, handleError } from "../../lib/response";
import { ValidationError } from "../../lib/errors";
import { validateUploadedFile } from "../../lib/file-validation";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
		db: ReturnType<typeof getDb>;
	};
};
 
const INDIAN_PHONE_REGEX = /^[6-9]\d{9}$/;
 
const profile = new Hono<Env>();
 
// GET /me - Get current user's profile
profile.get("/me", async (c) => {
	try {
		const user = c.get("user");
		if (!user) {
			return error(c, "UNAUTHORIZED", "Authentication required", 401);
		}
 
		const dal = c.get("dal");
		const fullUser = await dal.users.findById(user.id);
		if (!fullUser) {
			return error(c, "NOT_FOUND", "User not found", 404);
		}
 
		return success(c, {
			id: fullUser.id,
			name: fullUser.name,
			email: fullUser.email,
			phoneNumber: fullUser.phoneNumber,
			image: fullUser.image,
			themePreference: fullUser.themePreference,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// PUT /me - Update name and phone number
profile.put("/me", async (c) => {
	try {
		const user = c.get("user");
		if (!user) {
			return error(c, "UNAUTHORIZED", "Authentication required", 401);
		}
 
		const body = await c.req.json<{
			name?: string;
			phoneNumber?: string | null;
		}>();
		const dal = c.get("dal");
 
		const updates: Record<string, unknown> = {};
 
		// Validate name
		if (body.name !== undefined) {
			const name = body.name.trim();
			if (!name || name.length > 100) {
				throw new ValidationError(
					"Name is required and must be 100 characters or fewer",
				);
			}
			updates.name = name;
		}
 
		// Validate phone number
		if (body.phoneNumber !== undefined) {
			if (body.phoneNumber === null || body.phoneNumber === "") {
				updates.phoneNumber = null;
			} else {
				const phone = body.phoneNumber.trim();
				if (!INDIAN_PHONE_REGEX.test(phone)) {
					throw new ValidationError(
						"Phone number must be a valid 10-digit Indian mobile number",
					);
				}
				// Normalize to E.164 format for consistent storage
				const e164Phone = `+91${phone}`;
				// Check uniqueness
				const existing = await dal.users.findByPhoneNumber(e164Phone, user.id);
				if (existing) {
					return error(
						c,
						"PHONE_EXISTS",
						"This phone number is already in use by another account",
						409,
					);
				}
				updates.phoneNumber = e164Phone;
			}
		}
 
		if (Object.keys(updates).length === 0) {
			throw new ValidationError("No valid fields to update");
		}
 
		const updated = await dal.users.update(user.id, updates);
		if (!updated) {
			return error(c, "NOT_FOUND", "User not found", 404);
		}
 
		return success(c, {
			id: updated.id,
			name: updated.name,
			email: updated.email,
			phoneNumber: updated.phoneNumber,
			image: updated.image,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// POST /me/avatar - Upload profile picture
profile.post("/me/avatar", async (c) => {
	try {
		const user = c.get("user");
		if (!user) {
			return error(c, "UNAUTHORIZED", "Authentication required", 401);
		}
 
		const r2 = c.env.R2;
		const dal = c.get("dal");
 
		const formData = await c.req.formData();
		const file = formData.get("file") as File | null;
 
		if (!file) {
			throw new ValidationError("No file provided");
		}
 
		validateUploadedFile(file);
 
		// Delete previous avatar if exists
		const currentUser = await dal.users.findById(user.id);
		if (currentUser?.image) {
			try {
				await r2.delete(currentUser.image);
			} catch {
				// Ignore delete errors for old avatar
			}
		}
 
		// Deterministic path so re-uploads overwrite
		const ext = file.name.split(".").pop() || "jpg";
		const path = `users/${user.id}/avatar.${ext}`;
 
		const arrayBuffer = await file.arrayBuffer();
		await r2.put(path, arrayBuffer, {
			httpMetadata: { contentType: file.type },
		});
 
		// Update user record
		await dal.users.update(user.id, { image: path });
 
		return success(c, {
			path,
			url: `/api/images/${path}`,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// DELETE /me/avatar - Remove profile picture
profile.delete("/me/avatar", async (c) => {
	try {
		const user = c.get("user");
		if (!user) {
			return error(c, "UNAUTHORIZED", "Authentication required", 401);
		}
 
		const r2 = c.env.R2;
		const dal = c.get("dal");
 
		const currentUser = await dal.users.findById(user.id);
		if (currentUser?.image) {
			try {
				await r2.delete(currentUser.image);
			} catch {
				// Ignore R2 delete errors
			}
		}
 
		await dal.users.update(user.id, { image: null });
 
		return success(c, { message: "Avatar removed" });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// POST /me/change-phone - Send OTP to new phone number
profile.post("/me/change-phone", async (c) => {
	try {
		const user = c.get("user");
		if (!user) {
			return error(c, "UNAUTHORIZED", "Authentication required", 401);
		}
 
		const body = await c.req.json<{ phoneNumber: string }>();
		const dal = c.get("dal");
 
		const phone = body.phoneNumber?.trim();
		if (!phone || !INDIAN_PHONE_REGEX.test(phone)) {
			throw new ValidationError(
				"Phone number must be a valid 10-digit Indian mobile number",
			);
		}
 
		// Normalize to E.164 format
		const e164Phone = `+91${phone}`;
 
		// Check uniqueness
		const existing = await dal.users.findByPhoneNumber(e164Phone, user.id);
		if (existing) {
			return error(
				c,
				"PHONE_EXISTS",
				"This phone number is already in use by another account",
				409,
			);
		}
 
		// Generate cryptographically secure 6-digit OTP
		const otpBytes = new Uint8Array(4);
		crypto.getRandomValues(otpBytes);
		const code = String(100000 + (new DataView(otpBytes.buffer).getUint32(0) % 900000));
 
		// Store OTP in verifications table
		const { generateId } = await import("../../lib/utils");
		const authVerifications = (await import("../../db/schema/auth")).verifications;
		const db = c.get("db");
 
		// Delete any existing phone change verification for this user
		await db
			.delete(authVerifications)
			.where(eq(authVerifications.identifier, `phone-change:${user.id}`));
 
		await db.insert(authVerifications).values({
			id: generateId(),
			identifier: `phone-change:${user.id}`,
			value: JSON.stringify({ code, phoneNumber: e164Phone, attempts: 0 }),
			expiresAt: new Date(Date.now() + 5 * 60 * 1000), // 5 minutes
		});
 
		// Send OTP via WhatsApp
		const { sendWhatsAppOtp } = await import("../../lib/communication/whatsapp-otp");
		await sendWhatsAppOtp(c.env, e164Phone, code);
 
		return success(c, { message: "OTP sent to your phone via WhatsApp" });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// POST /me/change-phone/verify - Verify OTP and update phone number
profile.post("/me/change-phone/verify", async (c) => {
	try {
		const user = c.get("user");
		if (!user) {
			return error(c, "UNAUTHORIZED", "Authentication required", 401);
		}
 
		const body = await c.req.json<{ phoneNumber: string; code: string }>();
		const dal = c.get("dal");
		const db = c.get("db");
 
		const phone = body.phoneNumber?.trim();
		const code = body.code?.trim();
 
		if (!phone || !code) {
			throw new ValidationError("Phone number and OTP code are required");
		}
 
		// Normalize to E.164 format
		const e164Phone = phone.startsWith("+") ? phone : `+91${phone}`;
 
		// Look up the pending verification
		const authVerifications = (await import("../../db/schema/auth")).verifications;
		const records = await db
			.select()
			.from(authVerifications)
			.where(eq(authVerifications.identifier, `phone-change:${user.id}`))
			.limit(1);
 
		const record = records[0];
		if (!record) {
			return error(c, "INVALID_OTP", "No pending phone change. Please request a new OTP.", 400);
		}
 
		// Check expiry
		if (new Date() > record.expiresAt) {
			await db
				.delete(authVerifications)
				.where(eq(authVerifications.id, record.id));
			return error(c, "OTP_EXPIRED", "OTP has expired. Please request a new one.", 400);
		}
 
		// Parse verification data safely
		let stored: { code: string; phoneNumber: string; attempts?: number };
		try {
			stored = JSON.parse(record.value);
		} catch {
			await db.delete(authVerifications).where(eq(authVerifications.id, record.id));
			return error(c, "INVALID_OTP", "Verification data corrupted. Please request a new code.", 400);
		}
 
		// Verify OTP and phone match (with brute-force protection)
		if (stored.code !== code || stored.phoneNumber !== e164Phone) {
			const attempts = (stored.attempts || 0) + 1;
			if (attempts >= 5) {
				await db.delete(authVerifications).where(eq(authVerifications.id, record.id));
				return error(c, "TOO_MANY_ATTEMPTS", "Too many failed attempts. Please request a new code.", 400);
			}
			await db.update(authVerifications)
				.set({ value: JSON.stringify({ ...stored, attempts }) })
				.where(eq(authVerifications.id, record.id));
			return error(c, "INVALID_OTP", "Invalid OTP code", 400);
		}
 
		// Check uniqueness again (race condition guard)
		const existing = await dal.users.findByPhoneNumber(e164Phone, user.id);
		if (existing) {
			await db
				.delete(authVerifications)
				.where(eq(authVerifications.id, record.id));
			return error(
				c,
				"PHONE_EXISTS",
				"This phone number is already in use by another account",
				409,
			);
		}
 
		// Update user's phone number in E.164 format
		const updated = await dal.users.update(user.id, { phoneNumber: e164Phone });
		/* v8 ignore start -- defensive guard: user just authenticated */
		if (!updated) {
			return error(c, "NOT_FOUND", "User not found", 404);
		}
		/* v8 ignore stop */
 
		// Clean up verification record
		await db
			.delete(authVerifications)
			.where(eq(authVerifications.id, record.id));
 
		return success(c, {
			id: updated.id,
			name: updated.name,
			email: updated.email,
			phoneNumber: updated.phoneNumber,
			image: updated.image,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// POST /me/change-email - Send OTP to new email address
// NOTE: This custom OTP-based email change bypasses Better Auth's changeEmail plugin.
// It directly updates users.email and sets emailVerified=true after OTP verification.
// Better Auth's Drizzle adapter reads email from the users table, so this is safe.
profile.post("/me/change-email", async (c) => {
	try {
		const user = c.get("user");
		if (!user) {
			return error(c, "UNAUTHORIZED", "Authentication required", 401);
		}
 
		const body = await c.req.json<{ email: string }>();
		const dal = c.get("dal");
 
		const newEmail = body.email?.trim().toLowerCase();
		if (!newEmail || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(newEmail)) {
			throw new ValidationError("Please enter a valid email address");
		}
 
		// Don't allow changing to the same email
		if (newEmail === user.email) {
			throw new ValidationError("This is already your current email");
		}
 
		// Check uniqueness
		const existing = await dal.users.findByEmail(newEmail);
		if (existing) {
			return error(
				c,
				"EMAIL_EXISTS",
				"This email is already in use by another account",
				409,
			);
		}
 
		// Generate cryptographically secure 6-digit OTP
		const otpBytes = new Uint8Array(4);
		crypto.getRandomValues(otpBytes);
		const code = String(100000 + (new DataView(otpBytes.buffer).getUint32(0) % 900000));
 
		// Store OTP in verifications table
		const { generateId } = await import("../../lib/utils");
		const authVerifications = (await import("../../db/schema/auth")).verifications;
		const db = c.get("db");
 
		// Delete any existing email change verification for this user
		await db
			.delete(authVerifications)
			.where(eq(authVerifications.identifier, `email-change:${user.id}`));
 
		await db.insert(authVerifications).values({
			id: generateId(),
			identifier: `email-change:${user.id}`,
			value: JSON.stringify({ code, email: newEmail, attempts: 0 }),
			expiresAt: new Date(Date.now() + 5 * 60 * 1000), // 5 minutes
		});
 
		// Send OTP via email
		const { CommunicationGateway } = await import("../../lib/communication/gateway");
		const gateway = new CommunicationGateway(dal, c.env);
		await gateway.send({
			channel: "email",
			recipient: newEmail,
			eventType: "otp_verification",
			userId: user.id,
			transactional: true,
			content: {
				template: "email-otp",
				subject: "Your Interioring verification code",
				props: { code, userName: user.name },
			},
		});
 
		return success(c, { message: "Verification code sent to your new email" });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// POST /me/change-email/verify - Verify OTP and update email
profile.post("/me/change-email/verify", async (c) => {
	try {
		const user = c.get("user");
		if (!user) {
			return error(c, "UNAUTHORIZED", "Authentication required", 401);
		}
 
		const body = await c.req.json<{ email: string; code: string }>();
		const dal = c.get("dal");
		const db = c.get("db");
 
		const newEmail = body.email?.trim().toLowerCase();
		const code = body.code?.trim();
 
		if (!newEmail || !code) {
			throw new ValidationError("Email and verification code are required");
		}
 
		// Look up the pending verification
		const authVerifications = (await import("../../db/schema/auth")).verifications;
		const records = await db
			.select()
			.from(authVerifications)
			.where(eq(authVerifications.identifier, `email-change:${user.id}`))
			.limit(1);
 
		const record = records[0];
		if (!record) {
			return error(c, "INVALID_OTP", "No pending email change. Please request a new code.", 400);
		}
 
		// Check expiry
		if (new Date() > record.expiresAt) {
			await db
				.delete(authVerifications)
				.where(eq(authVerifications.id, record.id));
			return error(c, "OTP_EXPIRED", "Verification code has expired. Please request a new one.", 400);
		}
 
		// Parse verification data safely
		let stored: { code: string; email: string; attempts?: number };
		try {
			stored = JSON.parse(record.value);
		} catch {
			await db.delete(authVerifications).where(eq(authVerifications.id, record.id));
			return error(c, "INVALID_OTP", "Verification data corrupted. Please request a new code.", 400);
		}
 
		// Verify OTP and email match (with brute-force protection)
		/* v8 ignore start -- defensive guard: always matches in tests */
		if (stored.code !== code || stored.email !== newEmail) {
			const attempts = (stored.attempts || 0) + 1;
			if (attempts >= 5) {
		/* v8 ignore stop */
				await db.delete(authVerifications).where(eq(authVerifications.id, record.id));
				return error(c, "TOO_MANY_ATTEMPTS", "Too many failed attempts. Please request a new code.", 400);
			}
			await db.update(authVerifications)
				.set({ value: JSON.stringify({ ...stored, attempts }) })
				.where(eq(authVerifications.id, record.id));
			return error(c, "INVALID_OTP", "Invalid verification code", 400);
		}
 
		// Check uniqueness again (race condition guard)
		const existing = await dal.users.findByEmail(newEmail);
		if (existing) {
			await db
				.delete(authVerifications)
				.where(eq(authVerifications.id, record.id));
			return error(
				c,
				"EMAIL_EXISTS",
				"This email is already in use by another account",
				409,
			);
		}
 
		// Update user's email and mark as verified
		const updated = await dal.users.update(user.id, {
			email: newEmail,
			emailVerified: true,
		});
		/* v8 ignore start -- defensive guard: user just authenticated */
		if (!updated) {
			return error(c, "NOT_FOUND", "User not found", 404);
		}
		/* v8 ignore stop */
 
		// Clean up verification record
		await db
			.delete(authVerifications)
			.where(eq(authVerifications.id, record.id));
 
		return success(c, {
			id: updated.id,
			name: updated.name,
			email: updated.email,
			phoneNumber: updated.phoneNumber,
			image: updated.image,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// POST /me/set-password - Set password for users who signed up without one (phone, magic link, social)
profile.post("/me/set-password", async (c) => {
	try {
		const user = c.get("user");
		if (!user) {
			return error(c, "UNAUTHORIZED", "Authentication required", 401);
		}
 
		const body = await c.req.json<{ newPassword: string }>();
		const newPassword = body.newPassword;
 
		if (!newPassword || newPassword.length < 8) {
			throw new ValidationError("Password must be at least 8 characters");
		}
		if (!/[A-Z]/.test(newPassword) || !/[a-z]/.test(newPassword) || !/\d/.test(newPassword) || !/[^A-Za-z0-9]/.test(newPassword)) {
			throw new ValidationError("Password must include uppercase, lowercase, number, and special character");
		}
 
		const db = c.get("db");
		const { accounts } = await import("../../db/schema/auth");
 
		// Check if user already has a credential account
		const existing = await db
			.select()
			.from(accounts)
			.where(eq(accounts.userId, user.id))
			.all();
 
		const hasCredential = existing.some(
			(a) => a.providerId === "credential" && a.password,
		);
 
		if (hasCredential) {
			return error(c, "ALREADY_HAS_PASSWORD", "You already have a password. Use change password instead.", 400);
		}
 
		// Hash and create credential account
		const { hashPassword } = await import("../../lib/password");
		const { generateId } = await import("../../lib/utils");
		const passwordHash = await hashPassword(newPassword);
 
		await db.insert(accounts).values({
			id: generateId(),
			userId: user.id,
			accountId: user.id,
			providerId: "credential",
			password: passwordHash,
		});
 
		return success(c, { status: true });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// PUT /me/preferences - Update user preferences (theme, etc.)
const VALID_THEMES = ["light", "dark", "system"];
 
profile.put("/me/preferences", async (c) => {
	try {
		const user = c.get("user");
		if (!user) {
			return error(c, "UNAUTHORIZED", "Authentication required", 401);
		}
 
		const body = await c.req.json<{
			themePreference?: string;
		}>();
		const dal = c.get("dal");
 
		const updates: Record<string, unknown> = {};
 
		if (body.themePreference !== undefined) {
			if (!VALID_THEMES.includes(body.themePreference)) {
				throw new ValidationError(
					"Invalid theme preference. Must be 'light', 'dark', or 'system'",
				);
			}
			updates.themePreference = body.themePreference;
		}
 
		if (Object.keys(updates).length === 0) {
			throw new ValidationError("No valid fields to update");
		}
 
		const updated = await dal.users.update(user.id, updates);
		if (!updated) {
			return error(c, "NOT_FOUND", "User not found", 404);
		}
 
		return success(c, {
			themePreference: updated.themePreference,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default profile;