Merge pull request #115 from crkos/dev

add sqlite compatibility + fix whitespace bug collections
This commit is contained in:
Daniel 2023-08-04 18:37:39 -04:00 committed by GitHub
commit 2177f12b9b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 176 additions and 107 deletions

2
.gitignore vendored
View File

@ -36,6 +36,8 @@ next-env.d.ts
# generated files and folders # generated files and folders
/data /data
.idea
prisma/dev.db
# tests # tests
/tests /tests

View File

@ -1,10 +1,11 @@
import { prisma } from "@/lib/api/db"; import {prisma} from "@/lib/api/db";
import { LinkRequestQuery, Sort } from "@/types/global"; import {LinkRequestQuery, Sort} from "@/types/global";
export default async function getLink(userId: number, body: string) { export default async function getLink(userId: number, body: string) {
const query: LinkRequestQuery = JSON.parse(decodeURIComponent(body)); const query: LinkRequestQuery = JSON.parse(decodeURIComponent(body));
console.log(query); console.log(query);
const POSTGRES_IS_ENABLED = process.env.DATABASE_URL.startsWith("postgresql");
// Sorting logic // Sorting logic
let order: any; let order: any;
if (query.sort === Sort.DateNewestFirst) if (query.sort === Sort.DateNewestFirst)
@ -37,8 +38,8 @@ export default async function getLink(userId: number, body: string) {
skip: query.cursor ? 1 : undefined, skip: query.cursor ? 1 : undefined,
cursor: query.cursor cursor: query.cursor
? { ? {
id: query.cursor, id: query.cursor,
} }
: undefined, : undefined,
where: { where: {
collection: { collection: {
@ -58,7 +59,7 @@ export default async function getLink(userId: number, body: string) {
}, },
[query.searchQuery ? "OR" : "AND"]: [ [query.searchQuery ? "OR" : "AND"]: [
{ {
pinnedBy: query.pinnedOnly ? { some: { id: userId } } : undefined, pinnedBy: query.pinnedOnly ? {some: {id: userId}} : undefined,
}, },
{ {
name: { name: {
@ -66,7 +67,7 @@ export default async function getLink(userId: number, body: string) {
query.searchQuery && query.searchFilter?.name query.searchQuery && query.searchFilter?.name
? query.searchQuery ? query.searchQuery
: undefined, : undefined,
mode: "insensitive", mode: POSTGRES_IS_ENABLED ? "insensitive" : undefined
}, },
}, },
{ {
@ -75,7 +76,7 @@ export default async function getLink(userId: number, body: string) {
query.searchQuery && query.searchFilter?.url query.searchQuery && query.searchFilter?.url
? query.searchQuery ? query.searchQuery
: undefined, : undefined,
mode: "insensitive", mode: POSTGRES_IS_ENABLED ? "insensitive" : undefined
}, },
}, },
{ {
@ -84,7 +85,7 @@ export default async function getLink(userId: number, body: string) {
query.searchQuery && query.searchFilter?.description query.searchQuery && query.searchFilter?.description
? query.searchQuery ? query.searchQuery
: undefined, : undefined,
mode: "insensitive", mode: POSTGRES_IS_ENABLED ? "insensitive" : undefined
}, },
}, },
{ {
@ -92,44 +93,44 @@ export default async function getLink(userId: number, body: string) {
query.searchQuery && !query.searchFilter?.tags query.searchQuery && !query.searchFilter?.tags
? undefined ? undefined
: { : {
some: query.tagId some: query.tagId
? { ? {
// If tagId was defined, filter by tag // If tagId was defined, filter by tag
id: query.tagId, id: query.tagId,
name: name:
query.searchQuery && query.searchFilter?.tags query.searchQuery && query.searchFilter?.tags
? { ? {
contains: query.searchQuery, contains: query.searchQuery,
mode: "insensitive", mode: POSTGRES_IS_ENABLED ? "insensitive" : undefined
} }
: undefined, : undefined,
OR: [ OR: [
{ ownerId: userId }, // Tags owned by the user {ownerId: userId}, // Tags owned by the user
{ {
links: { links: {
some: { some: {
name: { name: {
contains: contains:
query.searchQuery && query.searchQuery &&
query.searchFilter?.tags query.searchFilter?.tags
? query.searchQuery ? query.searchQuery
: undefined, : undefined,
mode: "insensitive", mode: POSTGRES_IS_ENABLED ? "insensitive" : undefined
}, },
collection: { collection: {
members: { members: {
some: { some: {
userId, // Tags from collections where the user is a member userId, // Tags from collections where the user is a member
},
},
}, },
}, },
}, },
}, },
], },
} },
: undefined, ],
}, }
: undefined,
},
}, },
], ],
}, },
@ -137,8 +138,8 @@ export default async function getLink(userId: number, body: string) {
tags: true, tags: true,
collection: true, collection: true,
pinnedBy: { pinnedBy: {
where: { id: userId }, where: {id: userId},
select: { id: true }, select: {id: true},
}, },
}, },
orderBy: order || { orderBy: order || {
@ -146,5 +147,5 @@ export default async function getLink(userId: number, body: string) {
}, },
}); });
return { response: links, status: 200 }; return {response: links, status: 200};
} }

