Skip to content

Instantly share code, notes, and snippets.

@allenhwkim
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allenhwkim/911e6dd6dbc1da197918 to your computer and use it in GitHub Desktop.
Save allenhwkim/911e6dd6dbc1da197918 to your computer and use it in GitHub Desktop.
Server-side angularjs-auth implementation
/***********************
* authentications.js
************************/
var jwt = require('jwt-simple');
var crypto = require('crypto');
var secret = process.env.TOKEN_SECRET || 'shhhhhhhhhh';
var authHeaderName = "x-access-token";
var md5Username = '21232f297a57a5a743894a0e4a801fc3';
var md5Password = '9d51b3f14e6d6763bd11fd73cf470bf2';
var md5 = function(str) {
return crypto.createHash('md5').update(str).digest('hex');
}
exports.login = function(req, res) {
var username = req.params.username || req.query.username || '';
var password = req.params.password || req.query.password || '';
if (md5(username) == md5Username && md5(password) == md5Password) {
var token = jwt.encode({
user: username,
roles: ['admin']
}, secret);
res.set(authHeaderName, token);
res.send(200, {
token: token,
username: username ,
roles: ['admin']
});
return;
} else {
res.send(401, {err: 'invalid user or password'});
return;
}
};
exports.hasRole = function(role) {
return function(req, res, next) {
var token = (req.body && req.body.access_token) ||
(req.query && req.access_token) ||
(req.headers[authHeaderName]);
if (token) {
try {
var decoded = jwt.decode(token, secret);
if (decoded.roles && decoded.roles.indexOf(role)) {
next();
}
} catch(err) {
res.send(401, {err: 'Invalid authorization token'});
}
} else {
res.send(401, {err: 'Invalid authorization token'});
}
};
};
/***********************
* server.js
************************/
var app = express();
/**
* Server Routes and Handlers -- Authetication
*/
var auths = require("authentications.js");
app.get('/login', auths.login);
/**
* Server Routes and Handlers -- Articles
*/
var articles = require("./routes/api/articles");
app.get('/public', function(req, res) {
res.send('hello world');
});
app.post('/admin', auths.hasRole('admin'), function(req,res) {
res.send('hello admin');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment