Revert "undo commit"

This reverts commit 9103f67db5.
This commit is contained in:
daniel31x13
2024-11-03 03:27:52 -05:00
parent e37702aa14
commit dbd096ab76
176 changed files with 2362 additions and 9401 deletions
@@ -1,31 +1,15 @@
import { prisma } from "@/lib/api/db";
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import getPermission from "@/lib/api/getPermission";
import {
UpdateCollectionSchema,
UpdateCollectionSchemaType,
} from "@/lib/shared/schemaValidation";
export default async function updateCollection(
userId: number,
collectionId: number,
body: UpdateCollectionSchemaType
data: CollectionIncludingMembersAndLinkCount
) {
if (!collectionId)
return { response: "Please choose a valid collection.", status: 401 };
const dataValidation = UpdateCollectionSchema.safeParse(body);
if (!dataValidation.success) {
return {
response: `Error: ${
dataValidation.error.issues[0].message
} [${dataValidation.error.issues[0].path.join(", ")}]`,
status: 400,
};
}
const data = dataValidation.data;
const collectionIsAccessible = await getPermission({
userId,
collectionId,
@@ -34,8 +18,10 @@ export default async function updateCollection(
if (!(collectionIsAccessible?.ownerId === userId))
return { response: "Collection is not accessible.", status: 401 };
console.log(data);
if (data.parentId) {
if (data.parentId !== "root") {
if (data.parentId !== ("root" as any)) {
const findParentCollection = await prisma.collection.findUnique({
where: {
id: data.parentId,
@@ -58,12 +44,6 @@ export default async function updateCollection(
}
}
const uniqueMembers = data.members.filter(
(e, i, a) =>
a.findIndex((el) => el.userId === e.userId) === i &&
e.userId !== collectionIsAccessible.ownerId
);
const updatedCollection = await prisma.$transaction(async () => {
await prisma.usersAndCollections.deleteMany({
where: {
@@ -81,24 +61,22 @@ export default async function updateCollection(
name: data.name.trim(),
description: data.description,
color: data.color,
icon: data.icon,
iconWeight: data.iconWeight,
isPublic: data.isPublic,
parent:
data.parentId && data.parentId !== "root"
data.parentId && data.parentId !== ("root" as any)
? {
connect: {
id: data.parentId,
},
}
: data.parentId === "root"
: data.parentId === ("root" as any)
? {
disconnect: true,
}
: undefined,
members: {
create: uniqueMembers.map((e) => ({
user: { connect: { id: e.userId } },
create: data.members.map((e) => ({
user: { connect: { id: e.user.id || e.userId } },
canCreate: e.canCreate,
canUpdate: e.canUpdate,
canDelete: e.canDelete,
@@ -1,26 +1,16 @@
import { prisma } from "@/lib/api/db";
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import createFolder from "@/lib/api/storage/createFolder";
import {
PostCollectionSchema,
PostCollectionSchemaType,
} from "@/lib/shared/schemaValidation";
export default async function postCollection(
body: PostCollectionSchemaType,
collection: CollectionIncludingMembersAndLinkCount,
userId: number
) {
const dataValidation = PostCollectionSchema.safeParse(body);
if (!dataValidation.success) {
if (!collection || collection.name.trim() === "")
return {
response: `Error: ${
dataValidation.error.issues[0].message
} [${dataValidation.error.issues[0].path.join(", ")}]`,
response: "Please enter a valid collection.",
status: 400,
};
}
const collection = dataValidation.data;
if (collection.parentId) {
const findParentCollection = await prisma.collection.findUnique({
@@ -44,11 +34,14 @@ export default async function postCollection(
const newCollection = await prisma.collection.create({
data: {
owner: {
connect: {
id: userId,
},
},
name: collection.name.trim(),
description: collection.description,
color: collection.color,
icon: collection.icon,
iconWeight: collection.iconWeight,
parent: collection.parentId
? {
connect: {
@@ -56,16 +49,6 @@ export default async function postCollection(
},
}
: undefined,
owner: {
connect: {
id: userId,
},
},
createdBy: {
connect: {
id: userId,
},
},
},
include: {
_count: {
@@ -1,11 +1,11 @@
import { prisma } from "@/lib/api/db";
import { LinkRequestQuery, Order, Sort } from "@/types/global";
import { LinkRequestQuery, Sort } from "@/types/global";
export default async function getDashboardData(
userId: number,
query: LinkRequestQuery
) {
let order: Order = { id: "desc" };
let order: any = { id: "desc" };
if (query.sort === Sort.DateNewestFirst) order = { id: "desc" };
else if (query.sort === Sort.DateOldestFirst) order = { id: "asc" };
else if (query.sort === Sort.NameAZ) order = { name: "asc" };
@@ -1,5 +1,5 @@
import { prisma } from "@/lib/api/db";
import { LinkRequestQuery, Order, Sort } from "@/types/global";
import { LinkRequestQuery, Sort } from "@/types/global";
type Response<D> =
| {
@@ -17,7 +17,7 @@ export default async function getDashboardData(
userId: number,
query: LinkRequestQuery
): Promise<Response<any>> {
let order: Order = { id: "desc" };
let order: any;
if (query.sort === Sort.DateNewestFirst) order = { id: "desc" };
else if (query.sort === Sort.DateOldestFirst) order = { id: "asc" };
else if (query.sort === Sort.NameAZ) order = { name: "asc" };
@@ -48,7 +48,7 @@ export default async function getDashboardData(
});
const pinnedLinks = await prisma.link.findMany({
take: 16,
take: 10,
where: {
AND: [
{
@@ -80,7 +80,7 @@ export default async function getDashboardData(
});
const recentlyAddedLinks = await prisma.link.findMany({
take: 16,
take: 10,
where: {
collection: {
OR: [
@@ -105,17 +105,12 @@ export default async function getDashboardData(
});
const links = [...recentlyAddedLinks, ...pinnedLinks].sort(
(a, b) => new Date(b.id).getTime() - new Date(a.id).getTime()
);
// Make sure links are unique
const uniqueLinks = links.filter(
(link, index, self) => index === self.findIndex((t) => t.id === link.id)
(a, b) => (new Date(b.id) as any) - (new Date(a.id) as any)
);
return {
data: {
links: uniqueLinks,
links,
numberOfPinnedLinks,
},
message: "Dashboard data fetched successfully.",
@@ -1,10 +1,9 @@
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import updateLinkById from "../linkId/updateLinkById";
import { UpdateLinkSchemaType } from "@/lib/shared/schemaValidation";
export default async function updateLinks(
userId: number,
links: UpdateLinkSchemaType[],
links: LinkIncludingShortenedCollectionAndTags[],
removePreviousTags: boolean,
newData: Pick<
LinkIncludingShortenedCollectionAndTags,
@@ -23,7 +22,7 @@ export default async function updateLinks(
updatedTags = [...(newData.tags ?? [])];
}
const updatedData: UpdateLinkSchemaType = {
const updatedData: LinkIncludingShortenedCollectionAndTags = {
...link,
tags: updatedTags,
collection: {
+2 -2
View File
@@ -1,11 +1,11 @@
import { prisma } from "@/lib/api/db";
import { LinkRequestQuery, Order, Sort } from "@/types/global";
import { LinkRequestQuery, Sort } from "@/types/global";
export default async function getLink(userId: number, query: LinkRequestQuery) {
const POSTGRES_IS_ENABLED =
process.env.DATABASE_URL?.startsWith("postgresql");
let order: Order = { id: "desc" };
let order: any = { id: "desc" };
if (query.sort === Sort.DateNewestFirst) order = { id: "desc" };
else if (query.sort === Sort.DateOldestFirst) order = { id: "asc" };
else if (query.sort === Sort.NameAZ) order = { name: "asc" };
@@ -1,30 +1,19 @@
import { prisma } from "@/lib/api/db";
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import { UsersAndCollections } from "@prisma/client";
import getPermission from "@/lib/api/getPermission";
import { moveFiles, removeFiles } from "@/lib/api/manageLinkFiles";
import isValidUrl from "@/lib/shared/isValidUrl";
import {
UpdateLinkSchema,
UpdateLinkSchemaType,
} from "@/lib/shared/schemaValidation";
import { moveFiles } from "@/lib/api/manageLinkFiles";
export default async function updateLinkById(
userId: number,
linkId: number,
body: UpdateLinkSchemaType
data: LinkIncludingShortenedCollectionAndTags
) {
const dataValidation = UpdateLinkSchema.safeParse(body);
if (!dataValidation.success) {
if (!data || !data.collection.id)
return {
response: `Error: ${
dataValidation.error.issues[0].message
} [${dataValidation.error.issues[0].path.join(", ")}]`,
status: 400,
response: "Please choose a valid link and collection.",
status: 401,
};
}
const data = dataValidation.data;
const collectionIsAccessible = await getPermission({ userId, linkId });
@@ -36,18 +25,17 @@ export default async function updateLinkById(
(e: UsersAndCollections) => e.userId === userId
);
// If the user is part of a collection, they can pin it to their dashboard
if (canPinPermission && data.pinnedBy && data.pinnedBy[0]) {
// If the user is able to create a link, they can pin it to their dashboard only.
if (canPinPermission) {
const updatedLink = await prisma.link.update({
where: {
id: linkId,
},
data: {
pinnedBy: data?.pinnedBy
? data.pinnedBy[0]?.id === userId
pinnedBy:
data?.pinnedBy && data.pinnedBy[0]
? { connect: { id: userId } }
: { disconnect: { id: userId } }
: undefined,
: { disconnect: { id: userId } },
},
include: {
collection: true,
@@ -60,7 +48,7 @@ export default async function updateLinkById(
},
});
return { response: updatedLink, status: 200 };
// return { response: updatedLink, status: 200 };
}
const targetCollectionIsAccessible = await getPermission({
@@ -74,9 +62,11 @@ export default async function updateLinkById(
const targetCollectionMatchesData = data.collection.id
? data.collection.id === targetCollectionIsAccessible?.id
: true && data.collection.ownerId
? data.collection.ownerId === targetCollectionIsAccessible?.ownerId
: true;
: true && data.collection.name
? data.collection.name === targetCollectionIsAccessible?.name
: true && data.collection.ownerId
? data.collection.ownerId === targetCollectionIsAccessible?.ownerId
: true;
if (!targetCollectionMatchesData)
return {
@@ -99,41 +89,13 @@ export default async function updateLinkById(
status: 401,
};
else {
const oldLink = await prisma.link.findUnique({
where: {
id: linkId,
},
});
if (
data.url &&
oldLink &&
oldLink?.url !== data.url &&
isValidUrl(data.url)
) {
await removeFiles(oldLink.id, oldLink.collectionId);
} else if (oldLink?.url !== data.url)
return {
response: "Invalid URL.",
status: 401,
};
const updatedLink = await prisma.link.update({
where: {
id: linkId,
},
data: {
name: data.name,
url: data.url,
description: data.description,
icon: data.icon,
iconWeight: data.iconWeight,
color: data.color,
image: oldLink?.url !== data.url ? null : undefined,
pdf: oldLink?.url !== data.url ? null : undefined,
readable: oldLink?.url !== data.url ? null : undefined,
monolith: oldLink?.url !== data.url ? null : undefined,
preview: oldLink?.url !== data.url ? null : undefined,
collection: {
connect: {
id: data.collection.id,
@@ -158,11 +120,10 @@ export default async function updateLinkById(
},
})),
},
pinnedBy: data?.pinnedBy
? data.pinnedBy[0]?.id === userId
pinnedBy:
data?.pinnedBy && data.pinnedBy[0]
? { connect: { id: userId } }
: { disconnect: { id: userId } }
: undefined,
: { disconnect: { id: userId } },
},
include: {
tags: true,
+23 -26
View File
@@ -1,30 +1,27 @@
import { prisma } from "@/lib/api/db";
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import fetchTitleAndHeaders from "@/lib/shared/fetchTitleAndHeaders";
import createFolder from "@/lib/api/storage/createFolder";
import setLinkCollection from "../../setLinkCollection";
import {
PostLinkSchema,
PostLinkSchemaType,
} from "@/lib/shared/schemaValidation";
import { hasPassedLimit } from "../../verifyCapacity";
const MAX_LINKS_PER_USER = Number(process.env.MAX_LINKS_PER_USER) || 30000;
export default async function postLink(
body: PostLinkSchemaType,
link: LinkIncludingShortenedCollectionAndTags,
userId: number
) {
const dataValidation = PostLinkSchema.safeParse(body);
if (!dataValidation.success) {
return {
response: `Error: ${
dataValidation.error.issues[0].message
} [${dataValidation.error.issues[0].path.join(", ")}]`,
status: 400,
};
if (link.url || link.type === "url") {
try {
new URL(link.url || "");
} catch (error) {
return {
response:
"Please enter a valid Address for the Link. (It should start with http/https)",
status: 400,
};
}
}
const link = dataValidation.data;
const linkCollection = await setLinkCollection(link, userId);
if (!linkCollection)
@@ -58,14 +55,19 @@ export default async function postLink(
};
}
const hasTooManyLinks = await hasPassedLimit(userId, 1);
const numberOfLinksTheUserHas = await prisma.link.count({
where: {
collection: {
ownerId: linkCollection.ownerId,
},
},
});
if (hasTooManyLinks) {
if (numberOfLinksTheUserHas > MAX_LINKS_PER_USER)
return {
response: `Your subscription have reached the maximum number of links allowed.`,
response: `Each collection owner can only have a maximum of ${MAX_LINKS_PER_USER} Links.`,
status: 400,
};
}
const { title, headers } = await fetchTitleAndHeaders(link.url || "");
@@ -92,11 +94,6 @@ export default async function postLink(
name,
description: link.description,
type: linkType,
createdBy: {
connect: {
id: userId,
},
},
collection: {
connect: {
id: linkCollection.id,
@@ -22,5 +22,18 @@ export default async function exportData(userId: number) {
const { password, id, ...userData } = user;
function redactIds(obj: any) {
if (Array.isArray(obj)) {
obj.forEach((o) => redactIds(o));
} else if (obj !== null && typeof obj === "object") {
delete obj.id;
for (let key in obj) {
redactIds(obj[key]);
}
}
}
redactIds(userData);
return { response: userData, status: 200 };
}
@@ -2,7 +2,9 @@ import { prisma } from "@/lib/api/db";
import createFolder from "@/lib/api/storage/createFolder";
import { JSDOM } from "jsdom";
import { parse, Node, Element, TextNode } from "himalaya";
import { hasPassedLimit } from "../../verifyCapacity";
import { writeFileSync } from "fs";
const MAX_LINKS_PER_USER = Number(process.env.MAX_LINKS_PER_USER) || 30000;
export default async function importFromHTMLFile(
userId: number,
@@ -19,14 +21,19 @@ export default async function importFromHTMLFile(
const bookmarks = document.querySelectorAll("A");
const totalImports = bookmarks.length;
const hasTooManyLinks = await hasPassedLimit(userId, totalImports);
const numberOfLinksTheUserHas = await prisma.link.count({
where: {
collection: {
ownerId: userId,
},
},
});
if (hasTooManyLinks) {
if (totalImports + numberOfLinksTheUserHas > MAX_LINKS_PER_USER)
return {
response: `Your subscription have reached the maximum number of links allowed.`,
response: `Each collection owner can only have a maximum of ${MAX_LINKS_PER_USER} Links.`,
status: 400,
};
}
const jsonData = parse(document.documentElement.outerHTML);
@@ -148,8 +155,6 @@ const createCollection = async (
collectionName: string,
parentId?: number
) => {
collectionName = collectionName.trim().slice(0, 254);
const findCollection = await prisma.collection.findFirst({
where: {
parentId,
@@ -177,11 +182,6 @@ const createCollection = async (
id: userId,
},
},
createdBy: {
connect: {
id: userId,
},
},
},
});
@@ -199,49 +199,34 @@ const createLink = async (
tags?: string[],
importDate?: Date
) => {
url = url.trim().slice(0, 254);
try {
new URL(url);
} catch (e) {
return;
}
tags = tags?.map((tag) => tag.trim().slice(0, 49));
name = name?.trim().slice(0, 254);
description = description?.trim().slice(0, 254);
if (importDate) {
const dateString = importDate.toISOString();
if (dateString.length > 50) {
importDate = undefined;
}
}
await prisma.link.create({
data: {
name: name || "",
url,
description,
collectionId,
createdById: userId,
tags:
tags && tags[0]
? {
connectOrCreate: tags.map((tag: string) => {
return {
where: {
name_ownerId: {
name: tag.trim(),
ownerId: userId,
},
},
create: {
name: tag.trim(),
owner: {
connect: {
id: userId,
return (
{
where: {
name_ownerId: {
name: tag.trim(),
ownerId: userId,
},
},
},
};
create: {
name: tag.trim(),
owner: {
connect: {
id: userId,
},
},
},
} || undefined
);
}),
}
: undefined,
@@ -1,7 +1,8 @@
import { prisma } from "@/lib/api/db";
import { Backup } from "@/types/global";
import createFolder from "@/lib/api/storage/createFolder";
import { hasPassedLimit } from "../../verifyCapacity";
const MAX_LINKS_PER_USER = Number(process.env.MAX_LINKS_PER_USER) || 30000;
export default async function importFromLinkwarden(
userId: number,
@@ -15,14 +16,19 @@ export default async function importFromLinkwarden(
totalImports += collection.links.length;
});
const hasTooManyLinks = await hasPassedLimit(userId, totalImports);
const numberOfLinksTheUserHas = await prisma.link.count({
where: {
collection: {
ownerId: userId,
},
},
});
if (hasTooManyLinks) {
if (totalImports + numberOfLinksTheUserHas > MAX_LINKS_PER_USER)
return {
response: `Your subscription have reached the maximum number of links allowed.`,
response: `Each collection owner can only have a maximum of ${MAX_LINKS_PER_USER} Links.`,
status: 400,
};
}
await prisma
.$transaction(
@@ -38,14 +44,9 @@ export default async function importFromLinkwarden(
id: userId,
},
},
name: e.name?.trim().slice(0, 254),
description: e.description?.trim().slice(0, 254),
color: e.color?.trim().slice(0, 50),
createdBy: {
connect: {
id: userId,
},
},
name: e.name,
description: e.description,
color: e.color,
},
});
@@ -53,40 +54,27 @@ export default async function importFromLinkwarden(
// Import Links
for (const link of e.links) {
if (link.url) {
try {
new URL(link.url.trim());
} catch (err) {
continue;
}
}
await prisma.link.create({
data: {
url: link.url?.trim().slice(0, 254),
name: link.name?.trim().slice(0, 254),
description: link.description?.trim().slice(0, 254),
url: link.url,
name: link.name,
description: link.description,
collection: {
connect: {
id: newCollection.id,
},
},
createdBy: {
connect: {
id: userId,
},
},
// Import Tags
tags: {
connectOrCreate: link.tags.map((tag) => ({
where: {
name_ownerId: {
name: tag.name?.slice(0, 49),
name: tag.name.trim(),
ownerId: userId,
},
},
create: {
name: tag.name?.trim().slice(0, 49),
name: tag.name.trim(),
owner: {
connect: {
id: userId,
@@ -1,6 +1,8 @@
import { prisma } from "@/lib/api/db";
import { Backup } from "@/types/global";
import createFolder from "@/lib/api/storage/createFolder";
import { hasPassedLimit } from "../../verifyCapacity";
const MAX_LINKS_PER_USER = Number(process.env.MAX_LINKS_PER_USER) || 30000;
type WallabagBackup = {
is_archived: number;
@@ -35,14 +37,19 @@ export default async function importFromWallabag(
let totalImports = backup.length;
const hasTooManyLinks = await hasPassedLimit(userId, totalImports);
const numberOfLinksTheUserHas = await prisma.link.count({
where: {
collection: {
ownerId: userId,
},
},
});
if (hasTooManyLinks) {
if (totalImports + numberOfLinksTheUserHas > MAX_LINKS_PER_USER)
return {
response: `Your subscription have reached the maximum number of links allowed.`,
response: `Each collection owner can only have a maximum of ${MAX_LINKS_PER_USER} Links.`,
status: 400,
};
}
await prisma
.$transaction(
@@ -55,56 +62,38 @@ export default async function importFromWallabag(
},
},
name: "Imports",
createdBy: {
connect: {
id: userId,
},
},
},
});
createFolder({ filePath: `archives/${newCollection.id}` });
for (const link of backup) {
if (link.url) {
try {
new URL(link.url.trim());
} catch (err) {
continue;
}
}
await prisma.link.create({
data: {
pinnedBy: link.is_starred
? { connect: { id: userId } }
: undefined,
url: link.url?.trim().slice(0, 254),
name: link.title?.trim().slice(0, 254) || "",
textContent: link.content?.trim() || "",
url: link.url,
name: link.title || "",
textContent: link.content || "",
importDate: link.created_at || null,
collection: {
connect: {
id: newCollection.id,
},
},
createdBy: {
connect: {
id: userId,
},
},
tags:
link.tags && link.tags[0]
? {
connectOrCreate: link.tags.map((tag) => ({
where: {
name_ownerId: {
name: tag?.trim().slice(0, 49),
name: tag.trim(),
ownerId: userId,
},
},
create: {
name: tag?.trim().slice(0, 49),
name: tag.trim(),
owner: {
connect: {
id: userId,
@@ -1,5 +1,5 @@
import { prisma } from "@/lib/api/db";
import { LinkRequestQuery, Order, Sort } from "@/types/global";
import { LinkRequestQuery, Sort } from "@/types/global";
export default async function getLink(
query: Omit<LinkRequestQuery, "tagId" | "pinnedOnly">
@@ -7,7 +7,7 @@ export default async function getLink(
const POSTGRES_IS_ENABLED =
process.env.DATABASE_URL?.startsWith("postgresql");
let order: Order = { id: "desc" };
let order: any;
if (query.sort === Sort.DateNewestFirst) order = { id: "desc" };
else if (query.sort === Sort.DateOldestFirst) order = { id: "asc" };
else if (query.sort === Sort.NameAZ) order = { name: "asc" };
@@ -5,20 +5,13 @@ export default async function getPublicUser(
isId: boolean,
requestingId?: number
) {
const user = await prisma.user.findFirst({
const user = await prisma.user.findUnique({
where: isId
? {
id: Number(targetId) as number,
}
: {
OR: [
{
username: targetId as string,
},
{
email: targetId as string,
},
],
username: targetId as string,
},
include: {
whitelistedUsers: {
@@ -29,7 +22,7 @@ export default async function getPublicUser(
},
});
if (!user || !user.id)
if (!user)
return { response: "User not found or profile is private.", status: 404 };
const whitelistedUsernames = user.whitelistedUsers?.map(
@@ -38,7 +31,7 @@ export default async function getPublicUser(
const isInAPublicCollection = await prisma.collection.findFirst({
where: {
OR: [
["OR"]: [
{ ownerId: user.id },
{
members: {
@@ -80,7 +73,6 @@ export default async function getPublicUser(
id: lessSensitiveInfo.id,
name: lessSensitiveInfo.name,
username: lessSensitiveInfo.username,
email: lessSensitiveInfo.email,
image: lessSensitiveInfo.image,
archiveAsScreenshot: lessSensitiveInfo.archiveAsScreenshot,
archiveAsMonolith: lessSensitiveInfo.archiveAsMonolith,
+1 -1
View File
@@ -29,7 +29,7 @@ export default async function createSession(
secret: process.env.NEXTAUTH_SECRET as string,
});
await prisma.accessToken.create({
const createToken = await prisma.accessToken.create({
data: {
name: sessionName || "Unknown Device",
userId,
+8 -22
View File
@@ -1,22 +1,15 @@
import { prisma } from "@/lib/api/db";
export default async function getTags({
userId,
collectionId,
}: {
userId?: number;
collectionId?: number;
}) {
export default async function getTags(userId: number) {
// Remove empty tags
if (userId)
await prisma.tag.deleteMany({
where: {
ownerId: userId,
links: {
none: {},
},
await prisma.tag.deleteMany({
where: {
ownerId: userId,
links: {
none: {},
},
});
},
});
const tags = await prisma.tag.findMany({
where: {
@@ -35,13 +28,6 @@ export default async function getTags({
},
},
},
{
links: {
some: {
collectionId,
},
},
},
],
},
include: {
@@ -1,31 +1,18 @@
import { prisma } from "@/lib/api/db";
import {
UpdateTagSchema,
UpdateTagSchemaType,
} from "@/lib/shared/schemaValidation";
import { Tag } from "@prisma/client";
export default async function updeteTagById(
userId: number,
tagId: number,
body: UpdateTagSchemaType
data: Tag
) {
const dataValidation = UpdateTagSchema.safeParse(body);
if (!dataValidation.success) {
return {
response: `Error: ${
dataValidation.error.issues[0].message
} [${dataValidation.error.issues[0].path.join(", ")}]`,
status: 400,
};
}
const { name } = dataValidation.data;
if (!tagId || !data.name)
return { response: "Please choose a valid name for the tag.", status: 401 };
const tagNameIsTaken = await prisma.tag.findFirst({
where: {
ownerId: userId,
name: name,
name: data.name,
},
});
@@ -52,7 +39,7 @@ export default async function updeteTagById(
id: tagId,
},
data: {
name: name,
name: data.name,
},
});
+15 -19
View File
@@ -1,32 +1,28 @@
import { prisma } from "@/lib/api/db";
import {
PostTokenSchemaType,
PostTokenSchema,
} from "@/lib/shared/schemaValidation";
import { TokenExpiry } from "@/types/global";
import crypto from "crypto";
import { decode, encode } from "next-auth/jwt";
export default async function postToken(
body: PostTokenSchemaType,
body: {
name: string;
expires: TokenExpiry;
},
userId: number
) {
const dataValidation = PostTokenSchema.safeParse(body);
console.log(body);
if (!dataValidation.success) {
const checkHasEmptyFields = !body.name || body.expires === undefined;
if (checkHasEmptyFields)
return {
response: `Error: ${
dataValidation.error.issues[0].message
} [${dataValidation.error.issues[0].path.join(", ")}]`,
response: "Please fill out all the fields.",
status: 400,
};
}
const { name, expires } = dataValidation.data;
const checkIfTokenExists = await prisma.accessToken.findFirst({
where: {
name: name,
name: body.name,
revoked: false,
userId,
},
@@ -44,16 +40,16 @@ export default async function postToken(
const oneDayInSeconds = 86400;
let expiryDateSecond = 7 * oneDayInSeconds;
if (expires === TokenExpiry.oneMonth) {
if (body.expires === TokenExpiry.oneMonth) {
expiryDate.setDate(expiryDate.getDate() + 30);
expiryDateSecond = 30 * oneDayInSeconds;
} else if (expires === TokenExpiry.twoMonths) {
} else if (body.expires === TokenExpiry.twoMonths) {
expiryDate.setDate(expiryDate.getDate() + 60);
expiryDateSecond = 60 * oneDayInSeconds;
} else if (expires === TokenExpiry.threeMonths) {
} else if (body.expires === TokenExpiry.threeMonths) {
expiryDate.setDate(expiryDate.getDate() + 90);
expiryDateSecond = 90 * oneDayInSeconds;
} else if (expires === TokenExpiry.never) {
} else if (body.expires === TokenExpiry.never) {
expiryDate.setDate(expiryDate.getDate() + 73000); // 200 years (not really never)
expiryDateSecond = 73050 * oneDayInSeconds;
} else {
@@ -79,7 +75,7 @@ export default async function postToken(
const createToken = await prisma.accessToken.create({
data: {
name: name,
name: body.name,
userId,
token: tokenBody?.jti as string,
expires: expiryDate,
+14 -64
View File
@@ -1,71 +1,21 @@
import { prisma } from "@/lib/api/db";
import { User } from "@prisma/client";
export default async function getUsers(user: User) {
if (user.id === Number(process.env.NEXT_PUBLIC_ADMIN || 1)) {
const users = await prisma.user.findMany({
select: {
id: true,
username: true,
email: true,
emailVerified: true,
subscriptions: {
select: {
active: true,
},
},
createdAt: true,
},
});
return {
response: users.sort((a: any, b: any) => a.id - b.id),
status: 200,
};
} else {
let subscriptionId = (
await prisma.subscription.findFirst({
where: {
userId: user.id,
},
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: {
id: true,
active: true,
},
})
)?.id;
if (!subscriptionId)
return {
response: "Subscription not found.",
status: 404,
};
const users = await prisma.user.findMany({
where: {
OR: [
{
parentSubscriptionId: subscriptionId,
},
{
subscriptions: {
id: subscriptionId,
},
},
],
},
select: {
id: true,
name: true,
username: true,
email: true,
emailVerified: true,
createdAt: true,
},
});
createdAt: true,
},
});
return {
response: users.sort((a: any, b: any) => a.id - b.id),
status: 200,
};
}
return { response: users, status: 200 };
}
+83 -72
View File
@@ -1,9 +1,7 @@
import { prisma } from "@/lib/api/db";
import type { NextApiRequest, NextApiResponse } from "next";
import bcrypt from "bcrypt";
import { PostUserSchema } from "@/lib/shared/schemaValidation";
import isAuthenticatedRequest from "../../isAuthenticatedRequest";
import { Subscription, User } from "@prisma/client";
import isServerAdmin from "../../isServerAdmin";
const emailEnabled =
process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;
@@ -14,61 +12,66 @@ interface Data {
status: number;
}
interface User {
name: string;
username?: string;
email?: string;
password: string;
}
export default async function postUser(
req: NextApiRequest,
res: NextApiResponse
): Promise<Data> {
const parentUser = await isAuthenticatedRequest({ req });
const isAdmin =
parentUser && parentUser.id === Number(process.env.NEXT_PUBLIC_ADMIN || 1);
const DISABLE_INVITES = process.env.DISABLE_INVITES === "true";
let isAdmin = await isServerAdmin({ req });
if (process.env.NEXT_PUBLIC_DISABLE_REGISTRATION === "true" && !isAdmin) {
return { response: "Registration is disabled.", status: 400 };
}
const dataValidation = PostUserSchema().safeParse(req.body);
const body: User = req.body;
if (!dataValidation.success) {
return {
response: `Error: ${
dataValidation.error.issues[0].message
} [${dataValidation.error.issues[0].path.join(", ")}]`,
status: 400,
};
}
const checkHasEmptyFields = emailEnabled
? !body.password || !body.name || !body.email
: !body.username || !body.password || !body.name;
const { name, email, password, invite } = dataValidation.data;
let { username } = dataValidation.data;
if (!body.password || body.password.length < 8)
return { response: "Password must be at least 8 characters.", status: 400 };
if (invite && (DISABLE_INVITES || !emailEnabled)) {
return { response: "You are not authorized to invite users.", status: 401 };
} else if (invite && !parentUser) {
return { response: "You must be logged in to invite users.", status: 401 };
}
if (checkHasEmptyFields)
return { response: "Please fill out all the fields.", status: 400 };
// Check email (if enabled)
const checkEmail =
/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
if (emailEnabled && !checkEmail.test(body.email?.toLowerCase() || ""))
return { response: "Please enter a valid email.", status: 400 };
// Check username (if email was disabled)
const checkUsername = RegExp("^[a-z0-9_-]{3,31}$");
const autoGeneratedUsername = "user" + Math.round(Math.random() * 1000000000);
if (!username) {
username = autoGeneratedUsername;
}
if (!emailEnabled && !password) {
if (body.username && !checkUsername.test(body.username?.toLowerCase()))
return {
response: "Password is required.",
response:
"Username has to be between 3-30 characters, no spaces and special characters are allowed.",
status: 400,
};
else if (!body.username) {
body.username = autoGeneratedUsername;
}
const checkIfUserExists = await prisma.user.findFirst({
where: {
OR: [
{
email: email ? email.toLowerCase().trim() : undefined,
email: body.email ? body.email.toLowerCase().trim() : undefined,
},
{
username: username ? username.toLowerCase().trim() : undefined,
username: body.username
? body.username.toLowerCase().trim()
: undefined,
},
],
},
@@ -80,57 +83,65 @@ export default async function postUser(
const saltRounds = 10;
const hashedPassword = bcrypt.hashSync(password || "", saltRounds);
const hashedPassword = bcrypt.hashSync(body.password, saltRounds);
const user = await prisma.user.create({
data: {
name: name,
username: emailEnabled ? username || autoGeneratedUsername : username,
email: emailEnabled ? email : undefined,
emailVerified: isAdmin ? new Date() : undefined,
password: password ? hashedPassword : undefined,
parentSubscription:
parentUser && invite
? {
connect: {
id: (parentUser.subscriptions as Subscription).id,
},
}
: undefined,
subscriptions:
stripeEnabled && isAdmin
// Subscription dates
const currentPeriodStart = new Date();
const currentPeriodEnd = new Date();
currentPeriodEnd.setFullYear(currentPeriodEnd.getFullYear() + 1000); // end date is in 1000 years...
if (isAdmin) {
const user = await prisma.user.create({
data: {
name: body.name,
username: emailEnabled
? (body.username as string).toLowerCase().trim() ||
autoGeneratedUsername
: (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: new Date(),
currentPeriodEnd: new Date(
new Date().setFullYear(new Date().getFullYear() + 1000)
), // 1000 years from now
currentPeriodStart,
currentPeriodEnd,
},
}
: undefined,
},
select: isAdmin
? {
id: true,
username: true,
email: true,
emailVerified: true,
password: true,
subscriptions: {
select: {
active: true,
},
},
select: {
id: true,
username: true,
email: true,
emailVerified: true,
subscriptions: {
select: {
active: true,
},
createdAt: true,
}
: undefined,
});
},
createdAt: true,
},
});
const { password: pass, ...userWithoutPassword } = user as User;
return { response: userWithoutPassword, status: 201 };
return { response: user, status: 201 };
} else {
await prisma.user.create({
data: {
name: body.name,
username: emailEnabled
? autoGeneratedUsername
: (body.username as string).toLowerCase().trim(),
email: emailEnabled ? body.email?.toLowerCase().trim() : undefined,
password: hashedPassword,
},
});
return { response: "User successfully created.", status: 201 };
}
} else {
return { response: "Email or Username already exists.", status: 400 };
}
@@ -4,28 +4,15 @@ import removeFolder from "@/lib/api/storage/removeFolder";
import Stripe from "stripe";
import { DeleteUserBody } from "@/types/global";
import removeFile from "@/lib/api/storage/removeFile";
import updateSeats from "@/lib/api/stripe/updateSeats";
export default async function deleteUserById(
userId: number,
body: DeleteUserBody,
isServerAdmin: boolean,
queryId: number
isServerAdmin?: boolean
) {
// First, we retrieve the user from the database
const user = await prisma.user.findUnique({
where: { id: userId },
include: {
subscriptions: {
include: {
user: true,
},
},
parentSubscription: {
include: {
user: true,
},
},
},
});
if (!user) {
@@ -36,74 +23,24 @@ export default async function deleteUserById(
}
if (!isServerAdmin) {
if (queryId === userId) {
if (user.password) {
const isPasswordValid = bcrypt.compareSync(
body.password,
user.password
);
if (user.password) {
const isPasswordValid = bcrypt.compareSync(
body.password,
user.password as string
);
if (!isPasswordValid && !isServerAdmin) {
return {
response: "Invalid credentials.",
status: 401,
};
}
} else {
if (!isPasswordValid && !isServerAdmin) {
return {
response:
"User has no password. Please reset your password from the forgot password page.",
status: 401,
response: "Invalid credentials.",
status: 401, // Unauthorized
};
}
} else {
if (user.parentSubscriptionId) {
console.log(userId, user.parentSubscriptionId);
return {
response: "Permission denied.",
status: 401,
};
} else {
if (!user.subscriptions) {
return {
response: "User has no subscription.",
status: 401,
};
}
const findChild = await prisma.user.findFirst({
where: { id: queryId, parentSubscriptionId: user.subscriptions?.id },
});
if (!findChild)
return {
response: "Permission denied.",
status: 401,
};
const removeUser = await prisma.user.update({
where: { id: findChild.id },
data: {
parentSubscription: {
disconnect: true,
},
},
select: {
id: true,
},
});
await updateSeats(
user.subscriptions.stripeSubscriptionId,
user.subscriptions.quantity - 1
);
return {
response: removeUser,
status: 200,
};
}
return {
response:
"User has no password. Please reset your password from the forgot password page.",
status: 401, // Unauthorized
};
}
}
@@ -113,27 +50,27 @@ export default async function deleteUserById(
async (prisma) => {
// Delete Access Tokens
await prisma.accessToken.deleteMany({
where: { userId: queryId },
where: { userId },
});
// Delete whitelisted users
await prisma.whitelistedUser.deleteMany({
where: { userId: queryId },
where: { userId },
});
// Delete links
await prisma.link.deleteMany({
where: { collection: { ownerId: queryId } },
where: { collection: { ownerId: userId } },
});
// Delete tags
await prisma.tag.deleteMany({
where: { ownerId: queryId },
where: { ownerId: userId },
});
// Find collections that the user owns
const collections = await prisma.collection.findMany({
where: { ownerId: queryId },
where: { ownerId: userId },
});
for (const collection of collections) {
@@ -152,29 +89,29 @@ export default async function deleteUserById(
// Delete collections after cleaning up related data
await prisma.collection.deleteMany({
where: { ownerId: queryId },
where: { ownerId: userId },
});
// Delete subscription
if (process.env.STRIPE_SECRET_KEY)
await prisma.subscription
.delete({
where: { userId: queryId },
where: { userId },
})
.catch((err) => console.log(err));
await prisma.usersAndCollections.deleteMany({
where: {
OR: [{ userId: queryId }, { collection: { ownerId: queryId } }],
OR: [{ userId: userId }, { collection: { ownerId: userId } }],
},
});
// Delete user's avatar
await removeFile({ filePath: `uploads/avatar/${queryId}.jpg` });
await removeFile({ filePath: `uploads/avatar/${userId}.jpg` });
// Finally, delete the user
await prisma.user.delete({
where: { id: queryId },
where: { id: userId },
});
},
{ timeout: 20000 }
@@ -187,36 +124,24 @@ export default async function deleteUserById(
});
try {
if (user.subscriptions?.id) {
const listByEmail = await stripe.customers.list({
email: user.email?.toLowerCase(),
expand: ["data.subscriptions"],
});
const listByEmail = await stripe.customers.list({
email: user.email?.toLowerCase(),
expand: ["data.subscriptions"],
});
if (listByEmail.data[0].subscriptions?.data[0].id) {
const deleted = await stripe.subscriptions.cancel(
listByEmail.data[0].subscriptions?.data[0].id,
{
cancellation_details: {
comment: body.cancellation_details?.comment,
feedback: body.cancellation_details?.feedback,
},
}
);
return {
response: deleted,
status: 200,
};
}
} else if (user.parentSubscription?.id) {
await updateSeats(
user.parentSubscription.stripeSubscriptionId,
user.parentSubscription.quantity - 1
if (listByEmail.data[0].subscriptions?.data[0].id) {
const deleted = await stripe.subscriptions.cancel(
listByEmail.data[0].subscriptions?.data[0].id,
{
cancellation_details: {
comment: body.cancellation_details?.comment,
feedback: body.cancellation_details?.feedback,
},
}
);
return {
response: "User account and all related data deleted successfully.",
response: deleted,
status: 200,
};
}
@@ -12,11 +12,6 @@ export default async function getUserById(userId: number) {
},
},
subscriptions: true,
parentSubscription: {
include: {
user: true,
},
},
},
});
@@ -27,21 +22,13 @@ export default async function getUserById(userId: number) {
(usernames) => usernames.username
);
const { password, subscriptions, parentSubscription, ...lessSensitiveInfo } =
user;
const { password, subscriptions, ...lessSensitiveInfo } = user;
const data = {
...lessSensitiveInfo,
whitelistedUsers: whitelistedUsernames,
subscription: {
active: subscriptions?.active,
quantity: subscriptions?.quantity,
},
parentSubscription: {
active: parentSubscription?.active,
user: {
email: parentSubscription?.user.email,
},
},
};
@@ -6,27 +6,42 @@ import createFile from "@/lib/api/storage/createFile";
import createFolder from "@/lib/api/storage/createFolder";
import sendChangeEmailVerificationRequest from "@/lib/api/sendChangeEmailVerificationRequest";
import { i18n } from "next-i18next.config";
import { UpdateUserSchema } from "@/lib/shared/schemaValidation";
const emailEnabled =
process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;
export default async function updateUserById(
userId: number,
body: AccountSettings
data: AccountSettings
) {
const dataValidation = UpdateUserSchema().safeParse(body);
if (!dataValidation.success) {
if (emailEnabled && !data.email)
return {
response: `Error: ${
dataValidation.error.issues[0].message
} [${dataValidation.error.issues[0].path.join(", ")}]`,
response: "Email invalid.",
status: 400,
};
else if (!data.username)
return {
response: "Username invalid.",
status: 400,
};
}
const data = dataValidation.data;
// Check email (if enabled)
const checkEmail =
/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
if (emailEnabled && !checkEmail.test(data.email?.toLowerCase() || ""))
return {
response: "Please enter a valid email.",
status: 400,
};
const checkUsername = RegExp("^[a-z0-9_-]{3,31}$");
if (!checkUsername.test(data.username.toLowerCase()))
return {
response:
"Username has to be between 3-30 characters, no spaces and special characters are allowed.",
status: 400,
};
const userIsTaken = await prisma.user.findFirst({
where: {
@@ -101,6 +116,7 @@ export default async function updateUserById(
const user = await prisma.user.findUnique({
where: { id: userId },
select: { email: true, password: true },
});
if (user && user.email && data.email && data.email !== user.email) {
@@ -132,7 +148,7 @@ export default async function updateUserById(
sendChangeEmailVerificationRequest(
user.email,
data.email,
data.name?.trim() || user.name || "Linkwarden User"
data.name.trim()
);
}
@@ -169,28 +185,16 @@ export default async function updateUserById(
// Other settings / Apply changes
const isInvited =
user?.name === null && user.parentSubscriptionId && !user.password;
if (isInvited && data.password === "")
return {
response: "Password is required.",
status: 400,
};
const saltRounds = 10;
const newHashedPassword = bcrypt.hashSync(
data.newPassword || data.password || "",
saltRounds
);
const newHashedPassword = bcrypt.hashSync(data.newPassword || "", saltRounds);
const updatedUser = await prisma.user.update({
where: {
id: userId,
},
data: {
name: data.name,
username: data.username,
name: data.name.trim(),
username: data.username?.toLowerCase().trim(),
isPrivate: data.isPrivate,
image:
data.image && data.image.startsWith("http")
@@ -198,10 +202,10 @@ export default async function updateUserById(
: data.image
? `uploads/avatar/${userId}.jpg`
: "",
collectionOrder: data.collectionOrder?.filter(
collectionOrder: data.collectionOrder.filter(
(value, index, self) => self.indexOf(value) === index
),
locale: i18n.locales.includes(data.locale || "") ? data.locale : "en",
locale: i18n.locales.includes(data.locale) ? data.locale : "en",
archiveAsScreenshot: data.archiveAsScreenshot,
archiveAsMonolith: data.archiveAsMonolith,
archiveAsPDF: data.archiveAsPDF,
@@ -209,28 +213,18 @@ export default async function updateUserById(
linksRouteTo: data.linksRouteTo,
preventDuplicateLinks: data.preventDuplicateLinks,
password:
isInvited || (data.newPassword && data.newPassword !== "")
data.newPassword && data.newPassword !== ""
? newHashedPassword
: undefined,
},
include: {
whitelistedUsers: true,
subscriptions: true,
parentSubscription: {
include: {
user: true,
},
},
},
});
const {
whitelistedUsers,
password,
subscriptions,
parentSubscription,
...userInfo
} = updatedUser;
const { whitelistedUsers, password, subscriptions, ...userInfo } =
updatedUser;
// If user.whitelistedUsers is not provided, we will assume the whitelistedUsers should be removed
const newWhitelistedUsernames: string[] = data.whitelistedUsers || [];
@@ -271,20 +265,11 @@ export default async function updateUserById(
});
}
const response = {
const response: Omit<AccountSettings, "password"> = {
...userInfo,
whitelistedUsers: newWhitelistedUsernames,
image: userInfo.image ? `${userInfo.image}?${Date.now()}` : "",
subscription: {
active: subscriptions?.active,
quantity: subscriptions?.quantity,
},
parentSubscription: {
active: parentSubscription?.active,
user: {
email: parentSubscription?.user.email,
},
},
subscription: { active: subscriptions?.active },
};
return { response, status: 200 };