All files / routes/admin users.routes.ts

100% Statements 124/124
98.61% Branches 71/72
100% Functions 9/9
100% Lines 124/124

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                                            1x     1x 11x   11x               11x 11x 1x   10x 10x 1x   9x 1x   8x 1x               7x 11x 11x 1x       6x 6x 1x       5x 5x     5x       5x 5x               2x 2x 1x   1x       3x           3x       1x 2x   2x 2x 2x 2x   2x         2x               1x 2x 2x   2x 2x 1x     1x       1x 4x 4x   4x             4x 4x 1x       3x 1x               2x             2x       1x 4x 4x   4x   4x 1x               3x 3x 1x         2x   2x 2x 1x     1x       1x 3x 3x 3x     3x 1x               2x 2x 1x     1x       1x 4x 4x 4x   4x           4x 1x     3x 3x 1x     2x         2x 1x     1x       1x 6x 6x   6x           6x 6x 1x       5x 2x 1x                   3x 1x             2x 1x       2x               2x 2x   2x       1x 2x 2x 2x   2x 2x 1x       1x 1x   1x        
// Admin Routes - User Management
import { Hono } from "hono";
import type { Dal } from "../../dal";
import type { Services } from "../../services";
import { success, error } from "../../lib/response";
import { generateId } from "../../lib/utils";
import { PRO_ROLES, PLATFORM_ROLES } from "../../db/schema";
import { createDualCache } from "../../lib/cache";
import { invalidateUserRoles } from "../../lib/role-cache";
import { hashPassword } from "../../lib/password";
import { normalizeToE164 } from "@interioring/utils/validation/phone";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
	};
};
 
const users = new Hono<Env>();
 
// Create new user
users.post("/", async (c) => {
	const dal = c.get("dal");
 
	const body = await c.req.json<{
		name: string;
		email: string;
		password: string;
		phoneNumber?: string;
	}>();
 
	// Validate required fields
	const trimmedName = body.name?.trim();
	if (!trimmedName) {
		return error(c, "INVALID_NAME", "Name is required", 400);
	}
	const nameLetters = trimmedName.match(/\p{L}/gu);
	if (!nameLetters || nameLetters.length < 2 || !/^[\p{L}]+(?:[ '-][\p{L}]+)*$/u.test(trimmedName)) {
		return error(c, "INVALID_NAME", "Name must contain at least 2 letters and only letters, spaces, hyphens, or apostrophes", 400);
	}
	if (!body.email?.trim()) {
		return error(c, "INVALID_EMAIL", "Email is required", 400);
	}
	if (!body.password || body.password.length < 8) {
		return error(
			c,
			"INVALID_PASSWORD",
			"Password must be at least 8 characters",
			400,
		);
	}
	// Validate and normalize phone number if provided.
	const trimmedPhone = body.phoneNumber?.trim();
	const normalizedPhone = trimmedPhone ? normalizeToE164(trimmedPhone) : undefined;
	if (trimmedPhone && !normalizedPhone) {
		return error(c, "INVALID_PHONE", "Enter a valid Indian phone number", 400);
	}
 
	// Check if email already exists
	const existingUser = await dal.users.findByEmail(body.email);
	if (existingUser) {
		return error(c, "EMAIL_EXISTS", "Email already in use", 400);
	}
 
	// Generate IDs
	const userId = generateId();
	const accountId = generateId();
 
	// Hash password
	const hashedPassword = await hashPassword(body.password);
 
	// Create user
	let user: Awaited<ReturnType<typeof dal.users.create>>;
	try {
		user = await dal.users.create({
			id: userId,
			name: trimmedName,
			email: body.email.trim().toLowerCase(),
			emailVerified: true, // Admin-created users are verified
			phoneNumber: normalizedPhone ?? undefined,
		});
	} catch (err) {
		const msg = err instanceof Error ? err.message : "";
		if (msg.includes("UNIQUE constraint") && msg.toLowerCase().includes("phone")) {
			return error(c, "PHONE_EXISTS", "Phone number is already in use", 400);
		}
		throw err;
	}
 
	// Create account for password
	await dal.users.createAccount({
		id: accountId,
		userId,
		hashedPassword,
	});
 
	return success(c, user, 201);
});
 
// List all users
users.get("/", async (c) => {
	const dal = c.get("dal");
 
	const { search, limit, offset } = c.req.query();
	const filters = { search };
	const limitNum = limit ? parseInt(limit, 10) : 50;
	const offsetNum = offset ? parseInt(offset, 10) : 0;
 
	const [usersList, total] = await Promise.all([
		dal.users.findAll(filters, offsetNum, limitNum),
		dal.users.count(filters),
	]);
 
	return success(c, usersList, 200, {
		total,
		limit: limitNum,
		offset: offsetNum,
	});
});
 
// Get single user with roles
users.get("/:id", async (c) => {
	const dal = c.get("dal");
	const userId = c.req.param("id");
 
	const result = await dal.users.getWithRoles(userId);
	if (!result) {
		return error(c, "NOT_FOUND", "User not found", 404);
	}
 
	return success(c, result);
});
 
// Update user
users.put("/:id", async (c) => {
	const dal = c.get("dal");
	const userId = c.req.param("id");
 
	const body = await c.req.json<{
		name?: string;
		email?: string;
		emailVerified?: boolean;
		phoneNumber?: string;
	}>();
 
	const existingUser = await dal.users.findById(userId);
	if (!existingUser) {
		return error(c, "NOT_FOUND", "User not found", 404);
	}
 
	// If email is being changed, check for uniqueness
	if (body.email && body.email !== existingUser.email) {
		const emailExists = await dal.users.findByEmail(body.email);
		/* v8 ignore start -- defensive guard: duplicate email unlikely in test */
		if (emailExists) {
			return error(c, "EMAIL_EXISTS", "Email already in use", 400);
		}
		/* v8 ignore stop */
	}
 
	const updated = await dal.users.update(userId, {
		name: body.name,
		email: body.email,
		emailVerified: body.emailVerified,
		phoneNumber: body.phoneNumber,
	});
 
	return success(c, updated);
});
 
// Reset user password (admin sets a new password)
users.post("/:id/reset-password", async (c) => {
	const dal = c.get("dal");
	const userId = c.req.param("id");
 
	const body = await c.req.json<{ password: string }>();
 
	if (!body.password || body.password.length < 8) {
		return error(
			c,
			"INVALID_PASSWORD",
			"Password must be at least 8 characters",
			400,
		);
	}
 
	const user = await dal.users.findById(userId);
	if (!user) {
		return error(c, "NOT_FOUND", "User not found", 404);
	}
 
	// Hash the password using the same method Better Auth uses
	// Better Auth uses bcrypt-like hashing via Web Crypto API
	const hashedPassword = await hashPassword(body.password);
 
	const success_ = await dal.users.updatePassword(userId, hashedPassword);
	if (!success_) {
		return error(c, "UPDATE_FAILED", "Failed to update password", 500);
	}
 
	return success(c, { message: "Password updated successfully" });
});
 
// Delete user
users.delete("/:id", async (c) => {
	const dal = c.get("dal");
	const userId = c.req.param("id");
	const currentUser = c.get("user");
 
	// Prevent deleting yourself
	if (currentUser?.id === userId) {
		return error(
			c,
			"CANNOT_DELETE_SELF",
			"Cannot delete your own account",
			400,
		);
	}
 
	const deleted = await dal.users.delete(userId);
	if (!deleted) {
		return error(c, "NOT_FOUND", "User not found", 404);
	}
 
	return success(c, { message: "User deleted successfully" });
});
 
// Ban/unban user
users.post("/:id/ban", async (c) => {
	const dal = c.get("dal");
	const userId = c.req.param("id");
	const currentUser = c.get("user");
 
	const body = await c.req.json<{
		banned: boolean;
		banReason?: string;
	}>();
 
	// Prevent banning yourself
	if (currentUser?.id === userId) {
		return error(c, "CANNOT_BAN_SELF", "Cannot ban your own account", 400);
	}
 
	const user = await dal.users.findById(userId);
	if (!user) {
		return error(c, "NOT_FOUND", "User not found", 404);
	}
 
	const updated = await dal.users.setBanned(
		userId,
		body.banned,
		body.banReason,
	);
	if (!updated) {
		return error(c, "UPDATE_FAILED", "Failed to update user", 500);
	}
 
	return success(c, updated);
});
 
// Add role to user
users.post("/:id/roles", async (c) => {
	const dal = c.get("dal");
	const userId = c.req.param("id");
 
	const body = await c.req.json<{
		tenantType: "platform" | "pro";
		tenantId?: string;
		role: string;
	}>();
 
	const user = await dal.users.findById(userId);
	if (!user) {
		return error(c, "NOT_FOUND", "User not found", 404);
	}
 
	// Validate role based on tenant type
	if (body.tenantType === "platform") {
		if (!(PLATFORM_ROLES as readonly string[]).includes(body.role)) {
			return error(
				c,
				"INVALID_ROLE",
				`Invalid platform role: ${body.role}`,
				400,
			);
		}
	/* v8 ignore start -- V8 artifact: else-if always matches */
	} else if (body.tenantType === "pro") {
	/* v8 ignore stop */
		if (!body.tenantId) {
			return error(
				c,
				"MISSING_TENANT",
				"Pro ID required for pro roles",
				400,
			);
		}
		if (!(PRO_ROLES as readonly string[]).includes(body.role)) {
			return error(c, "INVALID_ROLE", `Invalid pro role: ${body.role}`, 400);
		}
	}
 
	const role = await dal.userTenantRoles.create({
		userId,
		tenantType: body.tenantType,
		tenantId: body.tenantId || null,
		role: body.role,
	});
 
	// Invalidate cached roles for the affected user
	const cache = createDualCache(c.env.KV_CACHE);
	await invalidateUserRoles(cache, userId);
 
	return success(c, role, 201);
});
 
// Remove role from user
users.delete("/:id/roles/:roleId", async (c) => {
	const dal = c.get("dal");
	const userId = c.req.param("id");
	const roleId = parseInt(c.req.param("roleId"), 10);
 
	const deleted = await dal.userTenantRoles.delete(roleId);
	if (!deleted) {
		return error(c, "NOT_FOUND", "Role not found", 404);
	}
 
	// Invalidate cached roles for the affected user
	const cache = createDualCache(c.env.KV_CACHE);
	await invalidateUserRoles(cache, userId);
 
	return success(c, { message: "Role removed successfully" });
});
 
export default users;