Add local user authentication and admin capabilities
Implement local user authentication with password hashing, add admin roles for user management and audit log viewing, and introduce audit logging for critical actions. Replit-Commit-Author: Agent Replit-Commit-Session-Id: 776963d0-f75d-42e2-a57b-cc36bdff8495 Replit-Commit-Checkpoint-Type: full_checkpoint Replit-Commit-Event-Id: 832a44ff-12ae-4096-8a0d-666ec083d536 Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/0683fb79-a27c-485c-9333-5f4b288c4567/776963d0-f75d-42e2-a57b-cc36bdff8495/1p7jhzu Replit-Helium-Checkpoint-Created: true
This commit is contained in:
@@ -12,6 +12,7 @@
|
||||
"dependencies": {
|
||||
"@workspace/api-zod": "workspace:*",
|
||||
"@workspace/db": "workspace:*",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"connect-pg-simple": "^10.0.0",
|
||||
"cookie-parser": "^1.4.7",
|
||||
"cors": "^2.8.6",
|
||||
@@ -23,6 +24,7 @@
|
||||
"pino-http": "^10.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcryptjs": "^3.0.0",
|
||||
"@types/connect-pg-simple": "^7.0.3",
|
||||
"@types/cookie-parser": "^1.4.10",
|
||||
"@types/cors": "^2.8.19",
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import app from "./app";
|
||||
import { logger } from "./lib/logger";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { db, usersTable } from "@workspace/db";
|
||||
import { sql } from "drizzle-orm";
|
||||
|
||||
const rawPort = process.env["PORT"];
|
||||
|
||||
@@ -15,6 +18,30 @@ if (Number.isNaN(port) || port <= 0) {
|
||||
throw new Error(`Invalid PORT value: "${rawPort}"`);
|
||||
}
|
||||
|
||||
async function seedAdminUser(): Promise<void> {
|
||||
try {
|
||||
const [row] = await db.select({ count: sql<number>`count(*)::int` }).from(usersTable);
|
||||
if ((row?.count ?? 0) > 0) return;
|
||||
|
||||
const adminUsername = process.env.LOCAL_ADMIN_USERNAME || "admin";
|
||||
const adminPassword = process.env.LOCAL_ADMIN_PASSWORD;
|
||||
if (!adminPassword) {
|
||||
logger.warn("LOCAL_ADMIN_PASSWORD is not set — skipping admin seed. Set it to enable local login.");
|
||||
return;
|
||||
}
|
||||
|
||||
const passwordHash = await bcrypt.hash(adminPassword, 10);
|
||||
await db.insert(usersTable).values({
|
||||
username: adminUsername,
|
||||
passwordHash,
|
||||
role: "admin",
|
||||
});
|
||||
logger.info({ username: adminUsername }, "Admin user created");
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Failed to seed admin user");
|
||||
}
|
||||
}
|
||||
|
||||
app.listen(port, (err) => {
|
||||
if (err) {
|
||||
logger.error({ err }, "Error listening on port");
|
||||
@@ -22,4 +49,5 @@ app.listen(port, (err) => {
|
||||
}
|
||||
|
||||
logger.info({ port }, "Server listening");
|
||||
seedAdminUser();
|
||||
});
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { db, auditLogsTable } from "@workspace/db";
|
||||
import { type Request } from "express";
|
||||
|
||||
export async function writeAuditLog(
|
||||
req: Request,
|
||||
entityType: string,
|
||||
entityId: number | null,
|
||||
action: string,
|
||||
changes?: Record<string, unknown>,
|
||||
): Promise<void> {
|
||||
const user = req.session.user;
|
||||
if (!user) return;
|
||||
const username = user.preferred_username || user.name || user.sub;
|
||||
await db.insert(auditLogsTable).values({
|
||||
entityType,
|
||||
entityId,
|
||||
action,
|
||||
userId: user.sub,
|
||||
username,
|
||||
changes: changes ? JSON.stringify(changes) : null,
|
||||
});
|
||||
}
|
||||
@@ -7,3 +7,15 @@ export function requireAuth(req: Request, res: Response, next: NextFunction): vo
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
export function requireAdmin(req: Request, res: Response, next: NextFunction): void {
|
||||
if (!req.session.user) {
|
||||
res.status(401).json({ error: "Authentication required" });
|
||||
return;
|
||||
}
|
||||
if (req.session.user.role !== "admin") {
|
||||
res.status(403).json({ error: "Admin access required" });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Router, type IRouter } from "express";
|
||||
import { eq, desc, and } from "drizzle-orm";
|
||||
import { db, auditLogsTable } from "@workspace/db";
|
||||
import { requireAdmin } from "../middleware/auth";
|
||||
|
||||
const router: IRouter = Router();
|
||||
|
||||
router.get("/audit-logs", requireAdmin, async (req, res): Promise<void> => {
|
||||
const { entityType, entityId, limit } = req.query;
|
||||
const maxLimit = Math.min(parseInt(limit as string) || 100, 500);
|
||||
|
||||
const conditions: ReturnType<typeof eq>[] = [];
|
||||
if (entityType && typeof entityType === "string") {
|
||||
conditions.push(eq(auditLogsTable.entityType, entityType));
|
||||
}
|
||||
if (entityId) {
|
||||
const id = parseInt(entityId as string, 10);
|
||||
if (!isNaN(id)) {
|
||||
conditions.push(eq(auditLogsTable.entityId, id));
|
||||
}
|
||||
}
|
||||
|
||||
const logs = await db
|
||||
.select()
|
||||
.from(auditLogsTable)
|
||||
.where(conditions.length > 0 ? and(...conditions) : undefined)
|
||||
.orderBy(desc(auditLogsTable.createdAt))
|
||||
.limit(maxLimit);
|
||||
|
||||
res.json(logs);
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -1,11 +1,23 @@
|
||||
import { Router, type IRouter, type Request } from "express";
|
||||
import { Issuer, generators, type Client } from "openid-client";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { db, usersTable } from "@workspace/db";
|
||||
import { logger } from "../lib/logger";
|
||||
|
||||
const router: IRouter = Router();
|
||||
|
||||
let cachedClient: Client | null = null;
|
||||
|
||||
function isOidcConfigured(): boolean {
|
||||
return !!(
|
||||
process.env.KEYCLOAK_URL &&
|
||||
process.env.KEYCLOAK_REALM &&
|
||||
process.env.KEYCLOAK_CLIENT_ID &&
|
||||
process.env.KEYCLOAK_CLIENT_SECRET
|
||||
);
|
||||
}
|
||||
|
||||
function getBaseUrl(req: Request): string {
|
||||
if (process.env.APP_URL) return process.env.APP_URL;
|
||||
const host = req.get("x-forwarded-host") || req.get("host") || "localhost";
|
||||
@@ -40,10 +52,62 @@ async function getClient(): Promise<Client | null> {
|
||||
}
|
||||
}
|
||||
|
||||
router.get("/auth/mode", (_req, res): void => {
|
||||
res.json({ mode: isOidcConfigured() ? "oidc" : "local" });
|
||||
});
|
||||
|
||||
router.post("/auth/login", async (req, res): Promise<void> => {
|
||||
if (isOidcConfigured()) {
|
||||
res.status(400).json({ error: "Use OIDC login when Keycloak is configured." });
|
||||
return;
|
||||
}
|
||||
|
||||
const { username, password } = req.body;
|
||||
if (!username || !password) {
|
||||
res.status(400).json({ error: "username and password are required" });
|
||||
return;
|
||||
}
|
||||
|
||||
const [user] = await db
|
||||
.select()
|
||||
.from(usersTable)
|
||||
.where(eq(usersTable.username, String(username)))
|
||||
.limit(1);
|
||||
|
||||
if (!user) {
|
||||
res.status(401).json({ error: "Invalid username or password" });
|
||||
return;
|
||||
}
|
||||
|
||||
const valid = await bcrypt.compare(String(password), user.passwordHash);
|
||||
if (!valid) {
|
||||
res.status(401).json({ error: "Invalid username or password" });
|
||||
return;
|
||||
}
|
||||
|
||||
req.session.user = {
|
||||
sub: String(user.id),
|
||||
name: user.username,
|
||||
preferred_username: user.username,
|
||||
email: user.email ?? undefined,
|
||||
role: (user.role as "admin" | "user") ?? "user",
|
||||
isLocal: true,
|
||||
};
|
||||
|
||||
res.json({
|
||||
sub: String(user.id),
|
||||
email: user.email ?? null,
|
||||
name: user.username,
|
||||
preferredUsername: user.username,
|
||||
role: user.role,
|
||||
isLocal: true,
|
||||
});
|
||||
});
|
||||
|
||||
router.get("/auth/login", async (req, res): Promise<void> => {
|
||||
const client = await getClient();
|
||||
if (!client) {
|
||||
res.status(503).json({ error: "Keycloak is not configured. Set KEYCLOAK_URL, KEYCLOAK_REALM, KEYCLOAK_CLIENT_ID, KEYCLOAK_CLIENT_SECRET." });
|
||||
res.status(503).json({ error: "Keycloak is not configured." });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -94,6 +158,8 @@ router.get("/auth/callback", async (req, res): Promise<void> => {
|
||||
email: typeof userinfo.email === "string" ? userinfo.email : undefined,
|
||||
name: typeof userinfo.name === "string" ? userinfo.name : undefined,
|
||||
preferred_username: typeof userinfo.preferred_username === "string" ? userinfo.preferred_username : undefined,
|
||||
role: "user",
|
||||
isLocal: false,
|
||||
};
|
||||
delete req.session.codeVerifier;
|
||||
|
||||
@@ -108,7 +174,6 @@ router.get("/auth/callback", async (req, res): Promise<void> => {
|
||||
});
|
||||
|
||||
router.get("/auth/logout", async (req, res): Promise<void> => {
|
||||
const user = req.session.user;
|
||||
req.session.destroy(() => {});
|
||||
|
||||
const client = await getClient();
|
||||
@@ -132,6 +197,8 @@ router.get("/auth/me", async (req, res): Promise<void> => {
|
||||
email: u.email ?? null,
|
||||
name: u.name ?? null,
|
||||
preferredUsername: u.preferred_username ?? null,
|
||||
role: u.role ?? "user",
|
||||
isLocal: u.isLocal ?? false,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ import toolsRouter from "./tools";
|
||||
import ratingsRouter from "./ratings";
|
||||
import analyticsRouter from "./analytics";
|
||||
import authRouter from "./auth";
|
||||
import usersRouter from "./users";
|
||||
import auditRouter from "./audit";
|
||||
|
||||
const router: IRouter = Router();
|
||||
|
||||
@@ -12,5 +14,7 @@ router.use(healthRouter);
|
||||
router.use(toolsRouter);
|
||||
router.use(ratingsRouter);
|
||||
router.use(analyticsRouter);
|
||||
router.use(usersRouter);
|
||||
router.use(auditRouter);
|
||||
|
||||
export default router;
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
DeleteToolParams,
|
||||
} from "@workspace/api-zod";
|
||||
import { requireAuth } from "../middleware/auth";
|
||||
import { writeAuditLog } from "../lib/audit";
|
||||
|
||||
const router: IRouter = Router();
|
||||
|
||||
@@ -27,6 +28,13 @@ function buildToolWithStats(tool: typeof toolsTable.$inferSelect, ratings: { use
|
||||
return { ...tool, ratingCount, avgUsefulness, avgUsability, avgCombined };
|
||||
}
|
||||
|
||||
function canEditTool(req: import("express").Request, tool: { createdBy: string | null }): boolean {
|
||||
const user = req.session.user;
|
||||
if (!user) return false;
|
||||
if (user.role === "admin") return true;
|
||||
return tool.createdBy === user.sub || tool.createdBy === user.preferred_username;
|
||||
}
|
||||
|
||||
router.get("/tools", async (req, res): Promise<void> => {
|
||||
const parsed = ListToolsQueryParams.safeParse(req.query);
|
||||
if (!parsed.success) {
|
||||
@@ -79,16 +87,21 @@ router.post("/tools", requireAuth, async (req, res): Promise<void> => {
|
||||
return;
|
||||
}
|
||||
|
||||
const user = req.session.user!;
|
||||
const createdBy = user.preferred_username || user.name || user.sub;
|
||||
|
||||
const [tool] = await db.insert(toolsTable).values({
|
||||
name: parsed.data.name,
|
||||
description: parsed.data.description,
|
||||
category: parsed.data.category,
|
||||
websiteUrl: parsed.data.websiteUrl ?? null,
|
||||
iconUrl: parsed.data.iconUrl ?? null,
|
||||
createdBy,
|
||||
features: parsed.data.features ?? [],
|
||||
tags: parsed.data.tags ?? [],
|
||||
}).returning();
|
||||
|
||||
await writeAuditLog(req, "tool", tool.id, "create", { name: tool.name, category: tool.category });
|
||||
res.status(201).json(tool);
|
||||
});
|
||||
|
||||
@@ -120,6 +133,21 @@ router.patch("/tools/:id", requireAuth, async (req, res): Promise<void> => {
|
||||
return;
|
||||
}
|
||||
|
||||
const [existing] = await db
|
||||
.select()
|
||||
.from(toolsTable)
|
||||
.where(eq(toolsTable.id, params.data.id));
|
||||
|
||||
if (!existing) {
|
||||
res.status(404).json({ error: "Tool not found" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!canEditTool(req, existing)) {
|
||||
res.status(403).json({ error: "Not allowed to edit this tool" });
|
||||
return;
|
||||
}
|
||||
|
||||
const parsed = UpdateToolBody.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: parsed.error.message });
|
||||
@@ -127,13 +155,28 @@ router.patch("/tools/:id", requireAuth, async (req, res): Promise<void> => {
|
||||
}
|
||||
|
||||
const updateData: Record<string, unknown> = {};
|
||||
if (parsed.data.name !== undefined) updateData.name = parsed.data.name;
|
||||
if (parsed.data.description !== undefined) updateData.description = parsed.data.description;
|
||||
if (parsed.data.category !== undefined) updateData.category = parsed.data.category;
|
||||
if (parsed.data.websiteUrl !== undefined) updateData.websiteUrl = parsed.data.websiteUrl;
|
||||
if (parsed.data.iconUrl !== undefined) updateData.iconUrl = parsed.data.iconUrl;
|
||||
if (parsed.data.features !== undefined) updateData.features = parsed.data.features;
|
||||
if (parsed.data.tags !== undefined) updateData.tags = parsed.data.tags;
|
||||
const changes: Record<string, { from: unknown; to: unknown }> = {};
|
||||
|
||||
function track(key: keyof typeof existing, value: unknown) {
|
||||
if (value !== undefined && value !== existing[key]) {
|
||||
changes[key] = { from: existing[key], to: value };
|
||||
(updateData as Record<string, unknown>)[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
track("name", parsed.data.name);
|
||||
track("description", parsed.data.description);
|
||||
track("category", parsed.data.category);
|
||||
track("websiteUrl", parsed.data.websiteUrl);
|
||||
track("iconUrl", parsed.data.iconUrl);
|
||||
if (parsed.data.features !== undefined) {
|
||||
changes["features"] = { from: existing.features, to: parsed.data.features };
|
||||
updateData.features = parsed.data.features;
|
||||
}
|
||||
if (parsed.data.tags !== undefined) {
|
||||
changes["tags"] = { from: existing.tags, to: parsed.data.tags };
|
||||
updateData.tags = parsed.data.tags;
|
||||
}
|
||||
|
||||
const [tool] = await db
|
||||
.update(toolsTable)
|
||||
@@ -146,6 +189,10 @@ router.patch("/tools/:id", requireAuth, async (req, res): Promise<void> => {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Object.keys(changes).length > 0) {
|
||||
await writeAuditLog(req, "tool", tool.id, "update", changes);
|
||||
}
|
||||
|
||||
res.json(tool);
|
||||
});
|
||||
|
||||
@@ -156,12 +203,23 @@ router.delete("/tools/:id", requireAuth, async (req, res): Promise<void> => {
|
||||
return;
|
||||
}
|
||||
|
||||
const [tool] = await db.delete(toolsTable).where(eq(toolsTable.id, params.data.id)).returning();
|
||||
if (!tool) {
|
||||
const [existing] = await db
|
||||
.select()
|
||||
.from(toolsTable)
|
||||
.where(eq(toolsTable.id, params.data.id));
|
||||
|
||||
if (!existing) {
|
||||
res.status(404).json({ error: "Tool not found" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!canEditTool(req, existing)) {
|
||||
res.status(403).json({ error: "Not allowed to delete this tool" });
|
||||
return;
|
||||
}
|
||||
|
||||
await writeAuditLog(req, "tool", existing.id, "delete", { name: existing.name });
|
||||
await db.delete(toolsTable).where(eq(toolsTable.id, params.data.id));
|
||||
res.sendStatus(204);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { Router, type IRouter } from "express";
|
||||
import { eq } from "drizzle-orm";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { db, usersTable } from "@workspace/db";
|
||||
import { requireAdmin } from "../middleware/auth";
|
||||
import { writeAuditLog } from "../lib/audit";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
const router: IRouter = Router();
|
||||
|
||||
const UserCreateSchema = z.object({
|
||||
username: z.string().min(2),
|
||||
password: z.string().min(6),
|
||||
email: z.string().optional(),
|
||||
role: z.enum(["admin", "user"]).optional().default("user"),
|
||||
});
|
||||
|
||||
const UserRoleUpdateSchema = z.object({
|
||||
role: z.enum(["admin", "user"]),
|
||||
});
|
||||
|
||||
router.get("/users", requireAdmin, async (req, res): Promise<void> => {
|
||||
const users = await db
|
||||
.select({
|
||||
id: usersTable.id,
|
||||
username: usersTable.username,
|
||||
email: usersTable.email,
|
||||
role: usersTable.role,
|
||||
createdAt: usersTable.createdAt,
|
||||
})
|
||||
.from(usersTable)
|
||||
.orderBy(usersTable.createdAt);
|
||||
res.json(users);
|
||||
});
|
||||
|
||||
router.post("/users", requireAdmin, async (req, res): Promise<void> => {
|
||||
const parsed = UserCreateSchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: parsed.error.message });
|
||||
return;
|
||||
}
|
||||
|
||||
const existing = await db
|
||||
.select({ id: usersTable.id })
|
||||
.from(usersTable)
|
||||
.where(eq(usersTable.username, parsed.data.username))
|
||||
.limit(1);
|
||||
|
||||
if (existing.length > 0) {
|
||||
res.status(409).json({ error: "Username already exists" });
|
||||
return;
|
||||
}
|
||||
|
||||
const passwordHash = await bcrypt.hash(parsed.data.password, 10);
|
||||
const [user] = await db
|
||||
.insert(usersTable)
|
||||
.values({
|
||||
username: parsed.data.username,
|
||||
passwordHash,
|
||||
email: parsed.data.email ?? null,
|
||||
role: parsed.data.role ?? "user",
|
||||
})
|
||||
.returning({
|
||||
id: usersTable.id,
|
||||
username: usersTable.username,
|
||||
email: usersTable.email,
|
||||
role: usersTable.role,
|
||||
createdAt: usersTable.createdAt,
|
||||
});
|
||||
|
||||
await writeAuditLog(req, "user", user.id, "create", { username: user.username, role: user.role });
|
||||
res.status(201).json(user);
|
||||
});
|
||||
|
||||
router.patch("/users/:id", requireAdmin, async (req, res): Promise<void> => {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
if (isNaN(id)) {
|
||||
res.status(400).json({ error: "Invalid user id" });
|
||||
return;
|
||||
}
|
||||
|
||||
const parsed = UserRoleUpdateSchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: parsed.error.message });
|
||||
return;
|
||||
}
|
||||
|
||||
const [user] = await db
|
||||
.update(usersTable)
|
||||
.set({ role: parsed.data.role })
|
||||
.where(eq(usersTable.id, id))
|
||||
.returning({
|
||||
id: usersTable.id,
|
||||
username: usersTable.username,
|
||||
email: usersTable.email,
|
||||
role: usersTable.role,
|
||||
createdAt: usersTable.createdAt,
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
res.status(404).json({ error: "User not found" });
|
||||
return;
|
||||
}
|
||||
|
||||
await writeAuditLog(req, "user", id, "update", { role: parsed.data.role });
|
||||
res.json(user);
|
||||
});
|
||||
|
||||
router.delete("/users/:id", requireAdmin, async (req, res): Promise<void> => {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
if (isNaN(id)) {
|
||||
res.status(400).json({ error: "Invalid user id" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.session.user?.sub === String(id)) {
|
||||
res.status(400).json({ error: "Cannot delete your own account" });
|
||||
return;
|
||||
}
|
||||
|
||||
const [user] = await db.delete(usersTable).where(eq(usersTable.id, id)).returning();
|
||||
if (!user) {
|
||||
res.status(404).json({ error: "User not found" });
|
||||
return;
|
||||
}
|
||||
|
||||
await writeAuditLog(req, "user", id, "delete", { username: user.username });
|
||||
res.sendStatus(204);
|
||||
});
|
||||
|
||||
export default router;
|
||||
+2
@@ -7,6 +7,8 @@ declare module "express-session" {
|
||||
email?: string;
|
||||
name?: string;
|
||||
preferred_username?: string;
|
||||
role?: "admin" | "user";
|
||||
isLocal?: boolean;
|
||||
};
|
||||
codeVerifier?: string;
|
||||
returnTo?: string;
|
||||
|
||||
@@ -8,7 +8,10 @@ import Home from "@/pages/home";
|
||||
import ToolsBrowse from "@/pages/tools-browse";
|
||||
import ToolDetail from "@/pages/tool-detail";
|
||||
import ToolNew from "@/pages/tool-new";
|
||||
import ToolEdit from "@/pages/tool-edit";
|
||||
import Analytics from "@/pages/analytics";
|
||||
import Admin from "@/pages/admin";
|
||||
import Login from "@/pages/login";
|
||||
import NotFound from "@/pages/not-found";
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
@@ -24,10 +27,13 @@ function Router() {
|
||||
return (
|
||||
<Switch>
|
||||
<Route path="/" component={Home} />
|
||||
<Route path="/login" component={Login} />
|
||||
<Route path="/tools" component={ToolsBrowse} />
|
||||
<Route path="/tools/new" component={ToolNew} />
|
||||
<Route path="/tools/:id/edit" component={ToolEdit} />
|
||||
<Route path="/tools/:id" component={ToolDetail} />
|
||||
<Route path="/analytics" component={Analytics} />
|
||||
<Route path="/admin" component={Admin} />
|
||||
<Route component={NotFound} />
|
||||
</Switch>
|
||||
);
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
import { Link, useLocation } from "wouter";
|
||||
import { LayoutDashboard, Wrench, PlusCircle, BarChart3, LogIn, LogOut, User } from "lucide-react";
|
||||
import { LayoutDashboard, Wrench, PlusCircle, BarChart3, LogIn, LogOut, User, ShieldCheck } from "lucide-react";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
|
||||
export function Layout({ children }: { children: React.ReactNode }) {
|
||||
const [location] = useLocation();
|
||||
const { user, isLoading, isAuthenticated, login, logout } = useAuth();
|
||||
const { user, isLoading, isAuthenticated, isAdmin, isLocalMode, login, logout } = useAuth();
|
||||
|
||||
const links = [
|
||||
{ href: "/", label: "Dashboard", icon: LayoutDashboard },
|
||||
{ href: "/tools", label: "Browse Tools", icon: Wrench },
|
||||
{ href: "/tools/new", label: "Add Tool", icon: PlusCircle },
|
||||
{ href: "/analytics", label: "Analytics", icon: BarChart3 },
|
||||
...(isAdmin ? [{ href: "/admin", label: "Admin", icon: ShieldCheck }] : []),
|
||||
];
|
||||
|
||||
return (
|
||||
@@ -82,7 +83,7 @@ export function Layout({ children }: { children: React.ReactNode }) {
|
||||
data-testid="button-login"
|
||||
>
|
||||
<LogIn className="w-4 h-4" />
|
||||
Sign in with Keycloak
|
||||
{isLocalMode ? "Sign in" : "Sign in with Keycloak"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,32 +1,51 @@
|
||||
import { useGetMe } from "@workspace/api-client-react";
|
||||
|
||||
export type AuthUser = {
|
||||
sub: string;
|
||||
email?: string | null;
|
||||
name?: string | null;
|
||||
preferredUsername?: string | null;
|
||||
};
|
||||
import { useGetMe, useGetAuthMode, getGetMeQueryKey, getGetAuthModeQueryKey } from "@workspace/api-client-react";
|
||||
|
||||
export function useAuth() {
|
||||
const { data: user, isLoading, error } = useGetMe({
|
||||
query: {
|
||||
queryKey: getGetMeQueryKey(),
|
||||
retry: false,
|
||||
staleTime: 1000 * 60 * 5,
|
||||
},
|
||||
});
|
||||
|
||||
const { data: authMode } = useGetAuthMode({
|
||||
query: {
|
||||
queryKey: getGetAuthModeQueryKey(),
|
||||
staleTime: Infinity,
|
||||
retry: false,
|
||||
},
|
||||
});
|
||||
|
||||
const isAuthenticated = !!user && !error;
|
||||
const isAdmin = isAuthenticated && user?.role === "admin";
|
||||
const isLocalMode = authMode?.mode === "local";
|
||||
|
||||
function login(returnTo?: string) {
|
||||
const url = returnTo
|
||||
? `/api/auth/login?returnTo=${encodeURIComponent(returnTo)}`
|
||||
: "/api/auth/login";
|
||||
window.location.href = url;
|
||||
if (isLocalMode) {
|
||||
const path = returnTo
|
||||
? `/login?returnTo=${encodeURIComponent(returnTo)}`
|
||||
: "/login";
|
||||
window.location.href = path;
|
||||
} else {
|
||||
const url = returnTo
|
||||
? `/api/auth/login?returnTo=${encodeURIComponent(returnTo)}`
|
||||
: "/api/auth/login";
|
||||
window.location.href = url;
|
||||
}
|
||||
}
|
||||
|
||||
function logout() {
|
||||
window.location.href = "/api/auth/logout";
|
||||
}
|
||||
|
||||
return { user: isAuthenticated ? user : null, isLoading, isAuthenticated, login, logout };
|
||||
return {
|
||||
user: isAuthenticated ? user : null,
|
||||
isLoading,
|
||||
isAuthenticated,
|
||||
isAdmin,
|
||||
isLocalMode,
|
||||
login,
|
||||
logout,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
import { useState } from "react";
|
||||
import { useLocation } from "wouter";
|
||||
import {
|
||||
useListUsers,
|
||||
useCreateUser,
|
||||
useUpdateUser,
|
||||
useDeleteUser,
|
||||
useListAuditLogs,
|
||||
getListUsersQueryKey,
|
||||
getListAuditLogsQueryKey,
|
||||
} from "@workspace/api-client-react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { Layout } from "@/components/layout";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Users, ScrollText, ShieldAlert, Plus, Pencil, Trash2, Clock } from "lucide-react";
|
||||
import { format } from "date-fns";
|
||||
|
||||
export default function Admin() {
|
||||
const [, setLocation] = useLocation();
|
||||
const { user, isAdmin, isLoading: authLoading } = useAuth();
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [editUser, setEditUser] = useState<{ id: number; username: string; role: string } | null>(null);
|
||||
const [deleteConfirm, setDeleteConfirm] = useState<{ id: number; username: string } | null>(null);
|
||||
|
||||
const [newUsername, setNewUsername] = useState("");
|
||||
const [newPassword, setNewPassword] = useState("");
|
||||
const [newEmail, setNewEmail] = useState("");
|
||||
const [newRole, setNewRole] = useState<"admin" | "user">("user");
|
||||
|
||||
const { data: users, isLoading: loadingUsers } = useListUsers({
|
||||
query: { queryKey: getListUsersQueryKey(), enabled: isAdmin },
|
||||
});
|
||||
const { data: auditLogs, isLoading: loadingLogs } = useListAuditLogs(
|
||||
{ limit: 100 },
|
||||
{ query: { queryKey: getListAuditLogsQueryKey({ limit: 100 }), enabled: isAdmin } },
|
||||
);
|
||||
|
||||
const createUser = useCreateUser();
|
||||
const updateUser = useUpdateUser();
|
||||
const deleteUser = useDeleteUser();
|
||||
|
||||
if (!authLoading && !isAdmin) {
|
||||
return (
|
||||
<Layout>
|
||||
<div className="flex flex-col items-center justify-center py-20 gap-4">
|
||||
<ShieldAlert className="w-12 h-12 text-muted-foreground" />
|
||||
<h2 className="text-2xl font-bold">Admin Access Required</h2>
|
||||
<p className="text-muted-foreground">You need admin rights to view this page.</p>
|
||||
<Button variant="outline" onClick={() => setLocation("/")}>Go Home</Button>
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
|
||||
const handleCreateUser = () => {
|
||||
if (!newUsername || !newPassword) return;
|
||||
createUser.mutate(
|
||||
{ data: { username: newUsername, password: newPassword, email: newEmail || undefined, role: newRole } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast({ title: "User created", description: `${newUsername} has been created.` });
|
||||
queryClient.invalidateQueries({ queryKey: getListUsersQueryKey() });
|
||||
setCreateOpen(false);
|
||||
setNewUsername("");
|
||||
setNewPassword("");
|
||||
setNewEmail("");
|
||||
setNewRole("user");
|
||||
},
|
||||
onError: (err) => {
|
||||
toast({ title: "Failed to create user", description: err.data?.error ?? err.message, variant: "destructive" });
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const handleUpdateRole = (role: "admin" | "user") => {
|
||||
if (!editUser) return;
|
||||
updateUser.mutate(
|
||||
{ id: editUser.id, data: { role } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast({ title: "Role updated" });
|
||||
queryClient.invalidateQueries({ queryKey: getListUsersQueryKey() });
|
||||
setEditUser(null);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast({ title: "Failed to update role", description: err.data?.error ?? err.message, variant: "destructive" });
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const handleDeleteUser = () => {
|
||||
if (!deleteConfirm) return;
|
||||
deleteUser.mutate(
|
||||
{ id: deleteConfirm.id },
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast({ title: "User deleted", description: `${deleteConfirm.username} has been removed.` });
|
||||
queryClient.invalidateQueries({ queryKey: getListUsersQueryKey() });
|
||||
setDeleteConfirm(null);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast({ title: "Failed to delete user", description: (err.data as { error?: string } | null)?.error ?? err.message, variant: "destructive" });
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
function actionBadgeVariant(action: string): "default" | "secondary" | "destructive" | "outline" {
|
||||
if (action === "create") return "default";
|
||||
if (action === "delete") return "destructive";
|
||||
return "secondary";
|
||||
}
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<div className="space-y-6 pb-10">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight mb-2">Admin Panel</h1>
|
||||
<p className="text-muted-foreground">Manage users and review system changes.</p>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="users">
|
||||
<TabsList className="mb-4">
|
||||
<TabsTrigger value="users" className="gap-2">
|
||||
<Users className="w-4 h-4" /> Users
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="audit" className="gap-2">
|
||||
<ScrollText className="w-4 h-4" /> Audit Log
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="users">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>Local Users</CardTitle>
|
||||
<CardDescription>Manage accounts for local authentication.</CardDescription>
|
||||
</div>
|
||||
<Button size="sm" onClick={() => setCreateOpen(true)}>
|
||||
<Plus className="w-4 h-4 mr-2" /> Add User
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loadingUsers ? (
|
||||
<div className="space-y-3">
|
||||
{[1, 2, 3].map((i) => <Skeleton key={i} className="h-12 w-full" />)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y">
|
||||
{users?.map((u) => (
|
||||
<div key={u.id} className="flex items-center justify-between py-3 gap-4">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center shrink-0 font-medium text-primary text-sm">
|
||||
{u.username.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="font-medium text-sm truncate">{u.username}</p>
|
||||
{u.email && <p className="text-xs text-muted-foreground truncate">{u.email}</p>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<Badge variant={u.role === "admin" ? "default" : "secondary"}>
|
||||
{u.role}
|
||||
</Badge>
|
||||
{u.username !== user?.preferredUsername && (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => setEditUser({ id: u.id, username: u.username, role: u.role })}
|
||||
>
|
||||
<Pencil className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => setDeleteConfirm({ id: u.id, username: u.username })}
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{(!users || users.length === 0) && (
|
||||
<p className="text-sm text-muted-foreground py-4 text-center">No users yet.</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="audit">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Audit Log</CardTitle>
|
||||
<CardDescription>All create, update and delete operations tracked by the system.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loadingLogs ? (
|
||||
<div className="space-y-3">
|
||||
{[1, 2, 3, 4, 5].map((i) => <Skeleton key={i} className="h-14 w-full" />)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y">
|
||||
{auditLogs?.map((log) => (
|
||||
<div key={log.id} className="py-3 space-y-1">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Badge variant={actionBadgeVariant(log.action)} className="capitalize text-xs">
|
||||
{log.action}
|
||||
</Badge>
|
||||
<span className="text-sm font-medium capitalize">{log.entityType}</span>
|
||||
{log.entityId && (
|
||||
<span className="text-sm text-muted-foreground">#{log.entityId}</span>
|
||||
)}
|
||||
<span className="text-xs text-muted-foreground ml-auto flex items-center gap-1">
|
||||
<Clock className="w-3 h-3" />
|
||||
{format(new Date(log.createdAt), "dd.MM.yyyy HH:mm")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<span>by <span className="font-medium text-foreground">{log.username}</span></span>
|
||||
{log.changes && (
|
||||
<span className="truncate max-w-[400px] font-mono bg-muted px-1.5 py-0.5 rounded text-[11px]">
|
||||
{log.changes.length > 120 ? log.changes.slice(0, 120) + "…" : log.changes}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{(!auditLogs || auditLogs.length === 0) && (
|
||||
<p className="text-sm text-muted-foreground py-4 text-center">No audit entries yet.</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create New User</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-2">
|
||||
<div className="space-y-2">
|
||||
<Label>Username</Label>
|
||||
<Input value={newUsername} onChange={(e) => setNewUsername(e.target.value)} placeholder="username" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Password</Label>
|
||||
<Input type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} placeholder="min. 6 characters" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Email (Optional)</Label>
|
||||
<Input type="email" value={newEmail} onChange={(e) => setNewEmail(e.target.value)} placeholder="user@example.com" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Role</Label>
|
||||
<Select value={newRole} onValueChange={(v) => setNewRole(v as "admin" | "user")}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="user">User</SelectItem>
|
||||
<SelectItem value="admin">Admin</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setCreateOpen(false)}>Cancel</Button>
|
||||
<Button onClick={handleCreateUser} disabled={createUser.isPending || !newUsername || !newPassword}>
|
||||
{createUser.isPending ? "Creating…" : "Create User"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={!!editUser} onOpenChange={(open) => !open && setEditUser(null)}>
|
||||
<DialogContent className="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Change Role — {editUser?.username}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="py-2">
|
||||
<Select
|
||||
value={editUser?.role || "user"}
|
||||
onValueChange={(v) => setEditUser(editUser ? { ...editUser, role: v } : null)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="user">User</SelectItem>
|
||||
<SelectItem value="admin">Admin</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setEditUser(null)}>Cancel</Button>
|
||||
<Button
|
||||
onClick={() => handleUpdateRole(editUser?.role as "admin" | "user")}
|
||||
disabled={updateUser.isPending}
|
||||
>
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={!!deleteConfirm} onOpenChange={(open) => !open && setDeleteConfirm(null)}>
|
||||
<DialogContent className="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Delete User</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-sm text-muted-foreground py-2">
|
||||
Are you sure you want to delete <span className="font-medium text-foreground">{deleteConfirm?.username}</span>? This cannot be undone.
|
||||
</p>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setDeleteConfirm(null)}>Cancel</Button>
|
||||
<Button variant="destructive" onClick={handleDeleteUser} disabled={deleteUser.isPending}>
|
||||
{deleteUser.isPending ? "Deleting…" : "Delete"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
@@ -36,7 +36,9 @@ export default function Analytics() {
|
||||
const categoryChartData = categoryStats?.map(c => ({
|
||||
category: c.category,
|
||||
tools: c.toolCount,
|
||||
avgScore: c.avgCombined ? Number(c.avgCombined.toFixed(2)) : 0
|
||||
avgScore: (c.avgUsefulness != null && c.avgUsability != null)
|
||||
? Number(((c.avgUsefulness + c.avgUsability) / 2).toFixed(2))
|
||||
: 0
|
||||
})) || [];
|
||||
|
||||
const usefulnessData = distribution?.usefulness.map(b => ({ score: `${b.score} Star`, count: b.count })) || [];
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { useState } from "react";
|
||||
import { useLocation, useSearch } from "wouter";
|
||||
import { useLocalLogin } from "@workspace/api-client-react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
||||
import { Wrench, AlertCircle } from "lucide-react";
|
||||
|
||||
export default function Login() {
|
||||
const [, setLocation] = useLocation();
|
||||
const search = useSearch();
|
||||
const params = new URLSearchParams(search);
|
||||
const returnTo = params.get("returnTo") || "/";
|
||||
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
const localLogin = useLocalLogin();
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
localLogin.mutate(
|
||||
{ data: { username, password } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries();
|
||||
setLocation(returnTo);
|
||||
},
|
||||
onError: (err) => {
|
||||
setError(err.data?.error || err.message || "Invalid username or password");
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex items-center justify-center p-4">
|
||||
<div className="w-full max-w-sm space-y-6">
|
||||
<div className="flex flex-col items-center gap-2 text-center">
|
||||
<div className="flex items-center gap-2 text-primary font-bold text-2xl">
|
||||
<Wrench className="w-7 h-7" />
|
||||
<span>ToolRate</span>
|
||||
</div>
|
||||
<p className="text-muted-foreground text-sm">Sign in to your account</p>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-4">
|
||||
<CardTitle className="text-lg">Sign in</CardTitle>
|
||||
<CardDescription>Enter your credentials to continue</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="username">Username</Label>
|
||||
<Input
|
||||
id="username"
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="admin"
|
||||
autoFocus
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="flex items-center gap-2 text-destructive text-sm rounded-md bg-destructive/10 px-3 py-2">
|
||||
<AlertCircle className="w-4 h-4 shrink-0" />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={localLogin.isPending}
|
||||
>
|
||||
{localLogin.isPending ? "Signing in…" : "Sign in"}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -27,8 +27,20 @@ import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from "recharts";
|
||||
import { ExternalLink, Star, ArrowLeft, Plus } from "lucide-react";
|
||||
import { ExternalLink, Star, ArrowLeft, Plus, Pencil, Trash2 } from "lucide-react";
|
||||
import { Link } from "wouter";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { useDeleteTool, getListToolsQueryKey } from "@workspace/api-client-react";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
|
||||
const ratingSchema = z.object({
|
||||
usefulness: z.number().min(1).max(5),
|
||||
@@ -47,6 +59,10 @@ export default function ToolDetail() {
|
||||
const queryClient = useQueryClient();
|
||||
const { toast } = useToast();
|
||||
const [isReviewFormOpen, setIsReviewFormOpen] = useState(false);
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
|
||||
const { user, isAdmin } = useAuth();
|
||||
const deleteTool = useDeleteTool();
|
||||
|
||||
const { data: tool, isLoading: loadingTool } = useGetTool(id, {
|
||||
query: { enabled: !!id, queryKey: getGetToolQueryKey(id) }
|
||||
@@ -99,7 +115,7 @@ export default function ToolDetail() {
|
||||
onError: (error) => {
|
||||
toast({
|
||||
title: "Failed to submit rating",
|
||||
description: error.error || "An unexpected error occurred.",
|
||||
description: error.data?.error || error.message || "An unexpected error occurred.",
|
||||
variant: "destructive"
|
||||
});
|
||||
}
|
||||
@@ -122,7 +138,32 @@ export default function ToolDetail() {
|
||||
const usefulnessData = distribution?.usefulness.map(b => ({ score: b.score, count: b.count })).reverse() || [];
|
||||
const usabilityData = distribution?.usability.map(b => ({ score: b.score, count: b.count })).reverse() || [];
|
||||
|
||||
function canEdit(toolData: { createdBy?: string | null }): boolean {
|
||||
if (!user) return false;
|
||||
if (isAdmin) return true;
|
||||
return toolData.createdBy === user.sub ||
|
||||
toolData.createdBy === user.preferredUsername;
|
||||
}
|
||||
|
||||
function handleDelete() {
|
||||
deleteTool.mutate(
|
||||
{ id },
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast({ title: "Tool deleted" });
|
||||
queryClient.invalidateQueries({ queryKey: getListToolsQueryKey() });
|
||||
setLocation("/tools");
|
||||
},
|
||||
onError: (err) => {
|
||||
toast({ title: "Failed to delete", description: err.data?.error || err.message, variant: "destructive" });
|
||||
setDeleteOpen(false);
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Layout>
|
||||
<div className="space-y-6 max-w-5xl mx-auto pb-10">
|
||||
<Button variant="ghost" asChild className="mb-2 -ml-4 text-muted-foreground">
|
||||
@@ -183,7 +224,7 @@ export default function ToolDetail() {
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Based on {tool.ratingCount} reviews
|
||||
</div>
|
||||
|
||||
|
||||
{tool.websiteUrl && (
|
||||
<Button asChild className="w-full mt-2" variant="outline">
|
||||
<a href={tool.websiteUrl} target="_blank" rel="noopener noreferrer">
|
||||
@@ -191,6 +232,24 @@ export default function ToolDetail() {
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{canEdit(tool) && (
|
||||
<div className="flex gap-2 w-full mt-1">
|
||||
<Button asChild variant="outline" size="sm" className="flex-1 gap-2">
|
||||
<Link href={`/tools/${id}/edit`}>
|
||||
<Pencil className="w-3.5 h-3.5" /> Edit
|
||||
</Link>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1 gap-2 text-destructive hover:bg-destructive hover:text-destructive-foreground"
|
||||
onClick={() => setDeleteOpen(true)}
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" /> Delete
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -423,5 +482,27 @@ export default function ToolDetail() {
|
||||
)}
|
||||
</div>
|
||||
</Layout>
|
||||
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete this tool?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This will permanently remove <span className="font-medium">{tool?.name}</span> and all its ratings. This cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
onClick={handleDelete}
|
||||
disabled={deleteTool.isPending}
|
||||
>
|
||||
{deleteTool.isPending ? "Deleting…" : "Delete"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
import { useEffect } from "react";
|
||||
import { useRoute, useLocation } from "wouter";
|
||||
import { useForm, useFieldArray } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import * as z from "zod";
|
||||
import {
|
||||
useGetTool,
|
||||
useUpdateTool,
|
||||
getGetToolQueryKey,
|
||||
getListToolsQueryKey,
|
||||
} from "@workspace/api-client-react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { Layout } from "@/components/layout";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { Pencil, Plus, X, ArrowLeft } from "lucide-react";
|
||||
import { Link } from "wouter";
|
||||
import { CategoryCombobox } from "@/components/category-combobox";
|
||||
import { FeatureInput } from "@/components/feature-input";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
|
||||
const toolSchema = z.object({
|
||||
name: z.string().min(2, "Name must be at least 2 characters"),
|
||||
description: z.string().min(10, "Description must be at least 10 characters"),
|
||||
category: z.string().min(2, "Category is required"),
|
||||
websiteUrl: z.string().url("Must be a valid URL").optional().or(z.literal("")),
|
||||
iconUrl: z.string().url("Must be a valid URL").optional().or(z.literal("")),
|
||||
features: z.array(z.object({ value: z.string() })).optional(),
|
||||
tags: z.array(z.object({ value: z.string() })).optional(),
|
||||
});
|
||||
|
||||
type ToolFormValues = z.infer<typeof toolSchema>;
|
||||
|
||||
export default function ToolEdit() {
|
||||
const [match, params] = useRoute("/tools/:id/edit");
|
||||
const [, setLocation] = useLocation();
|
||||
const id = parseInt(params?.id || "0", 10);
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
const updateTool = useUpdateTool();
|
||||
const { isAuthenticated, isAdmin } = useAuth();
|
||||
|
||||
const { data: tool, isLoading } = useGetTool(id, {
|
||||
query: { enabled: !!id, queryKey: getGetToolQueryKey(id) },
|
||||
});
|
||||
|
||||
const form = useForm<ToolFormValues>({
|
||||
resolver: zodResolver(toolSchema),
|
||||
defaultValues: {
|
||||
name: "",
|
||||
description: "",
|
||||
category: "",
|
||||
websiteUrl: "",
|
||||
iconUrl: "",
|
||||
features: [],
|
||||
tags: [],
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (tool) {
|
||||
form.reset({
|
||||
name: tool.name,
|
||||
description: tool.description,
|
||||
category: tool.category,
|
||||
websiteUrl: tool.websiteUrl || "",
|
||||
iconUrl: tool.iconUrl || "",
|
||||
features: (tool.features || []).map((v) => ({ value: v })),
|
||||
tags: (tool.tags || []).map((v) => ({ value: v })),
|
||||
});
|
||||
}
|
||||
}, [tool, form]);
|
||||
|
||||
const { fields: featureFields, append: appendFeature, remove: removeFeature } = useFieldArray({
|
||||
control: form.control,
|
||||
name: "features",
|
||||
});
|
||||
|
||||
const { fields: tagFields, append: appendTag, remove: removeTag } = useFieldArray({
|
||||
control: form.control,
|
||||
name: "tags",
|
||||
});
|
||||
|
||||
const onSubmit = (data: ToolFormValues) => {
|
||||
const payload = {
|
||||
...data,
|
||||
websiteUrl: data.websiteUrl || undefined,
|
||||
iconUrl: data.iconUrl || undefined,
|
||||
features: data.features?.map((f) => f.value).filter((v) => v.trim() !== ""),
|
||||
tags: data.tags?.map((t) => t.value).filter((v) => v.trim() !== ""),
|
||||
};
|
||||
|
||||
updateTool.mutate(
|
||||
{ id, data: payload },
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast({ title: "Tool updated", description: "Changes saved successfully." });
|
||||
queryClient.invalidateQueries({ queryKey: getGetToolQueryKey(id) });
|
||||
queryClient.invalidateQueries({ queryKey: getListToolsQueryKey() });
|
||||
setLocation(`/tools/${id}`);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast({
|
||||
title: "Failed to update tool",
|
||||
description: err.data?.error || err.message || "An unexpected error occurred.",
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
if (!match || isNaN(id)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<div className="max-w-3xl mx-auto space-y-6 pb-10">
|
||||
<Button variant="ghost" asChild className="mb-2 -ml-4 text-muted-foreground">
|
||||
<Link href={`/tools/${id}`}>
|
||||
<ArrowLeft className="w-4 h-4 mr-2" /> Back to tool
|
||||
</Link>
|
||||
</Button>
|
||||
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight mb-2">Edit Tool</h1>
|
||||
<p className="text-muted-foreground">Update tool details and metadata.</p>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<Card>
|
||||
<CardContent className="p-6 space-y-4">
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<Skeleton className="h-24 w-full" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Pencil className="w-5 h-5 text-primary" />
|
||||
Tool Details
|
||||
</CardTitle>
|
||||
<CardDescription>Modify the tool information below.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Tool name" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="category"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Category</FormLabel>
|
||||
<FormControl>
|
||||
<CategoryCombobox value={field.value} onChange={field.onChange} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="websiteUrl"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Website URL (Optional)</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="https://..." type="url" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="iconUrl"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Icon / Logo URL (Optional)</FormLabel>
|
||||
<FormControl>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-9 h-9 rounded-md border bg-muted flex items-center justify-center overflow-hidden shrink-0">
|
||||
{field.value ? (
|
||||
<img
|
||||
src={field.value}
|
||||
alt="icon preview"
|
||||
className="w-full h-full object-contain p-0.5"
|
||||
onError={(e) => { (e.target as HTMLImageElement).style.display = "none"; }}
|
||||
/>
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground">img</span>
|
||||
)}
|
||||
</div>
|
||||
<Input
|
||||
placeholder="https://example.com/logo.png"
|
||||
type="url"
|
||||
{...field}
|
||||
className="flex-1"
|
||||
/>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="description"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Description</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder="What does this tool do?"
|
||||
className="min-h-[120px] resize-none"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="space-y-4 pt-4 border-t">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<h3 className="text-lg font-medium">Features</h3>
|
||||
<p className="text-sm text-muted-foreground">Key capabilities of this tool.</p>
|
||||
</div>
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => appendFeature({ value: "" })}>
|
||||
<Plus className="w-4 h-4 mr-2" /> Add Feature
|
||||
</Button>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
{featureFields.map((field, index) => (
|
||||
<FormField
|
||||
key={field.id}
|
||||
control={form.control}
|
||||
name={`features.${index}.value`}
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex items-start gap-2 space-y-0">
|
||||
<FormControl>
|
||||
<FeatureInput
|
||||
value={field.value ?? ""}
|
||||
onChange={field.onChange}
|
||||
placeholder="e.g. Real-time collaboration"
|
||||
/>
|
||||
</FormControl>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="shrink-0 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => removeFeature(index)}
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
{featureFields.length === 0 && (
|
||||
<p className="text-sm text-muted-foreground italic">No features added.</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 pt-4 border-t">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<h3 className="text-lg font-medium">Tags</h3>
|
||||
<p className="text-sm text-muted-foreground">Keywords for this tool.</p>
|
||||
</div>
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => appendTag({ value: "" })}>
|
||||
<Plus className="w-4 h-4 mr-2" /> Add Tag
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{tagFields.map((field, index) => (
|
||||
<FormField
|
||||
key={field.id}
|
||||
control={form.control}
|
||||
name={`tags.${index}.value`}
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex items-center space-y-0 relative w-[150px]">
|
||||
<FormControl>
|
||||
<Input placeholder="Tag" className="pr-8 h-9 text-sm" {...field} />
|
||||
</FormControl>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="absolute right-0 top-0 h-9 w-8 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => removeTag(index)}
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
</Button>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-6 border-t flex justify-end gap-3">
|
||||
<Button type="button" variant="outline" asChild>
|
||||
<Link href={`/tools/${id}`}>Cancel</Link>
|
||||
</Button>
|
||||
<Button type="submit" disabled={updateTool.isPending || !isAuthenticated}>
|
||||
{updateTool.isPending ? "Saving…" : "Save Changes"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
@@ -249,7 +249,7 @@ export default function ToolNew() {
|
||||
<FormItem className="flex items-start gap-2 space-y-0">
|
||||
<FormControl>
|
||||
<FeatureInput
|
||||
value={field.value}
|
||||
value={field.value ?? ""}
|
||||
onChange={field.onChange}
|
||||
placeholder="e.g. Real-time collaboration"
|
||||
data-testid={`input-feature-${index}`}
|
||||
|
||||
Reference in New Issue
Block a user