-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthController.js
More file actions
89 lines (75 loc) · 2.31 KB
/
Copy pathauthController.js
File metadata and controls
89 lines (75 loc) · 2.31 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
// controllers/authController.js
// Handles user registration, login, and fetching the current user's profile.
const asyncHandler = require('express-async-handler');
const User = require('../models/User');
const generateToken = require('../utils/generateToken');
// @desc Register a new user
// @route POST /api/auth/register
// @access Public
const registerUser = asyncHandler(async (req, res) => {
const { name, email, password, role } = req.body;
if (!name || !email || !password) {
res.status(400);
throw new Error('Please provide name, email and password');
}
const userExists = await User.findOne({ email });
if (userExists) {
res.status(400);
throw new Error('A user with this email already exists');
}
// Only allow 'customer' role on public signup; agent/admin accounts should be
// created by an existing admin via a protected endpoint in a real deployment.
const user = await User.create({
name,
email,
password,
role: role === 'agent' ? 'agent' : 'customer',
});
res.status(201).json({
success: true,
data: {
_id: user._id,
name: user.name,
email: user.email,
role: user.role,
token: generateToken(user._id),
},
});
});
// @desc Authenticate user & get token
// @route POST /api/auth/login
// @access Public
const loginUser = asyncHandler(async (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
res.status(400);
throw new Error('Please provide email and password');
}
// Explicitly select password since schema excludes it by default
const user = await User.findOne({ email }).select('+password');
if (!user || !(await user.matchPassword(password))) {
res.status(401);
throw new Error('Invalid email or password');
}
if (!user.isActive) {
res.status(403);
throw new Error('This account has been deactivated');
}
res.json({
success: true,
data: {
_id: user._id,
name: user.name,
email: user.email,
role: user.role,
token: generateToken(user._id),
},
});
});
// @desc Get currently logged-in user's profile
// @route GET /api/auth/me
// @access Private
const getMe = asyncHandler(async (req, res) => {
res.json({ success: true, data: req.user });
});
module.exports = { registerUser, loginUser, getMe };