⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.
TypeScript bookmarkbookmark-managercollaborationnextjsreact-nativeread-it-laterself-hostedtypescript
added the route
daniel31x13239589eaed5b
diff --git a/components/ModalContent/NewCollectionModal.tsx b/components/ModalContent/NewCollectionModal.tsxindex 7c174975..980bb44e 100644--- a/components/ModalContent/NewCollectionModal.tsx+++ b/components/ModalContent/NewCollectionModal.tsx@@ -47,7 +47,7 @@ export default function NewCollectionModal({ onClose, parent }: Props) {toast.dismiss(load);if (response.ok) {- toast.success(t("created"));+ toast.success(t("created_success"));if (response.data) {setAccount(data?.user.id as number);onClose();diff --git a/components/ModalContent/UploadFileModal.tsx b/components/ModalContent/UploadFileModal.tsxindex 1dc7a8c3..6b8aa772 100644--- a/components/ModalContent/UploadFileModal.tsx+++ b/components/ModalContent/UploadFileModal.tsx@@ -99,7 +99,7 @@ export default function UploadFileModal({ onClose }: Props) {toast.dismiss(load);if (response.ok) {- toast.success(t("created"));+ toast.success(t("created_success"));onClose();} else {toast.error(response.data as string);diff --git a/lib/api/controllers/session/createSession.ts b/lib/api/controllers/session/createSession.tsnew file mode 100644index 00000000..c2ff37e8--- /dev/null+++ b/lib/api/controllers/session/createSession.ts@@ -0,0 +1,48 @@+import { prisma } from "@/lib/api/db";+import crypto from "crypto";+import { decode, encode } from "next-auth/jwt";++export default async function createSession(+ userId: number,+ sessionName?: string+) {+ const now = Date.now();+ const expiryDate = new Date();+ const oneDayInSeconds = 86400;++ expiryDate.setDate(expiryDate.getDate() + 73000); // 200 years (not really never)+ const expiryDateSecond = 73050 * oneDayInSeconds;++ const token = await encode({+ token: {+ id: userId,+ iat: now / 1000,+ exp: (expiryDate as any) / 1000,+ jti: crypto.randomUUID(),+ },+ maxAge: expiryDateSecond || 604800,+ secret: process.env.NEXTAUTH_SECRET,+ });++ const tokenBody = await decode({+ token,+ secret: process.env.NEXTAUTH_SECRET,+ });++ const createToken = await prisma.accessToken.create({+ data: {+ name: sessionName || "Unknown Device",+ userId,+ token: tokenBody?.jti as string,+ isSession: true,+ expires: expiryDate,+ },+ });++ return {+ response: {+ token,+ },+ status: 200,+ };+}diff --git a/lib/api/controllers/tokens/getTokens.ts b/lib/api/controllers/tokens/getTokens.tsindex a5db351a..1c6efe30 100644--- a/lib/api/controllers/tokens/getTokens.ts+++ b/lib/api/controllers/tokens/getTokens.ts@@ -9,6 +9,7 @@ export default async function getToken(userId: number) {select: {id: true,name: true,+ isSession: true,expires: true,createdAt: true,},diff --git a/lib/api/verifyByCredentials.ts b/lib/api/verifyByCredentials.tsnew file mode 100644index 00000000..a0bbba21--- /dev/null+++ b/lib/api/verifyByCredentials.ts@@ -0,0 +1,63 @@+import { prisma } from "./db";+import { User } from "@prisma/client";+import verifySubscription from "./verifySubscription";+import bcrypt from "bcrypt";++type Props = {+ username: string;+ password: string;+};++const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;+const emailEnabled =+ process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;++export default async function verifyByCredentials({+ username,+ password,+}: Props): Promise<User | null> {+ const user = await prisma.user.findFirst({+ where: emailEnabled+ ? {+ OR: [+ {+ username: username.toLowerCase(),+ },+ {+ email: username?.toLowerCase(),+ },+ ],+ }+ : {+ username: username.toLowerCase(),+ },+ include: {+ subscriptions: true,+ },+ });++ if (!user) {+ return null;+ }++ let passwordMatches: boolean = false;++ if (user?.password) {+ passwordMatches = bcrypt.compareSync(password, user.password);++ if (!passwordMatches) {+ return null;+ } else {+ if (STRIPE_SECRET_KEY) {+ const subscribedUser = await verifySubscription(user);++ if (!subscribedUser) {+ return null;+ }+ }+ return user;+ }+ } else {+ return null;+ }+}diff --git a/pages/api/v1/session/index.ts b/pages/api/v1/session/index.tsnew file mode 100644index 00000000..bd3e50b1--- /dev/null+++ b/pages/api/v1/session/index.ts@@ -0,0 +1,23 @@+import type { NextApiRequest, NextApiResponse } from "next";+import verifyByCredentials from "@/lib/api/verifyByCredentials";+import createSession from "@/lib/api/controllers/session/createSession";++export default async function session(+ req: NextApiRequest,+ res: NextApiResponse+) {+ const { username, password, sessionName } = req.body;++ const user = await verifyByCredentials({ username, password });++ if (!user)+ return res.status(400).json({+ response:+ "Invalid credentials. You might need to reset your password if you're sure you already signed up with the current username/email.",+ });++ if (req.method === "POST") {+ const token = await createSession(user.id, sessionName);+ return res.status(token.status).json({ response: token.response });+ }+}diff --git a/pages/settings/access-tokens.tsx b/pages/settings/access-tokens.tsxindex ef66f6dc..e526e2fa 100644--- a/pages/settings/access-tokens.tsx+++ b/pages/settings/access-tokens.tsx@@ -49,45 +49,50 @@ export default function AccessTokens() {</button>{tokens.length > 0 ? (- <>- <div className="divider my-0"></div>-- <table className="table">- <thead>- <tr>- <th></th>- <th>{t("name")}</th>- <th>{t("created")}</th>- <th>{t("expires")}</th>- <th></th>- </tr>- </thead>- <tbody>- {tokens.map((token, i) => (- <React.Fragment key={i}>- <tr>- <th>{i + 1}</th>- <td>{token.name}</td>- <td>- {new Date(token.createdAt || "").toLocaleDateString()}- </td>- <td>- {new Date(token.expires || "").toLocaleDateString()}- </td>- <td>- <button- className="btn btn-sm btn-ghost btn-square hover:bg-red-500"- onClick={() => openRevokeModal(token as AccessToken)}+ <table className="table mt-2 overflow-x-auto">+ <thead>+ <tr>+ <th>{t("name")}</th>+ <th>{t("created")}</th>+ <th>{t("expires")}</th>+ <th></th>+ </tr>+ </thead>+ <tbody>+ {tokens.map((token, i) => (+ <React.Fragment key={i}>+ <tr>+ <td className={token.isSession ? "text-primary" : ""}>+ {token.isSession ? (+ <div+ className="tooltip tooltip-right text-left"+ data-tip="This is a permanent session">- <i className="bi-x text-lg"></i>- </button>- </td>- </tr>- </React.Fragment>- ))}- </tbody>- </table>- </>+ {token.name}+ </div>+ ) : (+ token.name+ )}+ </td>+ <td>+ {new Date(token.createdAt || "").toLocaleDateString()}+ </td>+ <td>+ {new Date(token.expires || "").toLocaleDateString()}+ </td>+ <td>+ <button+ className="btn btn-sm btn-ghost btn-square hover:bg-red-500"+ onClick={() => openRevokeModal(token as AccessToken)}+ >+ <i className="bi-x text-lg"></i>+ </button>+ </td>+ </tr>+ </React.Fragment>+ ))}+ </tbody>+ </table>) : undefined}</div>diff --git a/prisma/migrations/20240626225737_add_new_field_to_access_tokens/migration.sql b/prisma/migrations/20240626225737_add_new_field_to_access_tokens/migration.sqlnew file mode 100644index 00000000..f502cb9a--- /dev/null+++ b/prisma/migrations/20240626225737_add_new_field_to_access_tokens/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "AccessToken" ADD COLUMN "isSession" BOOLEAN NOT NULL DEFAULT false;diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex b1af7174..37c544a4 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -175,6 +175,7 @@ model AccessToken {userId Inttoken String @uniquerevoked Boolean @default(false)+ isSession Boolean @default(false)expires DateTimelastUsedAt DateTime?createdAt DateTime @default(now())diff --git a/public/locales/en/common.json b/public/locales/en/common.jsonindex 7b6dd576..bb6cf70e 100644--- a/public/locales/en/common.json+++ b/public/locales/en/common.json@@ -92,7 +92,8 @@"access_tokens_description": "Access Tokens can be used to access Linkwarden from other apps and services without giving away your Username and Password.","new_token": "New Access Token","name": "Name",- "created": "Created!",+ "created_success": "Created!",+ "created": "Created","expires": "Expires","accountSettings": "Account Settings","language": "Language",