View File

@ -20,12 +20,15 @@ export default async function postLink(
}; };
} }
link.collection.name = link.collection.name.trim(); // This has to move above we assign link.collection.name
// Because if the link is null (write then delete text on collection)
// It will try to do trim on empty string and will throw and error, this prevents it.
if (!link.collection.name) { if (!link.collection.name) {
link.collection.name = "Unnamed Collection"; link.collection.name = "Unnamed Collection";
} }
link.collection.name = link.collection.name.trim();
if (link.collection.id) { if (link.collection.id) {
const collectionIsAccessible = (await getPermission( const collectionIsAccessible = (await getPermission(
userId, userId,

View File

@ -17,14 +17,23 @@ export default async function getUser({
id: params.lookupId, id: params.lookupId,
username: params.lookupUsername?.toLowerCase(), username: params.lookupUsername?.toLowerCase(),
}, },
include: {
whitelistedUsers: {
select: {
username: true
}
}
}
}); });
if (!user) return { response: "User not found.", status: 404 }; if (!user) return { response: "User not found.", status: 404 };
const whitelistedUsernames = user.whitelistedUsers?.map(usernames => usernames.username);
if ( if (
!isSelf && !isSelf &&
user?.isPrivate && user?.isPrivate &&
!user.whitelistedUsers.includes(username.toLowerCase()) !whitelistedUsernames.includes(username.toLowerCase())
) { ) {
return { response: "This profile is private.", status: 401 }; return { response: "This profile is private.", status: 401 };
} }
@ -33,7 +42,7 @@ export default async function getUser({
const data = isSelf const data = isSelf
? // If user is requesting its own data ? // If user is requesting its own data
lessSensitiveInfo {...lessSensitiveInfo, whitelistedUsers: whitelistedUsernames}
: { : {
// If user is requesting someone elses data // If user is requesting someone elses data
id: lessSensitiveInfo.id, id: lessSensitiveInfo.id,

View File

@ -106,14 +106,56 @@ export default async function updateUser(
username: user.username.toLowerCase(), username: user.username.toLowerCase(),
email: user.email?.toLowerCase(), email: user.email?.toLowerCase(),
isPrivate: user.isPrivate, isPrivate: user.isPrivate,
whitelistedUsers: user.whitelistedUsers,
password: password:
user.newPassword && user.newPassword !== "" user.newPassword && user.newPassword !== ""
? newHashedPassword ? newHashedPassword
: undefined, : undefined,
}, },
include: {
whitelistedUsers: true
}
}); });
const { whitelistedUsers, password, ...userInfo } = updatedUser;
// If user.whitelistedUsers is not provided, we will assume the whitelistedUsers should be removed
const newWhitelistedUsernames: string[] = user.whitelistedUsers || [];
// Get the current whitelisted usernames
const currentWhitelistedUsernames: string[] = whitelistedUsers.map((user) => user.username);
// Find the usernames to be deleted (present in current but not in new)
const usernamesToDelete: string[] = currentWhitelistedUsernames.filter(
(username) => !newWhitelistedUsernames.includes(username)
);
// Find the usernames to be created (present in new but not in current)
const usernamesToCreate: string[] = newWhitelistedUsernames.filter(
(username) => !currentWhitelistedUsernames.includes(username) && username.trim() !== ''
);
// Delete whitelistedUsers that are not present in the new list
await prisma.whitelistedUser.deleteMany({
where: {
userId: sessionUser.id,
username: {
in: usernamesToDelete,
},
},
});
// Create new whitelistedUsers that are not in the current list, no create many ;(
for (const username of usernamesToCreate) {
await prisma.whitelistedUser.create({
data: {
username,
userId: sessionUser.id,
},
});
}
const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY; const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
const PRICE_ID = process.env.PRICE_ID; const PRICE_ID = process.env.PRICE_ID;
@ -125,10 +167,9 @@ export default async function updateUser(
user.email as string user.email as string
); );
const { password, ...userInfo } = updatedUser;
const response: Omit<AccountSettings, "password"> = { const response: Omit<AccountSettings, "password"> = {
...userInfo, ...userInfo,
whitelistedUsers: newWhitelistedUsernames,
profilePic: `/api/avatar/${userInfo.id}?${Date.now()}`, profilePic: `/api/avatar/${userInfo.id}?${Date.now()}`,
}; };

View File

@ -33,11 +33,16 @@ export default async function Index(req: NextApiRequest, res: NextApiResponse) {
where: { where: {
id: queryId, id: queryId,
}, },
include: {
whitelistedUsers: true
}
}); });
const whitelistedUsernames = targetUser?.whitelistedUsers.map(whitelistedUsername => whitelistedUsername.username);
if ( if (
targetUser?.isPrivate && targetUser?.isPrivate &&
!targetUser.whitelistedUsers.includes(username) !whitelistedUsernames?.includes(username)
) { ) {
return res return res
.setHeader("Content-Type", "text/plain") .setHeader("Content-Type", "text/plain")

View File

@ -4,22 +4,22 @@ generator client {
datasource db { datasource db {
provider = "postgresql" provider = "postgresql"
url = env("DATABASE_URL") url = env("DATABASE_URL")
} }
model Account { model Account {
id String @id @default(cuid()) id String @id @default(cuid())
userId Int userId Int
type String type String
provider String provider String
providerAccountId String providerAccountId String
refresh_token String? @db.Text refresh_token String?
access_token String? @db.Text access_token String?
expires_at Int? expires_at Int?
token_type String? token_type String?
scope String? scope String?
id_token String? @db.Text id_token String?
session_state String? session_state String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade) user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@ -35,29 +35,37 @@ model Session {
} }
model User { model User {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
name String name String
username String? @unique username String? @unique
email String? @unique email String? @unique
emailVerified DateTime? emailVerified DateTime?
image String? image String?
accounts Account[] accounts Account[]
sessions Session[] sessions Session[]
password String
collections Collection[]
tags Tag[] password String
collections Collection[]
pinnedLinks Link[] tags Tag[]
collectionsJoined UsersAndCollections[] pinnedLinks Link[]
isPrivate Boolean @default(false)
whitelistedUsers String[] @default([]) collectionsJoined UsersAndCollections[]
createdAt DateTime @default(now()) isPrivate Boolean @default(false)
whitelistedUsers WhitelistedUser[]
createdAt DateTime @default(now())
}
model WhitelistedUser {
id Int @id @default(autoincrement())
username String @default("")
User User? @relation(fields: [userId], references: [id])
userId Int?
} }
model VerificationToken { model VerificationToken {
@ -69,27 +77,26 @@ model VerificationToken {
} }
model Collection { model Collection {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
name String name String
description String @default("") description String @default("")
color String @default("#0ea5e9") color String @default("#0ea5e9")
isPublic Boolean @default(false) isPublic Boolean @default(false)
owner User @relation(fields: [ownerId], references: [id])
owner User @relation(fields: [ownerId], references: [id]) ownerId Int
ownerId Int members UsersAndCollections[]
members UsersAndCollections[] links Link[]
links Link[] createdAt DateTime @default(now())
createdAt DateTime @default(now())
@@unique([name, ownerId]) @@unique([name, ownerId])
} }
model UsersAndCollections { model UsersAndCollections {
user User @relation(fields: [userId], references: [id]) user User @relation(fields: [userId], references: [id])
userId Int userId Int
collection Collection @relation(fields: [collectionId], references: [id]) collection Collection @relation(fields: [collectionId], references: [id])
collectionId Int collectionId Int
canCreate Boolean canCreate Boolean
@ -100,24 +107,24 @@ model UsersAndCollections {
} }
model Link { model Link {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
name String name String
url String url String
description String @default("") description String @default("")
pinnedBy User[] pinnedBy User[]
collection Collection @relation(fields: [collectionId], references: [id]) collection Collection @relation(fields: [collectionId], references: [id])
collectionId Int collectionId Int
tags Tag[] tags Tag[]
createdAt DateTime @default(now()) createdAt DateTime @default(now())
} }
model Tag { model Tag {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
name String name String
links Link[] links Link[]
owner User @relation(fields: [ownerId], references: [id]) owner User @relation(fields: [ownerId], references: [id])
ownerId Int ownerId Int
@@unique([name, ownerId]) @@unique([name, ownerId])

View File

@ -36,6 +36,7 @@ export interface CollectionIncludingMembersAndLinkCount
export interface AccountSettings extends User { export interface AccountSettings extends User {
profilePic: string; profilePic: string;
newPassword?: string; newPassword?: string;
whitelistedUsers: string[]
} }
interface LinksIncludingTags extends Link { interface LinksIncludingTags extends Link {