Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix the refreshToken never expire bug #82

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
364 changes: 195 additions & 169 deletions 11-auth-workflow/final/server/controllers/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,198 +3,224 @@ const Token = require('../models/Token');
const { StatusCodes } = require('http-status-codes');
const CustomError = require('../errors');
const {
attachCookiesToResponse,
createTokenUser,
sendVerificationEmail,
sendResetPasswordEmail,
createHash,
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 { 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 });
const { verificationToken, email } = req.body;
const user = await User.findOne({ email });

if (!user) {
throw new CustomError.UnauthenticatedError('Verification Failed');
}
if (!user) {
throw new CustomError.UnauthenticatedError('Verification Failed');
}

if (user.verificationToken !== verificationToken) {
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 = '';
(user.isVerified = true), (user.verified = Date.now());
user.verificationToken = '';

await user.save();
await user.save();

res.status(StatusCodes.OK).json({ msg: 'Email Verified' });
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 });

if (existingToken) {
const { isValid } = existingToken;
if (!isValid) {
throw new CustomError.UnauthenticatedError('Invalid Credentials');
}
refreshToken = existingToken.refreshToken;
attachCookiesToResponse({ res, user: tokenUser, refreshToken });
res.status(StatusCodes.OK).json({ user: tokenUser });
return;
}

refreshToken = crypto.randomBytes(40).toString('hex');
const userAgent = req.headers['user-agent'];
const ip = req.ip;
const userToken = { refreshToken, ip, userAgent, user: user._id };

await Token.create(userToken);

attachCookiesToResponse({ res, user: tokenUser, refreshToken });

res.status(StatusCodes.OK).json({ user: tokenUser });
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 });

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!' });
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 { 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');
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,
register,
login,
logout,
verifyEmail,
forgotPassword,
resetPassword,
};
Loading