Skip to content

Instantly share code, notes, and snippets.

@kconde2
Forked from vunb/AuthController.js
Created December 15, 2019 02:30
Show Gist options
  • Save kconde2/854ec38b97a750bf5d6423b8b31ef25a to your computer and use it in GitHub Desktop.
Save kconde2/854ec38b97a750bf5d6423b8b31ef25a to your computer and use it in GitHub Desktop.
/**
* AuthController
*
* @description :: Server-side logic for managing auths
* @help :: See http://links.sailsjs.org/docs/controllers
*/
module.exports = {
index: function (req, res) {
var email = req.param('email');
var password = req.param('password');
if (!email || !password) {
return res.json(401, {err: 'email and password required'});
}
Users.findOne({email: email}, function (err, user) {
if (!user) {
return res.json(401, {err: 'invalid email or password'});
}
Users.comparePassword(password, user, function (err, valid) {
if (err) {
return res.json(403, {err: 'forbidden'});
}
if (!valid) {
return res.json(401, {err: 'invalid email or password'});
} else {
res.json({
user: user,
token: jwToken.issue({id : user.id })
});
}
});
})
}
};
/**
* isAuthorized
*
* @description :: Policy to check if user is authorized with JSON web token
* @help :: See http://sailsjs.org/#!/documentation/concepts/Policies
*/
module.exports = function (req, res, next) {
var token;
if (req.headers && req.headers.authorization) {
var parts = req.headers.authorization.split(' ');
if (parts.length == 2) {
var scheme = parts[0],
credentials = parts[1];
if (/^Bearer$/i.test(scheme)) {
token = credentials;
}
} else {
return res.json(401, {err: 'Format is Authorization: Bearer [token]'});
}
} else if (req.param('token')) {
token = req.param('token');
// We delete the token from param to not mess with blueprints
delete req.query.token;
} else {
return res.json(401, {err: 'No Authorization header was found'});
}
jwToken.verify(token, function (err, token) {
if (err) return res.json(401, {err: 'Invalid Token!'});
req.token = token; // This is the decrypted token or the payload you provided
next();
});
};
/**
* jwToken
*
* @description :: JSON Webtoken Service for sails
* @help :: See https://github.com/auth0/node-jsonwebtoken & http://sailsjs.org/#!/documentation/concepts/Services
*/
var
jwt = require('jsonwebtoken'),
tokenSecret = "secretissecet";
// Generates a token from supplied payload
module.exports.issue = function(payload) {
return jwt.sign(
payload,
tokenSecret, // Token Secret that we sign it with
{
expiresInMinutes : 180 // Token Expire time
}
);
};
// Verifies token on a request
module.exports.verify = function(token, callback) {
return jwt.verify(
token, // The token to be verified
tokenSecret, // Same token we used to sign
{}, // No Option, for more see https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback
callback //Pass errors or decoded token to callback
);
};
/*
* For more information on how policies work, see:
* http://sailsjs.org/#/documentation/concepts/Policies
*
* For more information on configuring policies, check out:
* http://sailsjs.org/#/documentation/reference/sails.config/sails.config.policies.html
*/
module.exports.policies = {
'*': ['isAuthorized'], // Everything resctricted here
'UsersController': {
'create': true // We dont need authorization here, allowing public access
},
'AuthController': {
'*': true // We dont need authorization here, allowing public access
}
};
/**
* Users.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
// We don't want to store password with out encryption
var bcrypt = require('bcrypt');
module.exports = {
schema: true,
attributes: {
email: {
type: 'email',
required: 'true',
unique: true // Yes unique one
},
encryptedPassword: {
type: 'string'
},
// We don't wan't to send back encrypted password either
toJSON: function () {
var obj = this.toObject();
delete obj.encryptedPassword;
return obj;
}
},
// Here we encrypt password before creating a User
beforeCreate : function (values, next) {
bcrypt.genSalt(10, function (err, salt) {
if(err) return next(err);
bcrypt.hash(values.password, salt, function (err, hash) {
if(err) return next(err);
values.encryptedPassword = hash;
next();
})
})
},
comparePassword : function (password, user, cb) {
bcrypt.compare(password, user.encryptedPassword, function (err, match) {
if(err) cb(err);
if(match) {
cb(null, true);
} else {
cb(err);
}
})
}
};
/**
* UsersController
*
* @description :: Server-side logic for managing users
* @help :: See http://links.sailsjs.org/docs/controllers
*/
module.exports = {
create: function (req, res) {
if (req.body.password !== req.body.confirmPassword) {
return res.json(401, {err: 'Password doesn\'t match, What a shame!'});
}
Users.create(req.body).exec(function (err, user) {
if (err) {
return res.json(err.status, {err: err});
}
// If user created successfuly we return user and token as response
if (user) {
// NOTE: payload is { id: user.id}
res.json(200, {user: user, token: jwToken.issue({id: user.id})});
}
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment