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 | 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 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 { eq } from "drizzle-orm";
import { Hono } from "hono";
import type { Dal } from "../../dal";
import type { getDb } from "../../db";
import { ValidationError } from "../../lib/errors";
import { validateUploadedFile } from "../../lib/file-validation";
import { error, handleError, success } from "../../lib/response";
import type { Services } from "../../services";
import credentialChangeRoutes from "./profile/credential-change.routes";
const INDIAN_PHONE_REGEX = /^[6-9]\d{9}$/;
type Env = {
Bindings: CloudflareBindings;
Variables: {
user: { id: string; name: string; email: string } | null;
session: unknown;
dal: Dal;
services: Services;
db: ReturnType<typeof getDb>;
};
};
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);
}
});
// Phone/email change endpoints (4 OTP-based routes) live in
// profile/credential-change.routes.ts. Mounted at "/" so URL paths unchanged.
profile.route("/", credentialChangeRoutes);
// 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;
|