-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathauthcontroller.js
More file actions
213 lines (178 loc) · 5.96 KB
/
Copy pathauthcontroller.js
File metadata and controls
213 lines (178 loc) · 5.96 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import User from "../model/userModel.js";
import validator from "validator";
import bcrypt from "bcryptjs";
import { genToken, genToken1 } from "../config/Token.js";
import { sendMail, isEmailConfigured } from "../config/sendEmail.js";
import generateOTP from "../utils/otp.js";
import TempUser from "../model/tempUserModel.js";
import { otpTemplate } from "../utils/otpTemplet.js";
import { sendNotification } from "../services/notificationService.js";
export const sendOTP = async (req, res) => {
try {
const { name, email, password } = req.body;
if (!validator.isEmail(email)) {
return res.status(400).json({ message: "Invalid email address" });
}
if (password.length < 8) {
return res
.status(400)
.json({ message: "Password must be at least 8 characters long" });
}
const existUser = await User.findOne({ email });
if (existUser) {
return res.status(400).json({ message: "User already exists" });
}
await TempUser.findOneAndDelete({ email });
const otp = generateOTP();
const hashedPassword = await bcrypt.hash(password, 10);
// save temp user
await TempUser.create({
name,
email,
password: hashedPassword,
otp,
otpExpire: new Date(Date.now() + 5 * 60 * 1000),
});
if (!isEmailConfigured()) {
await TempUser.deleteOne({ email });
return res.status(503).json({
success: false,
message: "Email service is not configured",
});
}
try {
await sendMail(email, otpTemplate(otp));
} catch (_error) {
await TempUser.deleteOne({ email });
return res.status(500).json({
success: false,
message: "Failed to send OTP email",
});
}
return res.status(200).json({
success: true,
message: "OTP sent successfully",
});
} catch (_error) {
console.log("registration error:", _error);
return res.status(500).json({ message: `registration error: ${_error}` });
}
};
export const verifyOTP = async (req, res) => {
try {
const { email, otp } = req.body;
const tempUser = await TempUser.findOne({ email });
if (!tempUser) {
return res.status(400).json({ message: "User not found or OTP expired" });
}
if (tempUser.otp !== otp) {
return res.status(400).json({ message: "Invalid OTP" });
}
if (tempUser.otpExpire < new Date()) {
return res.status(400).json({ message: "OTP expired" });
}
const user = await User.create({
name: tempUser.name,
email: tempUser.email,
password: tempUser.password,
});
await TempUser.deleteOne({ email });
sendNotification({
isAdmin: true,
title: "New User Registered",
message: `${user.name} (${user.email}) has signed up.`,
type: "new_user",
});
const token = genToken(user._id);
res.cookie("token", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
maxAge: 7 * 24 * 60 * 60 * 1000,
});
return res.status(201).json({
success: true,
message: "User verified and created",
user,
});
} catch (_error) {
console.log("verifyOTP error:", _error);
return res.status(500).json({ message: "OTP verification failed" });
}
};
export const login = async (req, res) => {
try {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) return res.status(400).json({ message: "User not found" });
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return res.status(400).json({ message: "Invalid credentials" });
const token = genToken(user._id);
res.cookie("token", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
maxAge: 7 * 24 * 60 * 60 * 1000,
});
return res.status(200).json(user);
} catch (_error) {
console.log("login error:", _error);
return res.status(500).json({ message: `login error: ${_error}` });
}
};
export const googleLogin = async (req, res) => {
try {
const { name, email } = req.body;
let user = await User.findOne({ email });
if (!user) {
user = await User.create({ name, email });
}
const token = genToken(user._id);
res.cookie("token", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
maxAge: 7 * 24 * 60 * 60 * 1000,
});
return res.status(200).json(user);
} catch (_error) {
console.log("google login error:", _error);
return res.status(500).json({ message: `google login error: ${_error}` });
}
};
export const logOut = async (req, res) => {
try {
res.clearCookie("token", {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
maxAge: 0,
});
return res.status(200).json({ message: "Logged out successfully" });
} catch (_error) {
console.log("logout error:", _error);
return res.status(500).json({ message: `logout error: ${_error}` });
}
};
export const adminLogin = async (req, res) => {
try {
let { email, password } = req.body;
if (
email === process.env.ADMIN_EMAIL &&
password === process.env.ADMIN_PASSWORD
) {
const token = await genToken1(email);
res.cookie("adminToken", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
maxAge: 1 * 24 * 60 * 60 * 1000,
});
return res.status(200).json(token);
}
return res.status(400).json({ message: "Invalid admin credentials" });
} catch (_error) {
console.log("admin login error:", _error);
return res.status(500).json({ message: `admin login error: ${_error}` });
}
};