Merge pull request #626 from linkwarden/feat/add-session-route
added the route
This commit is contained in:
commit
6003c6c449
|
@ -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();
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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,
|
||||
};
|
||||
}
|
|
@ -9,6 +9,7 @@ export default async function getToken(userId: number) {
|
|||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
isSession: true,
|
||||
expires: true,
|
||||
createdAt: true,
|
||||
},
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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 });
|
||||
}
|
||||
}
|
|
@ -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>
|
||||
|
||||
|
|
|
@ -0,0 +1,2 @@
|
|||
-- AlterTable
|
||||
ALTER TABLE "AccessToken" ADD COLUMN "isSession" BOOLEAN NOT NULL DEFAULT false;
|
|
@ -175,6 +175,7 @@ model AccessToken {
|
|||
userId Int
|
||||
token String @unique
|
||||
revoked Boolean @default(false)
|
||||
isSession Boolean @default(false)
|
||||
expires DateTime
|
||||
lastUsedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
|
|
|
@ -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",
|
||||
|
|
Ŝarĝante…
Reference in New Issue