Merge pull request #592 from linkwarden/user-administration

User administration
This commit is contained in:
Daniel 2024-05-04 00:05:07 +03:30 committed by GitHub
commit f1655aad15
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 549 additions and 23 deletions

View File

@ -22,6 +22,7 @@ BROWSER_TIMEOUT=
IGNORE_UNAUTHORIZED_CA=
IGNORE_HTTPS_ERRORS=
IGNORE_URL_SIZE_LIMIT=
ADMINISTRATOR=
# AWS S3 Settings
SPACES_KEY=

View File

@ -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&apos;m doing
</button>
</div>
</Modal>
);
}

View File

@ -0,0 +1,133 @@
import toast from "react-hot-toast";
import Modal from "../Modal";
import useUserStore from "@/store/admin/users";
import TextInput from "../TextInput";
import { FormEvent, useState } from "react";
type Props = {
onClose: Function;
};
type FormData = {
name: string;
username?: string;
email?: string;
password: string;
};
const emailEnabled = process.env.NEXT_PUBLIC_EMAIL_PROVIDER === "true";
export default function NewUserModal({ onClose }: Props) {
const { addUser } = useUserStore();
const [form, setForm] = useState<FormData>({
name: "",
username: "",
email: emailEnabled ? "" : undefined,
password: "",
});
const [submitLoader, setSubmitLoader] = useState(false);
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!submitLoader) {
const checkFields = () => {
if (emailEnabled) {
return form.name !== "" && form.email !== "" && form.password !== "";
} else {
return (
form.name !== "" && form.username !== "" && form.password !== ""
);
}
};
if (checkFields()) {
if (form.password.length < 8)
return toast.error("Passwords must be at least 8 characters.");
setSubmitLoader(true);
const load = toast.loading("Creating Account...");
const response = await addUser(form);
toast.dismiss(load);
setSubmitLoader(false);
if (response.ok) {
toast.success("User Created!");
onClose();
} else {
toast.error(response.data as string);
}
} else {
toast.error("Please fill out all the fields.");
}
}
}
return (
<Modal toggleModal={onClose}>
<p className="text-xl font-thin">Create New User</p>
<div className="divider mb-3 mt-1"></div>
<form onSubmit={submit}>
<div className="grid sm:grid-cols-2 gap-3">
<div>
<p className="mb-2">Display Name</p>
<TextInput
placeholder="Johnny"
className="bg-base-200"
onChange={(e) => setForm({ ...form, name: e.target.value })}
value={form.name}
/>
</div>
{emailEnabled ? (
<div>
<p className="mb-2">Username</p>
<TextInput
placeholder="john"
className="bg-base-200"
onChange={(e) => setForm({ ...form, username: e.target.value })}
value={form.username}
/>
</div>
) : undefined}
<div>
<p className="mb-2">Email</p>
<TextInput
placeholder="johnny@example.com"
className="bg-base-200"
onChange={(e) => setForm({ ...form, email: e.target.value })}
value={form.email}
/>
</div>
<div>
<p className="mb-2">Password</p>
<TextInput
placeholder="••••••••••••••"
className="bg-base-200"
onChange={(e) => setForm({ ...form, password: e.target.value })}
value={form.password}
/>
</div>
</div>
<div className="flex justify-between items-center mt-5">
<button
className="btn btn-accent dark:border-violet-400 text-white ml-auto"
type="submit"
>
Create User
</button>
</div>
</form>
</Modal>
);
}

View File

@ -0,0 +1,21 @@
import { prisma } from "@/lib/api/db";
export default async function getUsers() {
// Get all users
const users = await prisma.user.findMany({
select: {
id: true,
username: true,
email: true,
emailVerified: true,
subscriptions: {
select: {
active: true,
},
},
createdAt: true,
},
});
return { response: users, status: 200 };
}

View File

