subman-nextjs/src/app/api/auth/actions.ts

137 lines
2.3 KiB
TypeScript
Raw Normal View History

2024-09-13 10:21:45 +00:00
import prisma from 'app/lib/db';
import { jwtVerify, JWTPayload, decodeJwt } from 'jose';
import { cookies } from 'next/headers';
2024-09-13 10:21:45 +00:00
export function getJWTSecretKey() {
const secret = process.env.JWT_SECRET
if (!secret) throw new Error("There is no JWT secret key")
return new TextEncoder().encode(secret)
}
export async function verifyJwt(token: string): Promise<JWTPayload | null> {
try {
//the curly braces here are used because you can't access the result of an await using dot notation
const { payload } = await jwtVerify(token, getJWTSecretKey)
return payload
} catch {
return null
}
}
export async function getJwt() {
const cookieStore = cookies()
const token = cookieStore.get("token")
if (token) {
try {
const payload = await verifyJwt(token.value)
if (payload) {
const authPayload = {
email: payload.email as string,
iat: payload.iat as number,
exp: payload.exp as number
}
return authPayload
}
} catch (error) {
return null
}
}
return null
}
export async function logout() {
const cookieStore = cookies()
const token = cookieStore.get('token')
if (token) {
//empty catch swallows errors
try {
cookieStore.delete('token')
} catch { }
}
const userData = cookieStore.get("userData")
if (userData) {
try {
cookieStore.delete('userData')
return true
} catch (_) { }
}
//return false if there is no userdata
return null
}
export function setUserDataCookie(userData) {
const cookieStore = cookies();
cookieStore.set({
name: 'userData',
value: JSON.stringify(userData),
path: '/',
maxAge: 3600,
sameSite: 'strict'
})
}
export type UserLogin = {
email: string,
password: string
}
export async function login(userLogin: UserLogin) {
try {
const user = await prisma.user.findFirst({ where: { email: userLogin.email } })
if (!user) { throw new Error('user does not exist') }
const bcrypt = require("bcrypt");
2024-09-13 10:21:45 +00:00
const passwordIsValid = await bcrypt.compare(userLogin.password, user.password)
if (!passwordIsValid) throw new Error('invalid password')
//return the user object without the hashed password
return { email: user.email, id: user.id }
} catch (error) {
console.error(error)
throw new Error('invalid login or password')
}
}
export async function jwtExpires() {
}