Skip to content

⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.

finalized administration panel

daniel31x13915d08a315f2
diff --git a/components/ModalContent/NewUserModal.tsx b/components/ModalContent/NewUserModal.tsx
new file mode 100644
index 00000000..27e1a15a
--- /dev/null
+++ b/components/ModalContent/NewUserModal.tsx
@@ -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="[email protected]"
+ 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>
+ );
+}
diff --git a/lib/api/controllers/users/postUser.ts b/lib/api/controllers/users/postUser.ts
index f24738bb..84ab2e0f 100644
--- a/lib/api/controllers/users/postUser.ts
+++ b/lib/api/controllers/users/postUser.ts
@@ -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,21 +84,63 @@ export default async function postUser(
const hashedPassword = bcrypt.hashSync(body.password, saltRounds);
- await prisma.user.create({
- data: {
- name: body.name,
- username: emailEnabled
- ? undefined
- : (body.username as string).toLowerCase().trim(),
- email: emailEnabled ? body.email?.toLowerCase().trim() : undefined,
- password: hashedPassword,
- },
- });
+ // 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,
+ username: emailEnabled
+ ? undefined
+ : (body.username as string).toLowerCase().trim(),
+ email: emailEnabled ? body.email?.toLowerCase().trim() : undefined,
+ password: hashedPassword,
+ },
+ });
- return res.status(201).json({ response: "User successfully created." });
+ 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.`,
});
}
}
diff --git a/lib/api/controllers/users/userId/deleteUserById.ts b/lib/api/controllers/users/userId/deleteUserById.ts
index 7e333445..9c01dcd0 100644
--- a/lib/api/controllers/users/userId/deleteUserById.ts
+++ b/lib/api/controllers/users/userId/deleteUserById.ts
@@ -11,7 +11,7 @@ const authentikEnabled = process.env.AUTHENTIK_CLIENT_SECRET;
export default async function deleteUserById(
userId: number,
body: DeleteUserBody,
- isServerAdmin: boolean
+ isServerAdmin?: boolean
) {
// First, we retrieve the user from the database
const user = await prisma.user.findUnique({
@@ -93,6 +93,7 @@ export default async function deleteUserById(
await prisma.subscription.delete({
where: { userId },
});
+ // .catch((err) => console.log(err));
await prisma.usersAndCollections.deleteMany({
where: {
diff --git a/pages/admin.tsx b/pages/admin.tsx
index 3d5a0a31..d7b9fdaa 100644
--- a/pages/admin.tsx
+++ b/pages/admin.tsx
@@ -1,4 +1,5 @@
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";
@@ -26,11 +27,10 @@ export default function Admin() {
userId: null,
});
+ const [newUserModal, setNewUserModal] = useState(false);
+
useEffect(() => {
- // fetch users
- fetch("/api/v1/users")
- .then((res) => res.json())
- .then((data) => setUsers(data.response));
+ setUsers();
}, []);
return (
@@ -79,7 +79,10 @@ export default function Admin() {
/>
</div>
- <div className="flex items-center btn btn-accent dark:border-violet-400 text-white btn-sm px-2 aspect-square relative">
+ <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>
@@ -96,6 +99,10 @@ export default function Admin() {
) : (
<p>No users found.</p>
)}
+
+ {newUserModal ? (
+ <NewUserModal onClose={() => setNewUserModal(false)} />
+ ) : null}
</div>
);
}
@@ -107,7 +114,7 @@ const UserListing = (
) => {
return (
<div className="overflow-x-auto whitespace-nowrap w-full">
- <table className="table table-zebra w-full">
+ <table className="table w-full">
<thead>
<tr>
<th></th>
@@ -122,19 +129,28 @@ const UserListing = (
</thead>
<tbody>
{users.map((user, index) => (
- <tr key={index}>
- <td className="rounded-tl">{index + 1}</td>
- <td>{user.username}</td>
+ <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>{JSON.stringify(user.subscriptions.active)}</td>
+ <td>
+ {user.subscriptions?.active ? (
+ JSON.stringify(user.subscriptions?.active)
+ ) : (
+ <b>N/A</b>
+ )}
+ </td>
)}
<td>{new Date(user.createdAt).toLocaleString()}</td>
- <td>
+ <td className="relative">
<button
- className="btn btn-sm btn-ghost"
+ 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 })
}
diff --git a/pages/api/v1/users/index.ts b/pages/api/v1/users/index.ts
index cce6b4ea..a4768fa6 100644
--- a/pages/api/v1/users/index.ts
+++ b/pages/api/v1/users/index.ts
@@ -9,7 +9,8 @@ export default async function users(req: NextApiRequest, res: NextApiResponse) {
return response;
} else if (req.method === "GET") {
const user = await verifyUser({ req, res });
- if (!user || process.env.ADMINISTRATOR !== user.username) return;
+ 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 });
diff --git a/store/admin/users.ts b/store/admin/users.ts
index c5cb5af1..6925611d 100644
--- a/store/admin/users.ts
+++ b/store/admin/users.ts
@@ -14,8 +14,8 @@ type ResponseObject = {
type UserStore = {
users: User[];
- setUsers: (users: User[]) => void;
- addUser: () => Promise<ResponseObject>;
+ setUsers: () => void;
+ addUser: (body: Partial<U>) => Promise<ResponseObject>;
removeUser: (userId: number) => Promise<ResponseObject>;
};
@@ -27,10 +27,15 @@ const useUserStore = create<UserStore>((set) => ({
const data = await response.json();
if (response.ok) set({ users: data.response });
+ else if (response.status === 401) window.location.href = "/dashboard";
},
- addUser: async () => {
+ 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();