@ -1,9 +1,11 @@
import { prisma } from "@/lib/api/db";
import type { NextApiRequest, NextApiResponse } from "next";
import bcrypt from "bcrypt";
import verifyUser from "../../verifyUser";
const emailEnabled =
process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;
const stripeEnabled = process.env.STRIPE_SECRET_KEY ? true : false;
interface Data {
response: string | object;
@ -20,7 +22,15 @@ export default async function postUser(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
if (process.env.NEXT_PUBLIC_DISABLE_REGISTRATION === "true") {
let isServerAdmin = false;
const user = await verifyUser({ req, res });
if (process.env.ADMINISTRATOR === user?.username) isServerAdmin = true;
if (
process.env.NEXT_PUBLIC_DISABLE_REGISTRATION === "true" &&
!isServerAdmin
) {
return res.status(400).json({ response: "Registration is disabled." });
}
@ -57,13 +67,16 @@ export default async function postUser(
});
const checkIfUserExists = await prisma.user.findFirst({
where: emailEnabled
? {
where: {
OR: [
{
email: body.email?.toLowerCase().trim(),
}
: {
},
{
username: (body.username as string).toLowerCase().trim(),
},
],
},
});
if (!checkIfUserExists) {
@ -71,6 +84,47 @@ export default async function postUser(
const hashedPassword = bcrypt.hashSync(body.password, saltRounds);
// Subscription dates
const currentPeriodStart = new Date();
const currentPeriodEnd = new Date();
currentPeriodEnd.setFullYear(currentPeriodEnd.getFullYear() + 1000); // end date is in 1000 years...
if (isServerAdmin) {
const user = await prisma.user.create({
data: {
name: body.name,
username: (body.username as string).toLowerCase().trim(),
email: emailEnabled ? body.email?.toLowerCase().trim() : undefined,
password: hashedPassword,
emailVerified: new Date(),
subscriptions: stripeEnabled
? {
create: {
stripeSubscriptionId:
"fake_sub_" + Math.round(Math.random() * 10000000000000),
active: true,
currentPeriodStart,
currentPeriodEnd,
},
}
: undefined,
},
select: {
id: true,
username: true,
email: true,
emailVerified: true,
subscriptions: {
select: {
active: true,
},
},
createdAt: true,
},
});
return res.status(201).json({ response: user });
} else {
await prisma.user.create({
data: {
name: body.name,
@ -83,9 +137,10 @@ export default async function postUser(
});
return res.status(201).json({ response: "User successfully created." });
}
} else if (checkIfUserExists) {
return res.status(400).json({
response: `${emailEnabled ? "Email" : "Username"} already exists.`,
response: `Email or Username already exists.`,
});
}
}

View File

@ -10,7 +10,8 @@ const authentikEnabled = process.env.AUTHENTIK_CLIENT_SECRET;
export default async function deleteUserById(
userId: number,
body: DeleteUserBody
body: DeleteUserBody,
isServerAdmin?: boolean
) {
// First, we retrieve the user from the database
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)
if (!keycloakEnabled && !authentikEnabled) {
if (!keycloakEnabled && !authentikEnabled && !isServerAdmin) {
const isPasswordValid = bcrypt.compareSync(
body.password,
user.password as string
);
if (!isPasswordValid) {
if (!isPasswordValid && !isServerAdmin) {
return {
response: "Invalid credentials.",
status: 401, // Unauthorized
@ -43,6 +44,11 @@ export default async function deleteUserById(
await prisma
.$transaction(
async (prisma) => {
// Delete Access Tokens
await prisma.accessToken.deleteMany({
where: { userId },
});
// Delete whitelisted users
await prisma.whitelistedUser.deleteMany({
where: { userId },
@ -87,6 +93,7 @@ export default async function deleteUserById(
await prisma.subscription.delete({
where: { userId },
});
// .catch((err) => console.log(err));
await prisma.usersAndCollections.deleteMany({
where: {

174
pages/admin.tsx Normal file
View File

@ -0,0 +1,174 @@
import DeleteUserModal from "@/components/ModalContent/DeleteUserModal";
import NewUserModal from "@/components/ModalContent/NewUserModal";
import useUserStore from "@/store/admin/users";
import { User as U } from "@prisma/client";
import Link from "next/link";
import { Fragment, useEffect, useState } from "react";
interface User extends U {
subscriptions: {
active: boolean;
};
}
type UserModal = {
isOpen: boolean;
userId: number | null;
};
export default function Admin() {
const { users, setUsers } = useUserStore();
const [searchQuery, setSearchQuery] = useState("");
const [filteredUsers, setFilteredUsers] = useState<User[]>();
const [deleteUserModal, setDeleteUserModal] = useState<UserModal>({
isOpen: false,
userId: null,
});
const [newUserModal, setNewUserModal] = useState(false);
useEffect(() => {
setUsers();
}, []);
return (
<div className="max-w-6xl mx-auto p-5">
<div className="flex sm:flex-row flex-col justify-between gap-2">
<div className="gap-2 inline-flex items-center">
<Link
href="/dashboard"
className="text-neutral btn btn-square btn-sm btn-ghost"
>
<i className="bi-chevron-left text-xl"></i>
</Link>
<p className="capitalize text-3xl font-thin inline">
User Administration
</p>
</div>
<div className="flex items-center relative justify-between gap-2">
<div>
<label
htmlFor="search-box"
className="inline-flex items-center w-fit absolute left-1 pointer-events-none rounded-md p-1 text-primary"
>
<i className="bi-search"></i>
</label>
<input
id="search-box"
type="text"
placeholder={"Search for Users"}
value={searchQuery}
onChange={(e) => {
setSearchQuery(e.target.value);
if (users) {
setFilteredUsers(
users.filter((user) =>
JSON.stringify(user)
.toLowerCase()
.includes(e.target.value.toLowerCase())
)
);
}
}}
className="border border-neutral-content bg-base-200 focus:border-primary py-1 rounded-md pl-9 pr-2 w-full max-w-[15rem] md:w-[15rem] md:max-w-full duration-200 outline-none"
/>
</div>
<div
onClick={() => setNewUserModal(true)}
className="flex items-center btn btn-accent dark:border-violet-400 text-white btn-sm px-2 aspect-square relative"
>
<i className="bi-plus text-3xl absolute"></i>
</div>
</div>
</div>
<div className="divider my-3"></div>
{filteredUsers && filteredUsers.length > 0 && searchQuery !== "" ? (
UserListing(filteredUsers, deleteUserModal, setDeleteUserModal)
) : searchQuery !== "" ? (
<p>No users found with the given search query.</p>
) : users && users.length > 0 ? (
UserListing(users, deleteUserModal, setDeleteUserModal)
) : (
<p>No users found.</p>
)}
{newUserModal ? (
<NewUserModal onClose={() => setNewUserModal(false)} />
) : null}
</div>
);
}
const UserListing = (
users: User[],
deleteUserModal: UserModal,
setDeleteUserModal: Function
) => {
return (
<div className="overflow-x-auto whitespace-nowrap w-full">
<table className="table w-full">
<thead>
<tr>
<th></th>
<th>Username</th>
{process.env.NEXT_PUBLIC_EMAIL_PROVIDER === "true" && (
<th>Email</th>
)}
{process.env.NEXT_PUBLIC_STRIPE === "true" && <th>Subscribed</th>}
<th>Created At</th>
<th></th>
</tr>
</thead>
<tbody>
{users.map((user, index) => (
<tr
key={index}
className="group hover:bg-neutral-content hover:bg-opacity-30 duration-100"
>
<td className="text-primary">{index + 1}</td>
<td>{user.username ? user.username : <b>N/A</b>}</td>
{process.env.NEXT_PUBLIC_EMAIL_PROVIDER === "true" && (
<td>{user.email}</td>
)}
{process.env.NEXT_PUBLIC_STRIPE === "true" && (
<td>
{user.subscriptions?.active ? (
JSON.stringify(user.subscriptions?.active)
) : (
<b>N/A</b>
)}
</td>
)}
<td>{new Date(user.createdAt).toLocaleString()}</td>
<td className="relative">
<button
className="btn btn-sm btn-ghost duration-100 hidden group-hover:block absolute z-20 right-[0.35rem] top-[0.35rem]"
onClick={() =>
setDeleteUserModal({ isOpen: true, userId: user.id })
}
>
<i className="bi bi-trash"></i>
</button>
</td>
</tr>
))}
</tbody>
</table>
{deleteUserModal.isOpen && deleteUserModal.userId ? (
<DeleteUserModal
onClose={() => setDeleteUserModal({ isOpen: false, userId: null })}
userId={deleteUserModal.userId}
/>
) : null}
</div>
);
};

View File

@ -16,9 +16,17 @@ export default async function users(req: NextApiRequest, res: NextApiResponse) {
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." });
if (req.method === "GET") {
@ -53,7 +61,7 @@ export default async function users(req: NextApiRequest, res: NextApiResponse) {
const updated = await updateUserById(userId, req.body);
return res.status(updated.status).json({ response: updated.response });
} 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 });
}
}

View File

@ -1,9 +1,18 @@
import type { NextApiRequest, NextApiResponse } from "next";
import postUser from "@/lib/api/controllers/users/postUser";
import getUsers from "@/lib/api/controllers/users/getUsers";
import verifyUser from "@/lib/api/verifyUser";
export default async function users(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "POST") {
const response = await postUser(req, res);
return response;
} else if (req.method === "GET") {
const user = await verifyUser({ req, res });
if (!user || process.env.ADMINISTRATOR !== user.username)
return res.status(401).json({ response: "Unauthorized..." });
const response = await getUsers();
return res.status(response.status).json({ response: response.response });
}
}

66
store/admin/users.ts Normal file
View File

@ -0,0 +1,66 @@
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: () => void;
addUser: (body: Partial<U>) => 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 });
else if (response.status === 401) window.location.href = "/dashboard";
},
addUser: async (body) => {
const response = await fetch("/api/v1/users", {
method: "POST",
body: JSON.stringify(body),
headers: {
"Content-Type": "application/json",
},
});
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;

View File

@ -14,6 +14,7 @@ declare global {
ARCHIVE_TAKE_COUNT?: string;
IGNORE_UNAUTHORIZED_CA?: string;
IGNORE_URL_SIZE_LIMIT?: string;
ADMINISTRATOR?: string;
SPACES_KEY?: string;
SPACES_SECRET?: string;