delete user functionality
This commit is contained in:
parent
154d0d5fb6
commit
08c2ff278f
|
@ -0,0 +1,51 @@
|
||||||
|
import toast from "react-hot-toast";
|
||||||
|
import Modal from "../Modal";
|
||||||
|
import useUserStore from "@/store/admin/users";
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
onClose: Function;
|
||||||
|
userId: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function DeleteUserModal({ onClose, userId }: Props) {
|
||||||
|
const { removeUser } = useUserStore();
|
||||||
|
|
||||||
|
const deleteUser = async () => {
|
||||||
|
const load = toast.loading("Deleting...");
|
||||||
|
|
||||||
|
const response = await removeUser(userId);
|
||||||
|
|
||||||
|
toast.dismiss(load);
|
||||||
|
|
||||||
|
response.ok && toast.success(`User Deleted.`);
|
||||||
|
|
||||||
|
onClose();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal toggleModal={onClose}>
|
||||||
|
<p className="text-xl font-thin text-red-500">Delete User</p>
|
||||||
|
|
||||||
|
<div className="divider mb-3 mt-1"></div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
<p>Are you sure you want to remove this user?</p>
|
||||||
|
|
||||||
|
<div role="alert" className="alert alert-warning">
|
||||||
|
<i className="bi-exclamation-triangle text-xl" />
|
||||||
|
<span>
|
||||||
|
<b>Warning:</b> This action is irreversible!
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
className={`ml-auto btn w-fit text-white flex items-center gap-2 duration-100 bg-red-500 hover:bg-red-400 hover:dark:bg-red-600 cursor-pointer`}
|
||||||
|
onClick={deleteUser}
|
||||||
|
>
|
||||||
|
<i className="bi-trash text-xl" />
|
||||||
|
Delete, I know what I'm doing
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
|
@ -10,7 +10,8 @@ const authentikEnabled = process.env.AUTHENTIK_CLIENT_SECRET;
|
||||||
|
|
||||||
export default async function deleteUserById(
|
export default async function deleteUserById(
|
||||||
userId: number,
|
userId: number,
|
||||||
body: DeleteUserBody
|
body: DeleteUserBody,
|
||||||
|
isServerAdmin: boolean
|
||||||
) {
|
) {
|
||||||
// First, we retrieve the user from the database
|
// First, we retrieve the user from the database
|
||||||
const user = await prisma.user.findUnique({
|
const user = await prisma.user.findUnique({
|
||||||
|
@ -25,13 +26,13 @@ export default async function deleteUserById(
|
||||||
}
|
}
|
||||||
|
|
||||||
// Then, we check if the provided password matches the one stored in the database (disabled in Keycloak integration)
|
// Then, we check if the provided password matches the one stored in the database (disabled in Keycloak integration)
|
||||||
if (!keycloakEnabled && !authentikEnabled) {
|
if (!keycloakEnabled && !authentikEnabled && !isServerAdmin) {
|
||||||
const isPasswordValid = bcrypt.compareSync(
|
const isPasswordValid = bcrypt.compareSync(
|
||||||
body.password,
|
body.password,
|
||||||
user.password as string
|
user.password as string
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!isPasswordValid) {
|
if (!isPasswordValid && !isServerAdmin) {
|
||||||
return {
|
return {
|
||||||
response: "Invalid credentials.",
|
response: "Invalid credentials.",
|
||||||
status: 401, // Unauthorized
|
status: 401, // Unauthorized
|
||||||
|
@ -43,6 +44,11 @@ export default async function deleteUserById(
|
||||||
await prisma
|
await prisma
|
||||||
.$transaction(
|
.$transaction(
|
||||||
async (prisma) => {
|
async (prisma) => {
|
||||||
|
// Delete Access Tokens
|
||||||
|
await prisma.accessToken.deleteMany({
|
||||||
|
where: { userId },
|
||||||
|
});
|
||||||
|
|
||||||
// Delete whitelisted users
|
// Delete whitelisted users
|
||||||
await prisma.whitelistedUser.deleteMany({
|
await prisma.whitelistedUser.deleteMany({
|
||||||
where: { userId },
|
where: { userId },
|
||||||
|
|
|
@ -1,6 +1,8 @@
|
||||||
|
import DeleteUserModal from "@/components/ModalContent/DeleteUserModal";
|
||||||
|
import useUserStore from "@/store/admin/users";
|
||||||
import { User as U } from "@prisma/client";
|
import { User as U } from "@prisma/client";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useEffect, useState } from "react";
|
import { Fragment, useEffect, useState } from "react";
|
||||||
|
|
||||||
interface User extends U {
|
interface User extends U {
|
||||||
subscriptions: {
|
subscriptions: {
|
||||||
|
@ -8,12 +10,22 @@ interface User extends U {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type UserModal = {
|
||||||
|
isOpen: boolean;
|
||||||
|
userId: number | null;
|
||||||
|
};
|
||||||
|
|
||||||
export default function Admin() {
|
export default function Admin() {
|
||||||
const [users, setUsers] = useState<User[]>();
|
const { users, setUsers } = useUserStore();
|
||||||
|
|
||||||
const [searchQuery, setSearchQuery] = useState("");
|
const [searchQuery, setSearchQuery] = useState("");
|
||||||
const [filteredUsers, setFilteredUsers] = useState<User[]>();
|
const [filteredUsers, setFilteredUsers] = useState<User[]>();
|
||||||
|
|
||||||
|
const [deleteUserModal, setDeleteUserModal] = useState<UserModal>({
|
||||||
|
isOpen: false,
|
||||||
|
userId: null,
|
||||||
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// fetch users
|
// fetch users
|
||||||
fetch("/api/v1/users")
|
fetch("/api/v1/users")
|
||||||
|
@ -31,7 +43,7 @@ export default function Admin() {
|
||||||
>
|
>
|
||||||
<i className="bi-chevron-left text-xl"></i>
|
<i className="bi-chevron-left text-xl"></i>
|
||||||
</Link>
|
</Link>
|
||||||
<p className="capitalize sm:text-3xl text-2xl font-thin inline">
|
<p className="capitalize text-3xl font-thin inline">
|
||||||
User Administration
|
User Administration
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
@ -76,11 +88,11 @@ export default function Admin() {
|
||||||
<div className="divider my-3"></div>
|
<div className="divider my-3"></div>
|
||||||
|
|
||||||
{filteredUsers && filteredUsers.length > 0 && searchQuery !== "" ? (
|
{filteredUsers && filteredUsers.length > 0 && searchQuery !== "" ? (
|
||||||
UserLising(filteredUsers)
|
UserListing(filteredUsers, deleteUserModal, setDeleteUserModal)
|
||||||
) : searchQuery !== "" ? (
|
) : searchQuery !== "" ? (
|
||||||
<p>No users found with the given search query.</p>
|
<p>No users found with the given search query.</p>
|
||||||
) : users && users.length > 0 ? (
|
) : users && users.length > 0 ? (
|
||||||
UserLising(users)
|
UserListing(users, deleteUserModal, setDeleteUserModal)
|
||||||
) : (
|
) : (
|
||||||
<p>No users found.</p>
|
<p>No users found.</p>
|
||||||
)}
|
)}
|
||||||
|
@ -88,7 +100,11 @@ export default function Admin() {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const UserLising = (users: User[]) => {
|
const UserListing = (
|
||||||
|
users: User[],
|
||||||
|
deleteUserModal: UserModal,
|
||||||
|
setDeleteUserModal: Function
|
||||||
|
) => {
|
||||||
return (
|
return (
|
||||||
<div className="overflow-x-auto whitespace-nowrap w-full">
|
<div className="overflow-x-auto whitespace-nowrap w-full">
|
||||||
<table className="table table-zebra w-full">
|
<table className="table table-zebra w-full">
|
||||||
|
@ -106,7 +122,7 @@ const UserLising = (users: User[]) => {
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{users.map((user, index) => (
|
{users.map((user, index) => (
|
||||||
<tr key={user.id}>
|
<tr key={index}>
|
||||||
<td className="rounded-tl">{index + 1}</td>
|
<td className="rounded-tl">{index + 1}</td>
|
||||||
<td>{user.username}</td>
|
<td>{user.username}</td>
|
||||||
{process.env.NEXT_PUBLIC_EMAIL_PROVIDER === "true" && (
|
{process.env.NEXT_PUBLIC_EMAIL_PROVIDER === "true" && (
|
||||||
|
@ -117,7 +133,12 @@ const UserLising = (users: User[]) => {
|
||||||
)}
|
)}
|
||||||
<td>{new Date(user.createdAt).toLocaleString()}</td>
|
<td>{new Date(user.createdAt).toLocaleString()}</td>
|
||||||
<td>
|
<td>
|
||||||
<button className="btn btn-sm btn-ghost">
|
<button
|
||||||
|
className="btn btn-sm btn-ghost"
|
||||||
|
onClick={() =>
|
||||||
|
setDeleteUserModal({ isOpen: true, userId: user.id })
|
||||||
|
}
|
||||||
|
>
|
||||||
<i className="bi bi-trash"></i>
|
<i className="bi bi-trash"></i>
|
||||||
</button>
|
</button>
|
||||||
</td>
|
</td>
|
||||||
|
@ -125,6 +146,13 @@ const UserLising = (users: User[]) => {
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
|
||||||
|
{deleteUserModal.isOpen && deleteUserModal.userId ? (
|
||||||
|
<DeleteUserModal
|
||||||
|
onClose={() => setDeleteUserModal({ isOpen: false, userId: null })}
|
||||||
|
userId={deleteUserModal.userId}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
@ -16,9 +16,17 @@ export default async function users(req: NextApiRequest, res: NextApiResponse) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const userId = token?.id;
|
const user = await prisma.user.findUnique({
|
||||||
|
where: {
|
||||||
|
id: token?.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
if (userId !== Number(req.query.id))
|
const isServerAdmin = process.env.ADMINISTRATOR === user?.username;
|
||||||
|
|
||||||
|
const userId = isServerAdmin ? Number(req.query.id) : token.id;
|
||||||
|
|
||||||
|
if (userId !== Number(req.query.id) && !isServerAdmin)
|
||||||
return res.status(401).json({ response: "Permission denied." });
|
return res.status(401).json({ response: "Permission denied." });
|
||||||
|
|
||||||
if (req.method === "GET") {
|
if (req.method === "GET") {
|
||||||
|
@ -53,7 +61,7 @@ export default async function users(req: NextApiRequest, res: NextApiResponse) {
|
||||||
const updated = await updateUserById(userId, req.body);
|
const updated = await updateUserById(userId, req.body);
|
||||||
return res.status(updated.status).json({ response: updated.response });
|
return res.status(updated.status).json({ response: updated.response });
|
||||||
} else if (req.method === "DELETE") {
|
} else if (req.method === "DELETE") {
|
||||||
const updated = await deleteUserById(userId, req.body);
|
const updated = await deleteUserById(userId, req.body, isServerAdmin);
|
||||||
return res.status(updated.status).json({ response: updated.response });
|
return res.status(updated.status).json({ response: updated.response });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,61 @@
|
||||||
|
import { User as U } from "@prisma/client";
|
||||||
|
import { create } from "zustand";
|
||||||
|
|
||||||
|
interface User extends U {
|
||||||
|
subscriptions: {
|
||||||
|
active: boolean;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
type ResponseObject = {
|
||||||
|
ok: boolean;
|
||||||
|
data: object | string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type UserStore = {
|
||||||
|
users: User[];
|
||||||
|
setUsers: (users: User[]) => void;
|
||||||
|
addUser: () => Promise<ResponseObject>;
|
||||||
|
removeUser: (userId: number) => Promise<ResponseObject>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const useUserStore = create<UserStore>((set) => ({
|
||||||
|
users: [],
|
||||||
|
setUsers: async () => {
|
||||||
|
const response = await fetch("/api/v1/users");
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (response.ok) set({ users: data.response });
|
||||||
|
},
|
||||||
|
addUser: async () => {
|
||||||
|
const response = await fetch("/api/v1/users", {
|
||||||
|
method: "POST",
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (response.ok)
|
||||||
|
set((state) => ({
|
||||||
|
users: [...state.users, data.response],
|
||||||
|
}));
|
||||||
|
|
||||||
|
return { ok: response.ok, data: data.response };
|
||||||
|
},
|
||||||
|
removeUser: async (userId) => {
|
||||||
|
const response = await fetch(`/api/v1/users/${userId}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (response.ok)
|
||||||
|
set((state) => ({
|
||||||
|
users: state.users.filter((user) => user.id !== userId),
|
||||||
|
}));
|
||||||
|
|
||||||
|
return { ok: response.ok, data: data.response };
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
export default useUserStore;
|
Ŝarĝante…
Reference in New Issue