bug fixed + add support for google profile pics

This commit is contained in:
daniel31x13 2024-05-07 16:59:00 -04:00
parent 2dd49ff844
commit 861f8e55f4
8 changed files with 100 additions and 37 deletions

View File

@ -201,7 +201,11 @@ const CollectionListing = () => {
}; };
if (!tree) { if (!tree) {
return <></>; return (
<p className="text-neutral text-xs font-semibold truncate w-full px-2 mt-5 mb-8">
You Have No Collections...
</p>
);
} else } else
return ( return (
<Tree <Tree

View File

@ -19,7 +19,7 @@ export default function ProfilePhoto({
const [image, setImage] = useState(""); const [image, setImage] = useState("");
useEffect(() => { useEffect(() => {
if (src && !src?.includes("base64")) if (src && !src?.includes("base64") && !src.startsWith("http"))
setImage(`/api/v1/${src.replace("uploads/", "").replace(".jpg", "")}`); setImage(`/api/v1/${src.replace("uploads/", "").replace(".jpg", "")}`);
else if (!src) setImage(""); else if (!src) setImage("");
else { else {

View File

@ -1,7 +1,7 @@
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"; import isServerAdmin from "../../isServerAdmin";
const emailEnabled = const emailEnabled =
process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false; process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;
@ -9,6 +9,7 @@ const stripeEnabled = process.env.STRIPE_SECRET_KEY ? true : false;
interface Data { interface Data {
response: string | object; response: string | object;
status: number;
} }
interface User { interface User {
@ -20,18 +21,12 @@ interface User {
export default async function postUser( export default async function postUser(
req: NextApiRequest, req: NextApiRequest,
res: NextApiResponse<Data> res: NextApiResponse
) { ): Promise<Data> {
let isServerAdmin = false; let isAdmin = await isServerAdmin({ req });
const user = await verifyUser({ req, res }); if (process.env.NEXT_PUBLIC_DISABLE_REGISTRATION === "true" && !isAdmin) {
if (process.env.ADMINISTRATOR === user?.username) isServerAdmin = true; return { response: "Registration is disabled.", status: 400 };
if (
process.env.NEXT_PUBLIC_DISABLE_REGISTRATION === "true" &&
!isServerAdmin
) {
return res.status(400).json({ response: "Registration is disabled." });
} }
const body: User = req.body; const body: User = req.body;
@ -41,39 +36,36 @@ export default async function postUser(
: !body.username || !body.password || !body.name; : !body.username || !body.password || !body.name;
if (!body.password || body.password.length < 8) if (!body.password || body.password.length < 8)
return res return { response: "Password must be at least 8 characters.", status: 400 };
.status(400)
.json({ response: "Password must be at least 8 characters." });
if (checkHasEmptyFields) if (checkHasEmptyFields)
return res return { response: "Please fill out all the fields.", status: 400 };
.status(400)
.json({ response: "Please fill out all the fields." });
// Check email (if enabled) // Check email (if enabled)
const checkEmail = const checkEmail =
/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i; /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
if (emailEnabled && !checkEmail.test(body.email?.toLowerCase() || "")) if (emailEnabled && !checkEmail.test(body.email?.toLowerCase() || ""))
return res.status(400).json({ return { response: "Please enter a valid email.", status: 400 };
response: "Please enter a valid email.",
});
// Check username (if email was disabled) // Check username (if email was disabled)
const checkUsername = RegExp("^[a-z0-9_-]{3,31}$"); const checkUsername = RegExp("^[a-z0-9_-]{3,31}$");
if (!emailEnabled && !checkUsername.test(body.username?.toLowerCase() || "")) if (!emailEnabled && !checkUsername.test(body.username?.toLowerCase() || ""))
return res.status(400).json({ return {
response: response:
"Username has to be between 3-30 characters, no spaces and special characters are allowed.", "Username has to be between 3-30 characters, no spaces and special characters are allowed.",
}); status: 400,
};
const checkIfUserExists = await prisma.user.findFirst({ const checkIfUserExists = await prisma.user.findFirst({
where: { where: {
OR: [ OR: [
{ {
email: body.email?.toLowerCase().trim(), email: body.email ? body.email.toLowerCase().trim() : undefined,
}, },
{ {
username: (body.username as string).toLowerCase().trim(), username: body.username
? body.username.toLowerCase().trim()
: undefined,
}, },
], ],
}, },
@ -89,7 +81,7 @@ export default async function postUser(
const currentPeriodEnd = new Date(); const currentPeriodEnd = new Date();
currentPeriodEnd.setFullYear(currentPeriodEnd.getFullYear() + 1000); // end date is in 1000 years... currentPeriodEnd.setFullYear(currentPeriodEnd.getFullYear() + 1000); // end date is in 1000 years...
if (isServerAdmin) { if (isAdmin) {
const user = await prisma.user.create({ const user = await prisma.user.create({
data: { data: {
name: body.name, name: body.name,
@ -123,7 +115,7 @@ export default async function postUser(
}, },
}); });
return res.status(201).json({ response: user }); return { response: user, status: 201 };
} else { } else {
await prisma.user.create({ await prisma.user.create({
data: { data: {
@ -136,11 +128,9 @@ export default async function postUser(
}, },
}); });
return res.status(201).json({ response: "User successfully created." }); return { response: "User successfully created.", status: 201 };
} }
} else if (checkIfUserExists) { } else {
return res.status(400).json({ return { response: "Email or Username already exists.", status: 400 };
response: `Email or Username already exists.`,
});
} }
} }

View File

@ -25,8 +25,10 @@ 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 SSO/OAuth integrations)
if (!keycloakEnabled && !authentikEnabled && !isServerAdmin) { if (user.password && !isServerAdmin) {
console.log("isServerAdmin", isServerAdmin);
console.log("isServerAdmin", body.password);
const isPasswordValid = bcrypt.compareSync( const isPasswordValid = bcrypt.compareSync(
body.password, body.password,
user.password as string user.password as string

44
lib/api/isServerAdmin.ts Normal file
View File

@ -0,0 +1,44 @@
import { NextApiRequest } from "next";
import { getToken } from "next-auth/jwt";
import { prisma } from "./db";
type Props = {
req: NextApiRequest;
};
export default async function isServerAdmin({ req }: Props): Promise<boolean> {
const token = await getToken({ req });
const userId = token?.id;
if (!userId) {
return false;
}
if (token.exp < Date.now() / 1000) {
return false;
}
// check if token is revoked
const revoked = await prisma.accessToken.findFirst({
where: {
token: token.jti,
revoked: true,
},
});
if (revoked) {
return false;
}
const findUser = await prisma.user.findFirst({
where: {
id: userId,
},
});
if (findUser?.username === process.env.ADMINISTRATOR) {
return true;
} else {
return false;
}
}

View File

@ -4,7 +4,16 @@ const { version } = require("./package.json");
const nextConfig = { const nextConfig = {
reactStrictMode: true, reactStrictMode: true,
images: { images: {
// For fetching the favicons
domains: ["t2.gstatic.com"], domains: ["t2.gstatic.com"],
// For profile pictures (Google OAuth)
remotePatterns: [
{
hostname: "*.googleusercontent.com",
},
],
minimumCacheTTL: 10, minimumCacheTTL: 10,
}, },
env: { env: {

View File

@ -1103,6 +1103,20 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) {
}, },
callbacks: { callbacks: {
async signIn({ user, account, profile, email, credentials }) { async signIn({ user, account, profile, email, credentials }) {
// console.log(
// "User sign in attempt...",
// "User",
// user,
// "Account",
// account,
// "Profile",
// profile,
// "Email",
// email,
// "Credentials",
// credentials
// );
if (account?.provider !== "credentials") { if (account?.provider !== "credentials") {
// registration via SSO can be separately disabled // registration via SSO can be separately disabled
const existingUser = await prisma.account.findFirst({ const existingUser = await prisma.account.findFirst({

View File

@ -6,7 +6,7 @@ import verifyUser from "@/lib/api/verifyUser";
export default async function users(req: NextApiRequest, res: NextApiResponse) { export default async function users(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "POST") { if (req.method === "POST") {
const response = await postUser(req, res); const response = await postUser(req, res);
return response; return res.status(response.status).json({ response: response.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) if (!user || process.env.ADMINISTRATOR !== user.username)