-
Notifications
You must be signed in to change notification settings - Fork 217
Expand file tree
/
Copy pathauth.ts
More file actions
96 lines (85 loc) · 2.39 KB
/
auth.ts
File metadata and controls
96 lines (85 loc) · 2.39 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import jwt from "jsonwebtoken";
import prismaModule from "../prisma.js";
import { SUBSCRIPTION_STATUS } from "../constants/subscription.js";
const { prisma } = prismaModule;
const JWT_SECRET = process.env.JWT_SECRET! as string;
if (!process.env.JWT_SECRET) {
throw new Error("JWT_SECRET is not defined in the environment variables");
}
export interface UserWithSubscription {
id: string;
email: string;
firstName: string;
authMethod: string;
createdAt: Date;
lastLogin: Date;
completedSteps: any;
isPaidUser: boolean;
subscription: {
id: string;
status: string;
startDate: Date;
endDate: Date | null;
planId: string;
} | null;
}
export const generateToken = (email: string): string => {
return jwt.sign({ email }, JWT_SECRET, { expiresIn: "7d" });
};
export const verifyToken = async (token: string): Promise<UserWithSubscription> => {
try {
const decoded = jwt.verify(token, JWT_SECRET);
if (typeof decoded === "string" || !decoded || typeof decoded !== "object") {
throw new Error("Invalid token payload");
}
const email = (decoded as { email?: string }).email;
if (!email) {
throw new Error("Email not found in token");
}
const user = await prisma.user.findUnique({
where: { email },
include: {
subscriptions: {
where: {
status: SUBSCRIPTION_STATUS.ACTIVE,
endDate: {
gte: new Date(),
},
},
orderBy: {
startDate: "desc",
},
take: 1,
include: {
plan: true,
},
},
},
});
if (!user) {
throw new Error("User not found");
}
const activeSubscription = user.subscriptions[0] || null;
return {
id: user.id,
email: user.email,
firstName: user.firstName,
authMethod: user.authMethod,
createdAt: user.createdAt,
lastLogin: user.lastLogin,
completedSteps: user.completedSteps,
isPaidUser: !!activeSubscription,
subscription: activeSubscription
? {
id: activeSubscription.id,
status: activeSubscription.status,
startDate: activeSubscription.startDate,
endDate: activeSubscription.endDate,
planId: activeSubscription.planId,
}
: null,
};
} catch (error) {
throw new Error("Token verification failed");
}
};