added the route

This commit is contained in:
daniel31x13 2024-06-26 21:38:34 -04:00
parent 586074ef43
commit 239589eaed
10 changed files with 185 additions and 41 deletions

View File

@ -47,7 +47,7 @@ export default function NewCollectionModal({ onClose, parent }: Props) {
toast.dismiss(load); toast.dismiss(load);
if (response.ok) { if (response.ok) {
toast.success(t("created")); toast.success(t("created_success"));
if (response.data) { if (response.data) {
setAccount(data?.user.id as number); setAccount(data?.user.id as number);
onClose(); onClose();

View File

@ -99,7 +99,7 @@ export default function UploadFileModal({ onClose }: Props) {
toast.dismiss(load); toast.dismiss(load);
if (response.ok) { if (response.ok) {
toast.success(t("created")); toast.success(t("created_success"));
onClose(); onClose();
} else { } else {
toast.error(response.data as string); toast.error(response.data as string);

View File

@ -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,
};
}

View File

@ -9,6 +9,7 @@ export default async function getToken(userId: number) {
select: { select: {
id: true, id: true,
name: true, name: true,
isSession: true,
expires: true, expires: true,
createdAt: true, createdAt: true,
}, },

View File

@ -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;
}
}

View File

@ -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 });
}
}

View File

@ -49,13 +49,9 @@ export default function AccessTokens() {
</button> </button>
{tokens.length > 0 ? ( {tokens.length > 0 ? (
<> <table className="table mt-2 overflow-x-auto">
<div className="divider my-0"></div>
<table className="table">
<thead> <thead>
<tr> <tr>
<th></th>
<th>{t("name")}</th> <th>{t("name")}</th>
<th>{t("created")}</th> <th>{t("created")}</th>
<th>{t("expires")}</th> <th>{t("expires")}</th>
@ -66,8 +62,18 @@ export default function AccessTokens() {
{tokens.map((token, i) => ( {tokens.map((token, i) => (
<React.Fragment key={i}> <React.Fragment key={i}>
<tr> <tr>
<th>{i + 1}</th> <td className={token.isSession ? "text-primary" : ""}>
<td>{token.name}</td> {token.isSession ? (
<div
className="tooltip tooltip-right text-left"
data-tip="This is a permanent session"
>
{token.name}
</div>
) : (
token.name
)}
</td>
<td> <td>
{new Date(token.createdAt || "").toLocaleDateString()} {new Date(token.createdAt || "").toLocaleDateString()}
</td> </td>
@ -87,7 +93,6 @@ export default function AccessTokens() {
))} ))}
</tbody> </tbody>
</table> </table>
</>
) : undefined} ) : undefined}
</div> </div>

View File

@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "AccessToken" ADD COLUMN "isSession" BOOLEAN NOT NULL DEFAULT false;

View File

@ -175,6 +175,7 @@ model AccessToken {
userId Int userId Int
token String @unique token String @unique
revoked Boolean @default(false) revoked Boolean @default(false)
isSession Boolean @default(false)
expires DateTime expires DateTime
lastUsedAt DateTime? lastUsedAt DateTime?
createdAt DateTime @default(now()) createdAt DateTime @default(now())

View File

@ -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.", "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", "new_token": "New Access Token",
"name": "Name", "name": "Name",
"created": "Created!", "created_success": "Created!",
"created": "Created",
"expires": "Expires", "expires": "Expires",
"accountSettings": "Account Settings", "accountSettings": "Account Settings",
"language": "Language", "language": "Language",