-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthcontroller.js
More file actions
106 lines (88 loc) · 2.65 KB
/
authcontroller.js
File metadata and controls
106 lines (88 loc) · 2.65 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
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import User from '../models/User.js';
import { createAndSendOTP, verifyOTP } from '../services/otp.service.js';
export const login = async (req, res) => {
try {
const { role, email, password } = req.body;
if (!role || !email || !password) {
return res.status(400).json({
success: false,
message: "Invalid Request",
});
}
const user = await User.findOne({
email: { $regex: new RegExp(`^${email}$`, 'i') },
role: { $regex: new RegExp(`^${role}$`, 'i') },
}).select('email role status password');
if (!user) {
return res.status(401).json({ success: false, message: 'Invalid role or email' });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(401).json({ success: false, message: 'Invalid password' });
}
// if (user.role.toLowerCase() === 'doctor' && user.status !== 'Active') {
// return res.status(403).json({ success: false, message: "Your account is currently inactive. Kindly reach out to the admin for support." });
// }
if (user.status !== 'Active') {
return res.status(403).json({ success: false, message: "Your account is currently inactive. Kindly reach out to the admin for support." });
}
const token = jwt.sign(
{ id: user._id, role: user.role, email: user.email },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
res.status(200).json({
success: true,
message: 'Login successful',
role: user.role,
token,
user: {
id: user._id,
email: user.email,
role: user.role,
status: user.status,
},
});
} catch (error) {
console.error('Login error:', error);
res.status(500).json({ success: false, message: 'Server error' });
}
};
export const sendOTP = async (req, res, next) => {
try {
const { email } = req.body;
if (!email) {
return res.status(400).json({
success: false,
message: 'Email is required'
});
}
await createAndSendOTP(email);
res.status(200).json({
success: true,
message: 'OTP sent successfully'
});
} catch (error) {
next(error);
}
};
export const validateOTP = async (req, res, next) => {
try {
const { email, otp } = req.body;
if (!email || !otp) {
return res.status(400).json({
success: false,
message: 'Email and OTP are required'
});
}
await verifyOTP(email, otp);
res.status(200).json({
success: true,
message: 'OTP verified successfully'
});
} catch (error) {
next(error);
}
};