-
Notifications
You must be signed in to change notification settings - Fork 7
/
auth.ts
68 lines (60 loc) · 1.72 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import jwt, { Secret } from 'jsonwebtoken';
import bcrypt from 'bcryptjs';
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
const JWT_SECRET = process.env.JWT_SECRET;
export async function verifyToken(token: string): Promise<number | null> {
try {
if (!JWT_SECRET) {
throw new Error('JWT_SECRET is not defined');
}
const decodedToken = jwt.verify(token, JWT_SECRET) as { userId: number };
const userId = decodedToken.userId;
return userId;
} catch (error) {
return null;
}
}
export async function authenticateUser(
email: string,
password: string
): Promise<string | null> {
const user = await prisma.portalUsers.findUnique({ where: { email } });
if (!user) {
return null;
}
if (!user.password) {
throw new Error('password is null');
}
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return null;
}
const token = await generateToken(user.id);
return token;
}
export async function generateToken(userId: number): Promise<string> {
if (!JWT_SECRET) {
throw new Error('JWT_SECRET is not defined');
}
const token = jwt.sign({ userId }, JWT_SECRET as Secret, {
expiresIn: '12h',
});
return token;
}
export async function validateToken(
authorization: string
): Promise<number | undefined> {
if (!authorization) {
throw new Error('Authorization token is missing.');
}
const contentArray = authorization.split(' ');
if (contentArray.length !== 2 || contentArray[0] !== 'Bearer') {
throw new Error('Authorization token extract error.');
}
const userId = await verifyToken(contentArray[1]);
if (!userId) {
throw new Error('Invalid token.');
}
return userId;
}