Compare commits
2 Commits
27e6e6a4a0
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 17dea01323 | |||
| 6e31681438 |
@@ -44,14 +44,16 @@ router.post(
|
|||||||
|
|
||||||
const hashedPassword = await hashPassword(req.body.password);
|
const hashedPassword = await hashPassword(req.body.password);
|
||||||
const user = await storage.createUser({
|
const user = await storage.createUser({
|
||||||
...req.body,
|
username: req.body.username,
|
||||||
password: hashedPassword,
|
password: hashedPassword,
|
||||||
|
role: "USER",
|
||||||
});
|
});
|
||||||
|
|
||||||
// Generate a JWT token for the user after successful registration
|
// Generate a JWT token for the user after successful registration
|
||||||
const token = generateToken(user);
|
const token = generateToken(user);
|
||||||
|
|
||||||
const { password, ...safeUser } = user;
|
const { password, ...rest } = user;
|
||||||
|
const safeUser = { ...rest, role: rest.role ?? "USER" };
|
||||||
return res.status(201).json({ user: safeUser, token });
|
return res.status(201).json({ user: safeUser, token });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Registration error:", error);
|
console.error("Registration error:", error);
|
||||||
@@ -77,12 +79,13 @@ router.post(
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (!isPasswordMatch) {
|
if (!isPasswordMatch) {
|
||||||
return res.status(401).json({ error: "Invalid password or password" });
|
return res.status(401).json({ error: "Invalid username or password" });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate a JWT token for the user after successful login
|
// Generate a JWT token for the user after successful login
|
||||||
const token = generateToken(user);
|
const token = generateToken(user);
|
||||||
const { password, ...safeUser } = user;
|
const { password, ...rest } = user;
|
||||||
|
const safeUser = { ...rest, role: rest.role ?? "USER" };
|
||||||
return res.status(200).json({ user: safeUser, token });
|
return res.status(200).json({ user: safeUser, token });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return res.status(500).json({ error: "Internal server error" });
|
return res.status(500).json({ error: "Internal server error" });
|
||||||
|
|||||||
@@ -3,8 +3,7 @@ import type { Request, Response } from "express";
|
|||||||
import { storage } from "../storage";
|
import { storage } from "../storage";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { UserUncheckedCreateInputObjectSchema } from "@repo/db/usedSchemas";
|
import { UserUncheckedCreateInputObjectSchema } from "@repo/db/usedSchemas";
|
||||||
import jwt from 'jsonwebtoken';
|
import bcrypt from "bcrypt";
|
||||||
import bcrypt from 'bcrypt';
|
|
||||||
|
|
||||||
|
|
||||||
const router = Router();
|
const router = Router();
|
||||||
@@ -25,15 +24,33 @@ router.get("/", async (req: Request, res: Response): Promise<any> => {
|
|||||||
const user = await storage.getUser(userId);
|
const user = await storage.getUser(userId);
|
||||||
if (!user) return res.status(404).send("User not found");
|
if (!user) return res.status(404).send("User not found");
|
||||||
|
|
||||||
|
const { password, ...rest } = user;
|
||||||
const { password, ...safeUser } = user;
|
res.json({ ...rest, role: rest.role ?? "USER" });
|
||||||
res.json(safeUser);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
res.status(500).send("Failed to fetch user");
|
res.status(500).send("Failed to fetch user");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// GET: List all users (for admin/settings; no passwords)
|
||||||
|
router.get("/list", async (req: Request, res: Response): Promise<any> => {
|
||||||
|
try {
|
||||||
|
if (!req.user?.id) return res.status(401).send("Unauthorized");
|
||||||
|
|
||||||
|
const limit = Math.min(Number(req.query.limit) || 100, 500);
|
||||||
|
const offset = Number(req.query.offset) || 0;
|
||||||
|
const users = await storage.getUsers(limit, offset);
|
||||||
|
const safe = users.map((u) => {
|
||||||
|
const { password: _p, ...rest } = u;
|
||||||
|
return { ...rest, role: rest.role ?? "USER" };
|
||||||
|
});
|
||||||
|
res.json(safe);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
res.status(500).send("Failed to fetch users");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// GET: User by ID
|
// GET: User by ID
|
||||||
router.get("/:id", async (req: Request, res: Response): Promise<any> => {
|
router.get("/:id", async (req: Request, res: Response): Promise<any> => {
|
||||||
try {
|
try {
|
||||||
@@ -46,32 +63,36 @@ router.get("/:id", async (req: Request, res: Response): Promise<any> => {
|
|||||||
const user = await storage.getUser(id);
|
const user = await storage.getUser(id);
|
||||||
if (!user) return res.status(404).send("User not found");
|
if (!user) return res.status(404).send("User not found");
|
||||||
|
|
||||||
const { password, ...safeUser } = user;
|
const { password, ...rest } = user;
|
||||||
res.json(safeUser);
|
res.json({ ...rest, role: rest.role ?? "USER" });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
res.status(500).send("Failed to fetch user");
|
res.status(500).send("Failed to fetch user");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// POST: Create new user
|
// POST: Create new user (password is hashed)
|
||||||
router.post("/", async (req: Request, res: Response) => {
|
router.post("/", async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
const input = userCreateSchema.parse(req.body);
|
const input = userCreateSchema.parse(req.body);
|
||||||
const newUser = await storage.createUser(input);
|
const existing = await storage.getUserByUsername(input.username);
|
||||||
const { password, ...safeUser } = newUser;
|
if (existing) {
|
||||||
res.status(201).json(safeUser);
|
return res.status(400).json({ error: "Username already exists" });
|
||||||
|
}
|
||||||
|
const hashed = await hashPassword(input.password);
|
||||||
|
const newUser = await storage.createUser({ ...input, password: hashed });
|
||||||
|
const { password: _p, ...rest } = newUser;
|
||||||
|
res.status(201).json({ ...rest, role: rest.role ?? "USER" });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
res.status(400).json({ error: "Invalid user data", details: err });
|
res.status(400).json({ error: "Invalid user data", details: err });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Function to hash password using bcrypt
|
// Hash password using bcrypt (used for create and update)
|
||||||
async function hashPassword(password: string) {
|
async function hashPassword(password: string) {
|
||||||
const saltRounds = 10; // Salt rounds for bcrypt
|
const saltRounds = 10;
|
||||||
const hashedPassword = await bcrypt.hash(password, saltRounds);
|
return bcrypt.hash(password, saltRounds);
|
||||||
return hashedPassword;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// PUT: Update user
|
// PUT: Update user
|
||||||
@@ -97,16 +118,16 @@ router.put("/:id", async (req: Request, res: Response):Promise<any> => {
|
|||||||
const updatedUser = await storage.updateUser(id, updates);
|
const updatedUser = await storage.updateUser(id, updates);
|
||||||
if (!updatedUser) return res.status(404).send("User not found");
|
if (!updatedUser) return res.status(404).send("User not found");
|
||||||
|
|
||||||
const { password, ...safeUser } = updatedUser;
|
const { password, ...rest } = updatedUser;
|
||||||
res.json(safeUser);
|
res.json({ ...rest, role: rest.role ?? "USER" });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
res.status(400).json({ error: "Invalid update data", details: err });
|
res.status(400).json({ error: "Invalid update data", details: err });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// DELETE: Delete user
|
// DELETE: Delete user (cannot delete current user)
|
||||||
router.delete("/:id", async (req: Request, res: Response):Promise<any> => {
|
router.delete("/:id", async (req: Request, res: Response): Promise<any> => {
|
||||||
try {
|
try {
|
||||||
const idParam = req.params.id;
|
const idParam = req.params.id;
|
||||||
if (!idParam) return res.status(400).send("User ID is required");
|
if (!idParam) return res.status(400).send("User ID is required");
|
||||||
@@ -114,6 +135,10 @@ router.delete("/:id", async (req: Request, res: Response):Promise<any> => {
|
|||||||
const id = parseInt(idParam);
|
const id = parseInt(idParam);
|
||||||
if (isNaN(id)) return res.status(400).send("Invalid user ID");
|
if (isNaN(id)) return res.status(400).send("Invalid user ID");
|
||||||
|
|
||||||
|
if (req.user?.id === id) {
|
||||||
|
return res.status(403).json({ error: "Cannot delete your own account" });
|
||||||
|
}
|
||||||
|
|
||||||
const success = await storage.deleteUser(id);
|
const success = await storage.deleteUser(id);
|
||||||
if (!success) return res.status(404).send("User not found");
|
if (!success) return res.status(404).send("User not found");
|
||||||
|
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ function Router() {
|
|||||||
component={() => <AppointmentsPage />}
|
component={() => <AppointmentsPage />}
|
||||||
/>
|
/>
|
||||||
<ProtectedRoute path="/patients" component={() => <PatientsPage />} />
|
<ProtectedRoute path="/patients" component={() => <PatientsPage />} />
|
||||||
<ProtectedRoute path="/settings" component={() => <SettingsPage />} />
|
<ProtectedRoute path="/settings" component={() => <SettingsPage />} adminOnly />
|
||||||
<ProtectedRoute path="/claims" component={() => <ClaimsPage />} />
|
<ProtectedRoute path="/claims" component={() => <ClaimsPage />} />
|
||||||
<ProtectedRoute
|
<ProtectedRoute
|
||||||
path="/insurance-status"
|
path="/insurance-status"
|
||||||
|
|||||||
@@ -16,10 +16,15 @@ import {
|
|||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { useMemo } from "react";
|
import { useMemo } from "react";
|
||||||
import { useSidebar } from "@/components/ui/sidebar";
|
import { useSidebar } from "@/components/ui/sidebar";
|
||||||
|
import { useAuth } from "@/hooks/use-auth";
|
||||||
|
|
||||||
export function Sidebar() {
|
export function Sidebar() {
|
||||||
const [location] = useLocation();
|
const [location] = useLocation();
|
||||||
const { state, openMobile, setOpenMobile } = useSidebar(); // "expanded" | "collapsed"
|
const { state, openMobile, setOpenMobile } = useSidebar();
|
||||||
|
const { user } = useAuth();
|
||||||
|
const isAdmin =
|
||||||
|
user?.role?.toUpperCase() === "ADMIN" ||
|
||||||
|
user?.username?.toLowerCase() === "admin";
|
||||||
|
|
||||||
const navItems = useMemo(
|
const navItems = useMemo(
|
||||||
() => [
|
() => [
|
||||||
@@ -78,13 +83,17 @@ export function Sidebar() {
|
|||||||
path: "/database-management",
|
path: "/database-management",
|
||||||
icon: <Database className="h-5 w-5" />,
|
icon: <Database className="h-5 w-5" />,
|
||||||
},
|
},
|
||||||
{
|
...(isAdmin
|
||||||
name: "Settings",
|
? [
|
||||||
path: "/settings",
|
{
|
||||||
icon: <Settings className="h-5 w-5" />,
|
name: "Settings",
|
||||||
},
|
path: "/settings",
|
||||||
|
icon: <Settings className="h-5 w-5" />,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []),
|
||||||
],
|
],
|
||||||
[]
|
[isAdmin]
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -70,9 +70,12 @@ export function TopAppBar() {
|
|||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<DropdownMenuItem>{user?.username}</DropdownMenuItem>
|
<DropdownMenuItem>{user?.username}</DropdownMenuItem>
|
||||||
<DropdownMenuItem>My Profile</DropdownMenuItem>
|
<DropdownMenuItem>My Profile</DropdownMenuItem>
|
||||||
<DropdownMenuItem onClick={() => setLocation("/settings")}>
|
{(user?.role?.toUpperCase() === "ADMIN" ||
|
||||||
Account Settings
|
user?.username?.toLowerCase() === "admin") && (
|
||||||
</DropdownMenuItem>
|
<DropdownMenuItem onClick={() => setLocation("/settings")}>
|
||||||
|
Account Settings
|
||||||
|
</DropdownMenuItem>
|
||||||
|
)}
|
||||||
<DropdownMenuSeparator />
|
<DropdownMenuSeparator />
|
||||||
<DropdownMenuItem onClick={handleLogout}>
|
<DropdownMenuItem onClick={handleLogout}>
|
||||||
Log out
|
Log out
|
||||||
|
|||||||
@@ -4,28 +4,32 @@ import { useAuth } from "@/hooks/use-auth";
|
|||||||
import { Suspense } from "react";
|
import { Suspense } from "react";
|
||||||
import { Redirect, Route } from "wouter";
|
import { Redirect, Route } from "wouter";
|
||||||
|
|
||||||
type ComponentLike = React.ComponentType; // works for both lazy() and regular components
|
type ComponentLike = React.ComponentType;
|
||||||
|
|
||||||
export function ProtectedRoute({
|
export function ProtectedRoute({
|
||||||
path,
|
path,
|
||||||
component: Component,
|
component: Component,
|
||||||
|
adminOnly,
|
||||||
}: {
|
}: {
|
||||||
path: string;
|
path: string;
|
||||||
component: ComponentLike;
|
component: ComponentLike;
|
||||||
|
adminOnly?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const { user, isLoading } = useAuth();
|
const { user, isLoading } = useAuth();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Route path={path}>
|
<Route path={path}>
|
||||||
{/* While auth is resolving: keep layout visible and show a small spinner in the content area */}
|
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<AppLayout>
|
<AppLayout>
|
||||||
<LoadingScreen />
|
<LoadingScreen />
|
||||||
</AppLayout>
|
</AppLayout>
|
||||||
) : !user ? (
|
) : !user ? (
|
||||||
<Redirect to="/auth" />
|
<Redirect to="/auth" />
|
||||||
|
) : adminOnly &&
|
||||||
|
user.role?.toUpperCase() !== "ADMIN" &&
|
||||||
|
user.username?.toLowerCase() !== "admin" ? (
|
||||||
|
<Redirect to="/dashboard" />
|
||||||
) : (
|
) : (
|
||||||
// Authenticated: render page inside layout. Lazy pages load with an in-layout spinner.
|
|
||||||
<AppLayout>
|
<AppLayout>
|
||||||
<Suspense fallback={<LoadingScreen />}>
|
<Suspense fallback={<LoadingScreen />}>
|
||||||
<Component />
|
<Component />
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { CredentialTable } from "@/components/settings/insuranceCredTable";
|
|||||||
import { useAuth } from "@/hooks/use-auth";
|
import { useAuth } from "@/hooks/use-auth";
|
||||||
import { Staff } from "@repo/db/types";
|
import { Staff } from "@repo/db/types";
|
||||||
|
|
||||||
|
type SafeUser = { id: number; username: string; role: "ADMIN" | "USER" };
|
||||||
|
|
||||||
export default function SettingsPage() {
|
export default function SettingsPage() {
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
@@ -215,7 +216,84 @@ export default function SettingsPage() {
|
|||||||
`Viewing staff member:\n${staff.name} (${staff.email || "No email"})`
|
`Viewing staff member:\n${staff.name} (${staff.email || "No email"})`
|
||||||
);
|
);
|
||||||
|
|
||||||
// MANAGE USER
|
// --- Users control (list, add, edit password, delete) ---
|
||||||
|
const {
|
||||||
|
data: usersList = [],
|
||||||
|
isLoading: usersLoading,
|
||||||
|
isError: usersError,
|
||||||
|
error: usersErrorObj,
|
||||||
|
} = useQuery<SafeUser[]>({
|
||||||
|
queryKey: ["/api/users/list"],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await apiRequest("GET", "/api/users/list");
|
||||||
|
if (!res.ok) throw new Error("Failed to fetch users");
|
||||||
|
return res.json();
|
||||||
|
},
|
||||||
|
staleTime: 1000 * 60 * 2,
|
||||||
|
});
|
||||||
|
|
||||||
|
const addUserMutate = useMutation<SafeUser, Error, { username: string; password: string; role?: "ADMIN" | "USER" }>({
|
||||||
|
mutationFn: async (data) => {
|
||||||
|
const res = await apiRequest("POST", "/api/users/", data);
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = await res.json().catch(() => null);
|
||||||
|
throw new Error(err?.error || "Failed to add user");
|
||||||
|
}
|
||||||
|
return res.json();
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["/api/users/list"] });
|
||||||
|
setAddUserModalOpen(false);
|
||||||
|
toast({ title: "User Added", description: "User created successfully.", variant: "default" });
|
||||||
|
},
|
||||||
|
onError: (e: any) => {
|
||||||
|
toast({ title: "Error", description: e?.message || "Failed to add user", variant: "destructive" });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateUserPasswordMutate = useMutation<SafeUser, Error, { id: number; password: string }>({
|
||||||
|
mutationFn: async ({ id, password }) => {
|
||||||
|
const res = await apiRequest("PUT", `/api/users/${id}`, { password });
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = await res.json().catch(() => null);
|
||||||
|
throw new Error(err?.error || "Failed to update password");
|
||||||
|
}
|
||||||
|
return res.json();
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["/api/users/list"] });
|
||||||
|
setEditPasswordUser(null);
|
||||||
|
toast({ title: "Password Updated", description: "Password changed successfully.", variant: "default" });
|
||||||
|
},
|
||||||
|
onError: (e: any) => {
|
||||||
|
toast({ title: "Error", description: e?.message || "Failed to update password", variant: "destructive" });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const deleteUserMutate = useMutation<number, Error, number>({
|
||||||
|
mutationFn: async (id) => {
|
||||||
|
const res = await apiRequest("DELETE", `/api/users/${id}`);
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = await res.json().catch(() => null);
|
||||||
|
throw new Error(err?.error || "Failed to delete user");
|
||||||
|
}
|
||||||
|
return id;
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
setUserToDelete(null);
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["/api/users/list"] });
|
||||||
|
toast({ title: "User Removed", description: "User deleted.", variant: "default" });
|
||||||
|
},
|
||||||
|
onError: (e: any) => {
|
||||||
|
toast({ title: "Error", description: e?.message || "Failed to delete user", variant: "destructive" });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const [addUserModalOpen, setAddUserModalOpen] = useState(false);
|
||||||
|
const [editPasswordUser, setEditPasswordUser] = useState<SafeUser | null>(null);
|
||||||
|
const [userToDelete, setUserToDelete] = useState<SafeUser | null>(null);
|
||||||
|
|
||||||
|
// MANAGE USER (current user profile)
|
||||||
const [usernameUser, setUsernameUser] = useState("");
|
const [usernameUser, setUsernameUser] = useState("");
|
||||||
|
|
||||||
//fetch user
|
//fetch user
|
||||||
@@ -303,10 +381,73 @@ export default function SettingsPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* User Setting section */}
|
{/* Users control section */}
|
||||||
|
<Card className="mt-6">
|
||||||
|
<CardContent className="py-6">
|
||||||
|
<div className="flex justify-between items-center mb-4">
|
||||||
|
<h3 className="text-lg font-semibold">User Accounts</h3>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setAddUserModalOpen(true)}
|
||||||
|
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
|
||||||
|
>
|
||||||
|
Add User
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="min-w-full divide-y divide-gray-200">
|
||||||
|
<thead className="bg-gray-50">
|
||||||
|
<tr>
|
||||||
|
<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Username</th>
|
||||||
|
<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Role</th>
|
||||||
|
<th className="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase">Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="bg-white divide-y divide-gray-200">
|
||||||
|
{usersLoading && (
|
||||||
|
<tr><td colSpan={3} className="px-4 py-4 text-gray-500">Loading users...</td></tr>
|
||||||
|
)}
|
||||||
|
{usersError && (
|
||||||
|
<tr><td colSpan={3} className="px-4 py-4 text-red-600">{(usersErrorObj as Error)?.message}</td></tr>
|
||||||
|
)}
|
||||||
|
{!usersLoading && !usersError && usersList.filter((u) => u.id !== user?.id).length === 0 && (
|
||||||
|
<tr><td colSpan={3} className="px-4 py-4 text-gray-500">No other users.</td></tr>
|
||||||
|
)}
|
||||||
|
{!usersLoading && usersList.filter((u) => u.id !== user?.id).map((u) => (
|
||||||
|
<tr key={u.id}>
|
||||||
|
<td className="px-4 py-2">
|
||||||
|
<span>{u.username}</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-2">{u.role}</td>
|
||||||
|
<td className="px-4 py-2 text-right space-x-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setEditPasswordUser(u)}
|
||||||
|
className="text-blue-600 hover:underline"
|
||||||
|
>
|
||||||
|
Edit password
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setUserToDelete(u)}
|
||||||
|
className="text-red-600 hover:underline"
|
||||||
|
title="Delete user"
|
||||||
|
>
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* User Setting section (current user profile) */}
|
||||||
<Card className="mt-6">
|
<Card className="mt-6">
|
||||||
<CardContent className="space-y-4 py-6">
|
<CardContent className="space-y-4 py-6">
|
||||||
<h3 className="text-lg font-semibold">User Settings</h3>
|
<h3 className="text-lg font-semibold">Admin Setting</h3>
|
||||||
<form
|
<form
|
||||||
className="space-y-4"
|
className="space-y-4"
|
||||||
onSubmit={(e) => {
|
onSubmit={(e) => {
|
||||||
@@ -358,6 +499,96 @@ export default function SettingsPage() {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
{/* Add User modal */}
|
||||||
|
{addUserModalOpen && (
|
||||||
|
<div className="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center z-50">
|
||||||
|
<div className="bg-white rounded-lg p-6 w-full max-w-md shadow-lg">
|
||||||
|
<h2 className="text-lg font-bold mb-4">Add User</h2>
|
||||||
|
<form
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const form = e.currentTarget;
|
||||||
|
const username = (form.querySelector('[name="new-username"]') as HTMLInputElement)?.value?.trim();
|
||||||
|
const password = (form.querySelector('[name="new-password"]') as HTMLInputElement)?.value;
|
||||||
|
const role = (form.querySelector('[name="new-role"]') as HTMLSelectElement)?.value as "ADMIN" | "USER";
|
||||||
|
if (!username || !password) {
|
||||||
|
toast({ title: "Error", description: "Username and password are required.", variant: "destructive" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
addUserMutate.mutate({ username, password, role: role || "USER" });
|
||||||
|
}}
|
||||||
|
className="space-y-4"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium">Username</label>
|
||||||
|
<input name="new-username" type="text" required className="mt-1 p-2 border rounded w-full" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium">Password</label>
|
||||||
|
<input name="new-password" type="password" required className="mt-1 p-2 border rounded w-full" placeholder="••••••••" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium">Role</label>
|
||||||
|
<select name="new-role" className="mt-1 p-2 border rounded w-full" defaultValue="USER">
|
||||||
|
<option value="USER">User</option>
|
||||||
|
<option value="ADMIN">Admin</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2 justify-end">
|
||||||
|
<button type="button" onClick={() => setAddUserModalOpen(false)} className="px-4 py-2 border rounded hover:bg-gray-100">
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button type="submit" disabled={addUserMutate.isPending} className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50">
|
||||||
|
{addUserMutate.isPending ? "Adding..." : "Add User"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Edit password modal */}
|
||||||
|
{editPasswordUser && (
|
||||||
|
<div className="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center z-50">
|
||||||
|
<div className="bg-white rounded-lg p-6 w-full max-w-md shadow-lg">
|
||||||
|
<h2 className="text-lg font-bold mb-4">Change password for {editPasswordUser.username}</h2>
|
||||||
|
<form
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const form = e.currentTarget;
|
||||||
|
const password = (form.querySelector('[name="edit-password"]') as HTMLInputElement)?.value;
|
||||||
|
if (!password?.trim()) {
|
||||||
|
toast({ title: "Error", description: "Password is required.", variant: "destructive" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
updateUserPasswordMutate.mutate({ id: editPasswordUser.id, password });
|
||||||
|
}}
|
||||||
|
className="space-y-4"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium">New password</label>
|
||||||
|
<input name="edit-password" type="password" required className="mt-1 p-2 border rounded w-full" placeholder="••••••••" />
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2 justify-end">
|
||||||
|
<button type="button" onClick={() => setEditPasswordUser(null)} className="px-4 py-2 border rounded hover:bg-gray-100">
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button type="submit" disabled={updateUserPasswordMutate.isPending} className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50">
|
||||||
|
{updateUserPasswordMutate.isPending ? "Saving..." : "Save"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<DeleteConfirmationDialog
|
||||||
|
isOpen={!!userToDelete}
|
||||||
|
onConfirm={() => userToDelete && deleteUserMutate.mutate(userToDelete.id)}
|
||||||
|
onCancel={() => setUserToDelete(null)}
|
||||||
|
entityName={userToDelete?.username}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Credential Section */}
|
{/* Credential Section */}
|
||||||
<div className="mt-6">
|
<div className="mt-6">
|
||||||
<CredentialTable />
|
<CredentialTable />
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ sudo bash -c 'echo -e "[global]\nbreak-system-packages = true" > /etc/pip.conf'
|
|||||||
|
|
||||||
-- this is optional, either create a venv for separate python based app in repo, or simply have global permissson by this.
|
-- this is optional, either create a venv for separate python based app in repo, or simply have global permissson by this.
|
||||||
|
|
||||||
## 4. Install PostgreSQL
|
## 5. Install PostgreSQL
|
||||||
```bash
|
```bash
|
||||||
sudo apt install -y postgresql postgresql-contrib
|
sudo apt install -y postgresql postgresql-contrib
|
||||||
|
|
||||||
@@ -37,7 +37,7 @@ sudo systemctl start postgresql
|
|||||||
sudo systemctl enable postgresql
|
sudo systemctl enable postgresql
|
||||||
```
|
```
|
||||||
|
|
||||||
## 5. Install Git
|
## 6. Install Git
|
||||||
```bash
|
```bash
|
||||||
sudo apt install -y git
|
sudo apt install -y git
|
||||||
```
|
```
|
||||||
@@ -18,10 +18,16 @@ datasource db {
|
|||||||
provider = "postgresql"
|
provider = "postgresql"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum UserRole {
|
||||||
|
ADMIN
|
||||||
|
USER
|
||||||
|
}
|
||||||
|
|
||||||
model User {
|
model User {
|
||||||
id Int @id @default(autoincrement())
|
id Int @id @default(autoincrement())
|
||||||
username String @unique
|
username String @unique
|
||||||
password String
|
password String
|
||||||
|
role UserRole @default(USER)
|
||||||
patients Patient[]
|
patients Patient[]
|
||||||
appointments Appointment[]
|
appointments Appointment[]
|
||||||
staff Staff[]
|
staff Staff[]
|
||||||
|
|||||||
@@ -6,11 +6,11 @@ function formatTime(date: Date): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
// Create multiple users
|
// Create multiple users (role: ADMIN | USER)
|
||||||
const users = await prisma.user.createMany({
|
const users = await prisma.user.createMany({
|
||||||
data: [
|
data: [
|
||||||
{ username: "admin2", password: "123456" },
|
{ username: "admin2", password: "123456", role: "ADMIN" },
|
||||||
{ username: "bob", password: "123456" },
|
{ username: "bob", password: "123456", role: "USER" },
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user