-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
auth.ts
40 lines (32 loc) · 1.27 KB
/
auth.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { env } from '$env/dynamic/private';
import { hashPassword } from '$lib/crypto';
import prisma from '@db';
import type { Cookies } from '@sveltejs/kit';
export const getUserIdFromCookie = async (cookies: Cookies) => {
const token = cookies.get('token');
if (!token) return null;
const authToken = await prisma.authToken.findFirst({
where: { token, expiresAt: { gt: new Date() } },
include: { user: { select: { id: true, verified: true } } }
});
if (!authToken) return null;
if (!authToken.user.verified) return null;
return authToken.user.id;
};
export const generateVerificationHash = async (userId: string) => {
const user = await prisma.user.findUnique({ where: { id: userId } });
if (!user) throw new Error('User not found');
const hash = await hashPassword(`${user.email}${user.id}${user.password}${user.verified}`, env.SALT);
return hash;
};
export const validateVerificationHash = async (userId: string, hash: string) => {
const user = await prisma.user.findUnique({ where: { id: userId } });
if (!user) return false;
const newHash = await hashPassword(
`${user.email}${user.id}${user.password}${user.verified}`,
env.SALT
);
if (newHash !== hash) return false;
await prisma.user.update({ where: { id: userId }, data: { verified: true } });
return true;
};