Skip to content

Commit

Permalink
feat(auth): refactoring local user authentication strategy
Browse files Browse the repository at this point in the history
* removed any redirects related to the client frontend pages
* refactored auth strategy to use services and repositories
  and removing all of that logic from mongoose
  • Loading branch information
lirantal committed Sep 8, 2017
1 parent 852b130 commit 0689d0c
Show file tree
Hide file tree
Showing 9 changed files with 347 additions and 201 deletions.
41 changes: 17 additions & 24 deletions server/modules/users/server/config/strategies/local.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,27 @@
/**
* Module dependencies
*/
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
User = require('mongoose').model('User');
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
// const User = require('mongoose').model('User')
const UserService = require('../../services/user.service')

module.exports = function () {
// Use local strategy
passport.use(new LocalStrategy({
usernameField: 'usernameOrEmail',
passwordField: 'password'
},
function (usernameOrEmail, password, done) {
User.findOne({
$or: [{
username: usernameOrEmail.toLowerCase()
}, {
email: usernameOrEmail.toLowerCase()
}]
}, function (err, user) {
if (err) {
return done(err);
}
if (!user || !user.authenticate(password)) {
}, async (email, password, done) => {
try {
const user = await UserService.authenticate(email, password)
if (user) {
return done(null, user)
} else {
return done(null, false, {
message: 'Invalid username or password (' + (new Date()).toLocaleTimeString() + ')'
});
message: 'Invalid username or password'
})
}

return done(null, user);
});
}));
};
} catch (err) {
return done(err)
}
}))
}
50 changes: 28 additions & 22 deletions server/modules/users/server/config/users.server.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,35 +3,41 @@
/**
* Module dependencies
*/
var passport = require('passport'),
User = require('mongoose').model('User'),
path = require('path'),
config = require(path.resolve('./lib/config'));
const path = require('path')
const config = require(path.resolve('./lib/config'))
const passport = require('passport')
// const User = require('mongoose').model('User')

const UserService = require('../services/user.service')

/**
* Module init function
*/
module.exports = function (app, db) {
// Serialize sessions
passport.serializeUser(function (user, done) {
done(null, user.id);
});
module.exports = function (app) {
// Serialize identifiable user's information to the session
// so that it can be pulled back in another request
passport.serializeUser((user, done) => {
done(null, user.id)
})

// Deserialize sessions
passport.deserializeUser(function (id, done) {
User.findOne({
_id: id
}, '-salt -password', function (err, user) {
done(err, user);
});
});
// Deserialize get the user identifying information that we saved
// in `passport.serializeUser()` and resolves the user account
// from it so it can be saved in `req.user`
passport.deserializeUser(async (id, done) => {
try {
const user = await UserService.getUserDeserializedById(id)
return done(null, user)
} catch (err) {
return done(err, null)
}
})

// Initialize strategies
config.utils.getGlobbedPaths(path.join(__dirname, './strategies/**/*.js')).forEach(function (strategy) {
require(path.resolve(strategy))(config);
});
config.utils.getGlobbedPaths(path.join(__dirname, './strategies/**/*.js')).forEach((strategy) => {
require(path.resolve(strategy))(config)
})

// Add passport's middleware
app.use(passport.initialize());
app.use(passport.session());
app.use(passport.initialize())
app.use(passport.session())
};
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
/**
* Module dependencies
*/
var path = require('path'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
mongoose = require('mongoose'),
passport = require('passport'),
User = mongoose.model('User');
const path = require('path')
const errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'))
const mongoose = require('mongoose')
const passport = require('passport')
const User = mongoose.model('User')

const UserService = require('../../services/user.service')

// URLs for which user can't be redirected on signin
var noReturnUrls = [
Expand All @@ -18,70 +20,29 @@ var noReturnUrls = [
/**
* Signup
*/
exports.signup = function (req, res) {
// For security measurement we remove the roles from the req.body object
delete req.body.roles;

// Init user and add missing fields
var user = new User(req.body);
user.provider = 'local';
user.displayName = user.firstName + ' ' + user.lastName;

// Then save the user
user.save(function (err) {
if (err) {
return res.status(422).send({
message: errorHandler.getErrorMessage(err)
});
} else {
// Remove sensitive data before login
user.password = undefined;
user.salt = undefined;

req.login(user, function (err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
});
};
exports.signup = async function (req, res) {
try {
const user = await UserService.signUp(req.body)
return res.json(user)
} catch (err) {
return res.status(500).send(err.message)
}
}

/**
* Signin after passport authentication
*/
exports.signin = function (req, res, next) {
passport.authenticate('local', function (err, user, info) {
if (err || !user) {
console.log(err);
console.log(user);
console.log(info);
res.status(422).send(info);
} else {
// Remove sensitive data before login
user.password = undefined;
user.salt = undefined;

req.login(user, function (err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
})(req, res, next);
};
exports.signin = async function (req, res) {
return res.json(req.user)
}

/**
* Signout
*/
exports.signout = function (req, res) {
req.logout();
res.redirect('/');
};
req.logout()
return res.status(200).send()
}

/**
* OAuth provider call
Expand Down
Loading

0 comments on commit 0689d0c

Please sign in to comment.