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
@@ -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,
};
}
+1
View File
@@ -9,6 +9,7 @@ export default async function getToken(userId: number) {
select: {
id: true,
name: true,
isSession: true,
expires: true,
createdAt: true,
},
+63
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;
}
}