finalized administration panel
This commit is contained in:
parent
08c2ff278f
commit
915d08a315
|
@ -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>
|
||||||
|
);
|
||||||
|
}
|
|
@ -1,9 +1,11 @@
|
||||||
import { prisma } from "@/lib/api/db";
|
import { prisma } from "@/lib/api/db";
|
||||||
import type { NextApiRequest, NextApiResponse } from "next";
|
import type { NextApiRequest, NextApiResponse } from "next";
|
||||||
import bcrypt from "bcrypt";
|
import bcrypt from "bcrypt";
|
||||||
|
import verifyUser from "../../verifyUser";
|
||||||
|
|
||||||
const emailEnabled =
|
const emailEnabled =
|
||||||
process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;
|
process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;
|
||||||
|
const stripeEnabled = process.env.STRIPE_SECRET_KEY ? true : false;
|
||||||
|
|
||||||
interface Data {
|
interface Data {
|
||||||
response: string | object;
|
response: string | object;
|
||||||
|
@ -20,7 +22,15 @@ export default async function postUser(
|
||||||
req: NextApiRequest,
|
req: NextApiRequest,
|
||||||
res: NextApiResponse<Data>
|
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." });
|
return res.status(400).json({ response: "Registration is disabled." });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -57,13 +67,16 @@ export default async function postUser(
|
||||||
});
|
});
|
||||||
|
|
||||||
const checkIfUserExists = await prisma.user.findFirst({
|
const checkIfUserExists = await prisma.user.findFirst({
|
||||||
where: emailEnabled
|
where: {
|
||||||
? {
|
OR: [
|
||||||
|
{
|
||||||
email: body.email?.toLowerCase().trim(),
|
email: body.email?.toLowerCase().trim(),
|
||||||
}
|
},
|
||||||
: {
|
{
|
||||||
username: (body.username as string).toLowerCase().trim(),
|
username: (body.username as string).toLowerCase().trim(),
|
||||||
},
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!checkIfUserExists) {
|
if (!checkIfUserExists) {
|
||||||
|
@ -71,6 +84,47 @@ export default async function postUser(
|
||||||
|
|
||||||
const hashedPassword = bcrypt.hashSync(body.password, saltRounds);
|
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({
|
await prisma.user.create({
|
||||||
data: {
|
data: {
|
||||||
name: body.name,
|
name: body.name,
|
||||||
|
@ -83,9 +137,10 @@ export default async function postUser(
|
||||||
});
|
});
|
||||||
|
|
||||||
return res.status(201).json({ response: "User successfully created." });
|
return res.status(201).json({ response: "User successfully created." });
|
||||||
|
}
|
||||||
} else if (checkIfUserExists) {
|
} else if (checkIfUserExists) {
|
||||||
return res.status(400).json({
|
return res.status(400).json({
|
||||||
response: `${emailEnabled ? "Email" : "Username"} already exists.`,
|
response: `Email or Username already exists.`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,7 +11,7 @@ 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
|
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({
|
||||||
|
@ -93,6 +93,7 @@ export default async function deleteUserById(
|
||||||
await prisma.subscription.delete({
|
await prisma.subscription.delete({
|
||||||
where: { userId },
|
where: { userId },
|
||||||
});
|
});
|
||||||
|
// .catch((err) => console.log(err));
|
||||||
|
|
||||||
await prisma.usersAndCollections.deleteMany({
|
await prisma.usersAndCollections.deleteMany({
|
||||||
where: {
|
where: {
|
||||||
|
|
|
@ -1,4 +1,5 @@
|
||||||
import DeleteUserModal from "@/components/ModalContent/DeleteUserModal";
|
import DeleteUserModal from "@/components/ModalContent/DeleteUserModal";
|
||||||
|
import NewUserModal from "@/components/ModalContent/NewUserModal";
|
||||||
import useUserStore from "@/store/admin/users";
|
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";
|
||||||
|
@ -26,11 +27,10 @@ export default function Admin() {
|
||||||
userId: null,
|
userId: null,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const [newUserModal, setNewUserModal] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// fetch users
|
setUsers();
|
||||||
fetch("/api/v1/users")
|
|
||||||
.then((res) => res.json())
|
|
||||||
.then((data) => setUsers(data.response));
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
@ -79,7 +79,10 @@ export default function Admin() {
|
||||||
/>
|
/>
|
||||||
</div>
|
</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>
|
<i className="bi-plus text-3xl absolute"></i>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@ -96,6 +99,10 @@ export default function Admin() {
|
||||||
) : (
|
) : (
|
||||||
<p>No users found.</p>
|
<p>No users found.</p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{newUserModal ? (
|
||||||
|
<NewUserModal onClose={() => setNewUserModal(false)} />
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -107,7 +114,7 @@ const UserListing = (
|
||||||
) => {
|
) => {
|
||||||
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 w-full">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th></th>
|
<th></th>
|
||||||
|
@ -122,19 +129,28 @@ const UserListing = (
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{users.map((user, index) => (
|
{users.map((user, index) => (
|
||||||
<tr key={index}>
|
<tr
|
||||||
<td className="rounded-tl">{index + 1}</td>
|
key={index}
|
||||||
<td>{user.username}</td>
|
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" && (
|
{process.env.NEXT_PUBLIC_EMAIL_PROVIDER === "true" && (
|
||||||
<td>{user.email}</td>
|
<td>{user.email}</td>
|
||||||
)}
|
)}
|
||||||
{process.env.NEXT_PUBLIC_STRIPE === "true" && (
|
{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>{new Date(user.createdAt).toLocaleString()}</td>
|
||||||
<td>
|
<td className="relative">
|
||||||
<button
|
<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={() =>
|
onClick={() =>
|
||||||
setDeleteUserModal({ isOpen: true, userId: user.id })
|
setDeleteUserModal({ isOpen: true, userId: user.id })
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,7 +9,8 @@ export default async function users(req: NextApiRequest, res: NextApiResponse) {
|
||||||
return response;
|
return response;
|
||||||
} else if (req.method === "GET") {
|
} else if (req.method === "GET") {
|
||||||
const user = await verifyUser({ req, res });
|
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();
|
const response = await getUsers();
|
||||||
return res.status(response.status).json({ response: response.response });
|
return res.status(response.status).json({ response: response.response });
|
||||||
|
|
|
@ -14,8 +14,8 @@ type ResponseObject = {
|
||||||
|
|
||||||
type UserStore = {
|
type UserStore = {
|
||||||
users: User[];
|
users: User[];
|
||||||
setUsers: (users: User[]) => void;
|
setUsers: () => void;
|
||||||
addUser: () => Promise<ResponseObject>;
|
addUser: (body: Partial<U>) => Promise<ResponseObject>;
|
||||||
removeUser: (userId: number) => Promise<ResponseObject>;
|
removeUser: (userId: number) => Promise<ResponseObject>;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -27,10 +27,15 @@ const useUserStore = create<UserStore>((set) => ({
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
|
||||||
if (response.ok) set({ users: data.response });
|
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", {
|
const response = await fetch("/api/v1/users", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
|
Ŝarĝante…
Reference in New Issue