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

Adapted to work with the most recent module versions #161

Open
wants to merge 1 commit 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
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
node_modules
.vscode/*
config/.env
2 changes: 0 additions & 2 deletions config/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ const connectDB = async () => {
const conn = await mongoose.connect(process.env.DB_STRING, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
})

console.log(`MongoDB Connected: ${conn.connection.host}`)
Expand Down
52 changes: 32 additions & 20 deletions config/passport.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,43 @@ const mongoose = require('mongoose')
const User = require('../models/User')

module.exports = function (passport) {
passport.use(new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
User.findOne({ email: email.toLowerCase() }, (err, user) => {
if (err) { return done(err) }
if (!user) {
return done(null, false, { msg: `Email ${email} not found.` })
}
if (!user.password) {
return done(null, false, { msg: 'Your account was registered using a sign-in provider. To enable password login, sign in using a provider, and then set a password under your user profile.' })
}
user.comparePassword(password, (err, isMatch) => {
if (err) { return done(err) }
if (isMatch) {
return done(null, user)
passport.use(
new LocalStrategy({ usernameField: 'email' }, async (email, password, done) => {
try {
const user = await User.findOne({ email: email.toLowerCase() }).exec();

if (!user) {
return done(null, false, { msg: `Email ${email} not found.` });
}
if (!user.password) {
return done(null, false, {
msg: 'Your account was registered using a sign-in provider. To enable password login, sign in using a provider, and then set a password under your user profile.',
});
}
return done(null, false, { msg: 'Invalid email or password.' })
})

user.comparePassword(password, (err, isMatch) => {
if (err) { return done(err) }
if (isMatch) {
return done(null, user)
}
return done(null, false, { msg: 'Invalid email or password.' })
})
} catch (err) {
return done(err);
}
})
}))

)

passport.serializeUser((user, done) => {
done(null, user.id)
})

passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => done(err, user))
})
passport.deserializeUser(async (id, done) => {
try {
const user = await User.findById(id).exec();
done(null, user);
} catch (err) {
done(err, null);
}
});
}
100 changes: 58 additions & 42 deletions controllers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,18 @@ const User = require('../models/User')
}

exports.logout = (req, res) => {
req.logout(() => {
console.log('User has logged out.')
})
req.session.destroy((err) => {
if (err) console.log('Error : Failed to destroy the session during logout.', err)
req.user = null
res.redirect('/')
})
}
req.logout(function (err) {
if (err) {
return next(err);
}
req.session.destroy((err) => {
if (err) console.log("Error : Failed to destroy the session during logout.", err);
req.user = null;
res.redirect("/");
});
});
};


exports.getSignup = (req, res) => {
if (req.user) {
Expand All @@ -56,41 +59,54 @@ const User = require('../models/User')
})
}

exports.postSignup = (req, res, next) => {
const validationErrors = []
if (!validator.isEmail(req.body.email)) validationErrors.push({ msg: 'Please enter a valid email address.' })
if (!validator.isLength(req.body.password, { min: 8 })) validationErrors.push({ msg: 'Password must be at least 8 characters long' })
if (req.body.password !== req.body.confirmPassword) validationErrors.push({ msg: 'Passwords do not match' })
exports.postSignup = async (req, res, next) => {
try {
const validationErrors = [];
if (!validator.isEmail(req.body.email))
validationErrors.push({ msg: 'Please enter a valid email address.' });
if (!validator.isLength(req.body.password, { min: 8 }))
validationErrors.push({ msg: 'Password must be at least 8 characters long' });
if (req.body.password !== req.body.confirmPassword)
validationErrors.push({ msg: 'Passwords do not match' });

if (validationErrors.length) {
req.flash('errors', validationErrors)
return res.redirect('../signup')
}
req.body.email = validator.normalizeEmail(req.body.email, { gmail_remove_dots: false })
if (validationErrors.length) {
req.flash('errors', validationErrors);
return res.redirect('../signup');
}
req.body.email = validator.normalizeEmail(req.body.email, {
gmail_remove_dots: false,
});

const user = new User({
userName: req.body.userName,
email: req.body.email,
password: req.body.password
})
const existingUser = await User.findOne({
$or: [
{ email: req.body.email },
{ userName: req.body.userName },
],
}).exec();

User.findOne({$or: [
{email: req.body.email},
{userName: req.body.userName}
]}, (err, existingUser) => {
if (err) { return next(err) }
if (existingUser) {
req.flash('errors', { msg: 'Account with that email address or username already exists.' })
return res.redirect('../signup')
req.flash('errors', {
msg: 'Account with that email address or username already exists.',
});
return res.redirect('../signup');
}
user.save((err) => {
if (err) { return next(err) }
req.logIn(user, (err) => {
if (err) {
return next(err)
}
res.redirect('/todos')
})
})
})
}

const user = new User({
userName: req.body.userName,
email: req.body.email,
password: req.body.password,
});

await user.save();

req.logIn(user, (err) => {
if (err) {
return next(err);
}
res.redirect('/todos');
});
} catch (err) {
return next(err);
}
};

Loading