Skip to content

Instantly share code, notes, and snippets.

@robwormald
Last active December 30, 2015 10:18
Show Gist options
  • Save robwormald/7814484 to your computer and use it in GitHub Desktop.
Save robwormald/7814484 to your computer and use it in GitHub Desktop.
/**
* AuthController
*
* @module :: Controller
* @description :: Contains logic for handling auth requests.
*/
var passport = require('passport');
var GoogleStrategy = require('passport-google').Strategy;
module.exports = {
process: function(req,res){
//console.log(req)
passport.authenticate(
'local',{ successReturnToOrRedirect: '/', failureRedirect: '/login' })(req, res);
},
signin : function(req,res){
res.view('login')
},
googlelogin : function(req,res,next){
passport.authenticate(
'google',{ successReturnToOrRedirect: '/', failureRedirect: '/login' })(req, res,next);
},
googlecallback : function(req,res,next){
console.log('???')
passport.authenticate('google',{ successReturnToOrRedirect: '/', failureRedirect: '/login' })(req, res,next);
},
logout: function(req,res){
req.logout();
res.redirect('/');
},
connect : function(req,res){
console.log('authenticated websocket connection')
res.json({ping : 'pong'})
}
};
var passport = require('passport'),
BearerStrategy = require('passport-http-bearer').Strategy,
BasicStrategy = require('passport-http').BasicStrategy,
LocalStrategy = require('passport-local').Strategy,
ClientPasswordStrategy = require('passport-oauth2-client-password').Strategy,
GoogleOAuth2Strategy = require('passport-google-oauth').OAuth2Strategy;
var utils = require('../innitUtils.js');
var fs = require('fs');
var file = 'googleConfig.json';
var _googleConfig = JSON.parse(fs.readFileSync(file, 'utf8'))
var serverURL = process.env.URL || "http://localhost:1337"
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findOne({id:id}, function (err, user) {
// if(user.domainKey){}
done(err, user);
});
});
/**
* LocalStrategy
*
* This strategy is used to authenticate users based on a username and password.
* Anytime a request is made to authorize an application, we must ensure that
* a user is logged in before asking them to approve the request.
*/
passport.use(
new LocalStrategy(
function (username, password, done) {
process.nextTick(
function () {
User.findOne({
username: username
}).done(
function (err, user) {
if (err) {
console.log(err);
return;
}
if (!user) {
return done(
null, false, {
message: 'Unknown user ' + username
});
}
if (user.validPassword(password)) {
return done(
null, false, {
message: 'Invalid password'
});
}
return done(null, user);
})
});
}));
console.log()
passport.use(new GoogleOAuth2Strategy({
clientID: _googleConfig.web.client_id,
clientSecret: _googleConfig.web.client_secret,
callbackURL: process.env.HOST + "/auth/google/callback",
offline : true,
scope : ["openid","email","https://www.googleapis.com/auth/plus.me","https://www.googleapis.com/auth/admin.directory.user.readonly","https://www.googleapis.com/auth/admin.directory.orgunit.readonly","https://www.googleapis.com/auth/admin.directory.group.readonly","https://www.googleapis.com/auth/admin.directory.device.mobile.readonly","https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly"],
passReqToCallback : true
},
function(req,accessToken, refreshToken, profile, done) {
console.log(accessToken)
console.log(refreshToken)
console.log(profile)
User.findOne({identifier : profile.id},function(err,user){
if (err) {
return done(err);
}
if (!user) {
if(profile._json && profile._json.verified_email){
// console.log(profile._json)
User.create({
identifier : profile.id,
username : profile._json.email,
password : utils.uid(16),
email : profile._json.email,
domain_key : profile._json['hd'],
provider : 'google'
}).done(function(err,_user){
if(accessToken){
// Token.create({
// user : user.id,
// token : accessToken,
// refreshToken : refreshToken || null,
// provider : 'google'
// }).done(function(err,token){
// user.credentials.google = token
// return done(null,user)
// })
console.log(_user)
return done(null,_user)
}
else{
return done(null,_user)
}
})
}
}
else{
return done(null, user);
}
})
}
));
/**
* BasicStrategy & ClientPasswordStrategy
*
* These strategies are used to authenticate registered OAuth clients. They are
* employed to protect the `token` endpoint, which consumers use to obtain
* access tokens. The OAuth 2.0 specification suggests that clients use the
* HTTP Basic scheme to authenticate. Use of the client password strategy
* allows clients to send the same credentials in the request body (as opposed
* to the `Authorization` header). While this approach is not recommended by
* the specification, in practice it is quite common.
*/
passport.use(new BasicStrategy(
function (username, password, done) {
User.findOne({
email: username
}, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false);
}
if (!user.password != password) {
return done(null, false);
}
return done(null, user);
});
}));
passport.use(new ClientPasswordStrategy(
function (clientId, clientSecret, done) {
Client.findOne({
id: clientId
}, function (err, client) {
if (err) {
return done(err);
}
if (!client) {
return done(null, false);
}
if (client.clientSecret != clientSecret) {
return done(null, false);
}
return done(null, client);
});
}));
/**
* BearerStrategy
*
* This strategy is used to authenticate users based on an access token (aka a
* bearer token). The user must have previously authorized a client
* application, which is issued an access token to make requests on behalf of
* the authorizing user.
*/
passport.use(new BearerStrategy(
function(accessToken, done) {
Token.findOne({accessToken:accessToken}, function(err, token) {
if (err) { return done(err); }
if (!token) { return done(null, false); }
var info = {scope: '*'}
User.findOne({
id: token.user
}).done(
function (err, user) {
User.findOne({
id: token.user
},done(err,user,info));
});
});
}
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment