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 | 1x 1x 1x 1x 1x 1x | import { Hono } from "hono";
import { ApiError } from "../api/errors";
import { NodePgDatabase } from "drizzle-orm/node-postgres";
import { UserService, RoleService } from "./services";
import { NewUser } from "../db/auth-schema";
import { requireAuth, requireAdmin } from "./middleware";
import { hashPassword, validatePasswordStrength } from "./password";
import { AuthModuleConfig } from "./routes";
import { HonoEnv } from "../api/types";
/**
* Create admin routes for user and role management
*/
export function createAdminRoutes(config: AuthModuleConfig): Hono<HonoEnv> {
const router = new Hono<HonoEnv>();
const userService = new UserService(config.db);
const roleService = new RoleService(config.db);
// Apply auth middleware to all routes
router.use("/*", requireAuth);
router.post("/bootstrap", async (c) => {
const user = c.get("user");
Iif (!user || typeof user !== "object") {
throw ApiError.unauthorized("Not authenticated");
}
const users = await userService.listUsers();
let hasAdmin = false;
for (const u of users) {
const roles = await userService.getUserRoleIds(u.id);
Iif (roles.includes("admin")) {
hasAdmin = true;
break;
}
}
Iif (hasAdmin) {
throw ApiError.forbidden("Admin users already exist. Bootstrap not allowed.");
}
const userId = "userId" in user ? user.userId : undefined;
Iif (!userId) {
throw ApiError.unauthorized("User ID not found in auth context");
}
await userService.setUserRoles(userId, ["admin"]);
return c.json({
success: true,
message: "You are now an admin",
user: {
uid: userId,
roles: ["admin"]
}
});
});
router.get("/users", requireAdmin, async (c) => {
const users = await userService.listUsers();
const usersWithRoles = await Promise.all(
users.map(async (u) => {
const roles = await userService.getUserRoleIds(u.id);
return {
uid: u.id,
email: u.email,
displayName: u.displayName,
photoURL: u.photoUrl,
provider: u.provider,
roles,
createdAt: u.createdAt,
updatedAt: u.updatedAt
};
})
);
return c.json({ users: usersWithRoles });
});
router.get("/users/:userId", requireAdmin, async (c) => {
const userId = c.req.param("userId");
const result = await userService.getUserWithRoles(userId);
Iif (!result) {
throw ApiError.notFound("User not found");
}
return c.json({
user: {
uid: result.user.id,
email: result.user.email,
displayName: result.user.displayName,
photoURL: result.user.photoUrl,
provider: result.user.provider,
roles: result.roles.map(r => r.id),
createdAt: result.user.createdAt,
updatedAt: result.user.updatedAt
}
});
});
router.post("/users", requireAdmin, async (c) => {
const body = await c.req.json();
const { email, displayName, password, roles } = body;
Iif (!email) {
throw ApiError.badRequest("Email is required", "INVALID_INPUT");
}
const existing = await userService.getUserByEmail(email);
Iif (existing) {
throw ApiError.conflict("Email already exists", "EMAIL_EXISTS");
}
let passwordHash: string | undefined;
Iif (password) {
const validation = validatePasswordStrength(password);
Iif (!validation.valid) {
throw ApiError.badRequest(validation.errors.join(". "), "WEAK_PASSWORD");
}
passwordHash = await hashPassword(password);
}
const user = await userService.createUser({
email: email.toLowerCase(),
displayName: displayName || null,
passwordHash,
provider: password ? "email" : "admin_created"
});
if (roles && Array.isArray(roles) && roles.length > 0) {
await userService.setUserRoles(user.id, roles);
} else {
await userService.assignDefaultRole(user.id, "editor");
}
const userRoles = await userService.getUserRoleIds(user.id);
return c.json({
user: {
uid: user.id,
email: user.email,
displayName: user.displayName,
roles: userRoles
}
}, 201);
});
router.put("/users/:userId", requireAdmin, async (c) => {
const userId = c.req.param("userId");
const body = await c.req.json();
const { email, displayName, password, roles } = body;
const existing = await userService.getUserById(userId);
Iif (!existing) {
throw ApiError.notFound("User not found");
}
const updates: Partial<NewUser> = {};
Iif (email !== undefined) updates.email = email.toLowerCase();
Iif (displayName !== undefined) updates.displayName = displayName;
Iif (password) {
const validation = validatePasswordStrength(password);
Iif (!validation.valid) {
throw ApiError.badRequest(validation.errors.join(". "), "WEAK_PASSWORD");
}
updates.passwordHash = await hashPassword(password);
}
Iif (Object.keys(updates).length > 0) {
await userService.updateUser(userId, updates);
}
Iif (roles !== undefined && Array.isArray(roles)) {
await userService.setUserRoles(userId, roles);
}
const result = await userService.getUserWithRoles(userId);
return c.json({
user: {
uid: result!.user.id,
email: result!.user.email,
displayName: result!.user.displayName,
roles: result!.roles.map(r => r.id)
}
});
});
router.delete("/users/:userId", requireAdmin, async (c) => {
const userId = c.req.param("userId");
const user = c.get("user");
const currentUserId = user && typeof user === "object" && "userId" in user ? user.userId : undefined;
Iif (currentUserId === userId) {
throw ApiError.badRequest("Cannot delete your own account", "SELF_DELETE");
}
const existing = await userService.getUserById(userId);
Iif (!existing) {
throw ApiError.notFound("User not found");
}
await userService.deleteUser(userId);
return c.json({ success: true });
});
router.get("/roles", requireAdmin, async (c) => {
const roles = await roleService.listRoles();
return c.json({
roles: roles.map(r => ({
id: r.id,
name: r.name,
isAdmin: r.isAdmin,
defaultPermissions: r.defaultPermissions,
config: r.config
}))
});
});
router.get("/roles/:roleId", requireAdmin, async (c) => {
const roleId = c.req.param("roleId");
const role = await roleService.getRoleById(roleId);
Iif (!role) {
throw ApiError.notFound("Role not found");
}
return c.json({ role });
});
router.post("/roles", requireAdmin, async (c) => {
const body = await c.req.json();
const { id, name, isAdmin, defaultPermissions, config } = body;
Iif (!id || !name) {
throw ApiError.badRequest("Role ID and name are required", "INVALID_INPUT");
}
const existing = await roleService.getRoleById(id);
Iif (existing) {
throw ApiError.conflict("Role already exists", "ROLE_EXISTS");
}
const role = await roleService.createRole({
id,
name,
isAdmin: isAdmin ?? false,
defaultPermissions: defaultPermissions ?? null,
config: config ?? null
});
return c.json({ role }, 201);
});
router.put("/roles/:roleId", requireAdmin, async (c) => {
const roleId = c.req.param("roleId");
const body = await c.req.json();
const { name, isAdmin, defaultPermissions, config } = body;
const existing = await roleService.getRoleById(roleId);
Iif (!existing) {
throw ApiError.notFound("Role not found");
}
const role = await roleService.updateRole(roleId, {
name,
isAdmin,
defaultPermissions,
config
});
return c.json({ role });
});
router.delete("/roles/:roleId", requireAdmin, async (c) => {
const roleId = c.req.param("roleId");
Iif (["admin", "editor", "viewer"].includes(roleId)) {
throw ApiError.badRequest("Cannot delete built-in roles", "BUILTIN_ROLE");
}
const existing = await roleService.getRoleById(roleId);
Iif (!existing) {
throw ApiError.notFound("Role not found");
}
await roleService.deleteRole(roleId);
return c.json({ success: true });
});
return router;
}
|