-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Expand file tree
/
Copy pathauthController.js
More file actions
226 lines (192 loc) · 5.86 KB
/
authController.js
File metadata and controls
226 lines (192 loc) · 5.86 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
214
215
216
217
218
219
220
221
222
223
224
225
226
const User = require('../models/User');
const Token = require('../models/Token');
const { StatusCodes } = require('http-status-codes');
const CustomError = require('../errors');
const {
attachCookiesToResponse,
createTokenUser,
sendVerificationEmail,
sendResetPasswordEmail,
createHash,
} = require('../utils');
const crypto = require('crypto');
const register = async (req, res) => {
const { email, name, password } = req.body;
const emailAlreadyExists = await User.findOne({ email });
if (emailAlreadyExists) {
throw new CustomError.BadRequestError('Email already exists');
}
// first registered user is an admin
const isFirstAccount = (await User.countDocuments({})) === 0;
const role = isFirstAccount ? 'admin' : 'user';
const verificationToken = crypto.randomBytes(40).toString('hex');
const user = await User.create({
name,
email,
password,
role,
verificationToken,
});
const origin = 'http://localhost:3000';
// const newOrigin = 'https://react-node-user-workflow-front-end.netlify.app';
// const tempOrigin = req.get('origin');
// const protocol = req.protocol;
// const host = req.get('host');
// const forwardedHost = req.get('x-forwarded-host');
// const forwardedProtocol = req.get('x-forwarded-proto');
await sendVerificationEmail({
name: user.name,
email: user.email,
verificationToken: user.verificationToken,
origin,
});
// send verification token back only while testing in postman!!!
res.status(StatusCodes.CREATED).json({
msg: 'Success! Please check your email to verify account',
});
};
const verifyEmail = async (req, res) => {
const { verificationToken, email } = req.body;
const user = await User.findOne({ email });
if (!user) {
throw new CustomError.UnauthenticatedError('Verification Failed');
}
if (user.verificationToken !== verificationToken) {
throw new CustomError.UnauthenticatedError('Verification Failed');
}
(user.isVerified = true), (user.verified = Date.now());
user.verificationToken = '';
await user.save();
res.status(StatusCodes.OK).json({ msg: 'Email Verified' });
};
const login = async (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
throw new CustomError.BadRequestError('Please provide email and password');
}
const user = await User.findOne({ email });
if (!user) {
throw new CustomError.UnauthenticatedError('Invalid Credentials');
}
const isPasswordCorrect = await user.comparePassword(password);
if (!isPasswordCorrect) {
throw new CustomError.UnauthenticatedError('Invalid Credentials');
}
if (!user.isVerified) {
throw new CustomError.UnauthenticatedError('Please verify your email');
}
const tokenUser = createTokenUser(user);
// create refresh token
let refreshToken = '';
// check for existing token
const existingToken = await Token.findOne({
user: user._id,
userAgent: req.headers['user-agent'], // add userAgent so, different devices will get different token
});
if (existingToken) {
const { isValid } = existingToken;
if (!isValid) {
throw new CustomError.UnauthenticatedError('Invalid Credentials');
}
//since this is login, expired or not dosen't matter, so just renew the exiredIn
existingToken.expiredIn = Date.now() + 1000 * 60 * 60 * 24 * 30; //30days
//also update the refreshToken for safe
existingToken.refreshToken = crypto.randomBytes(40).toString('hex');
const token = await existingToken.save();
refreshToken = token.refreshToken;
await attachCookiesToResponse({
res,
user: tokenUser,
refreshToken,
expiresIn: token.expiredIn,
});
return res.status(StatusCodes.OK).json({ user: tokenUser });
}
refreshToken = crypto.randomBytes(40).toString('hex');
const userAgent = req.headers['user-agent'];
const ip = req.ip;
const userToken = {
refreshToken,
ip,
userAgent,
user: user._id,
expiredIn: Date.now() + 1000 * 60 * 60 * 24 * 30,
};
const token = await Token.create(userToken);
await attachCookiesToResponse({
res,
user: tokenUser,
refreshToken,
expiresIn: token.expiredIn,
});
res.status(StatusCodes.OK).json({ user: tokenUser });
};
const logout = async (req, res) => {
await Token.findOneAndDelete({
user: req.user.userId,
userAgent: req.headers['user-agent'],
});
res.cookie('accessToken', 'logout', {
httpOnly: true,
expires: new Date(Date.now()),
});
res.cookie('refreshToken', 'logout', {
httpOnly: true,
expires: new Date(Date.now()),
});
res.status(StatusCodes.OK).json({ msg: 'user logged out!' });
};
const forgotPassword = async (req, res) => {
const { email } = req.body;
if (!email) {
throw new CustomError.BadRequestError('Please provide valid email');
}
const user = await User.findOne({ email });
if (user) {
const passwordToken = crypto.randomBytes(70).toString('hex');
// send email
const origin = 'http://localhost:3000';
await sendResetPasswordEmail({
name: user.name,
email: user.email,
token: passwordToken,
origin,
});
const tenMinutes = 1000 * 60 * 10;
const passwordTokenExpirationDate = new Date(Date.now() + tenMinutes);
user.passwordToken = createHash(passwordToken);
user.passwordTokenExpirationDate = passwordTokenExpirationDate;
await user.save();
}
res
.status(StatusCodes.OK)
.json({ msg: 'Please check your email for reset password link' });
};
const resetPassword = async (req, res) => {
const { token, email, password } = req.body;
if (!token || !email || !password) {
throw new CustomError.BadRequestError('Please provide all values');
}
const user = await User.findOne({ email });
if (user) {
const currentDate = new Date();
if (
user.passwordToken === createHash(token) &&
user.passwordTokenExpirationDate > currentDate
) {
user.password = password;
user.passwordToken = null;
user.passwordTokenExpirationDate = null;
await user.save();
}
}
res.send('reset password');
};
module.exports = {
register,
login,
logout,
verifyEmail,
forgotPassword,
resetPassword,
};