Skip to content

Instantly share code, notes, and snippets.

@francisngo
Created December 29, 2017 03:58
Show Gist options
  • Save francisngo/4881788d682e7c71042bb0663df858aa to your computer and use it in GitHub Desktop.
Save francisngo/4881788d682e7c71042bb0663df858aa to your computer and use it in GitHub Desktop.
Authenticate a Node.js API with JSON Web Tokens
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const morgan = require('morgan');
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const config = require('./config');
const User = require('./app/models/user');
const PORT = process.env.PORT || 1337;
const routes = express.Router();
mongoose.connect(config.database);
app.set('secret', config.secret);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(morgan('dev'));
routes.post('/authenticate', function(req, res) {
User.findOne({
name: req.body.name
}, function(err, user) {
if (err) throw err;
if (!user) {
res.json({ success: false, message: 'Authentication failed. User not found.' });
} else if (user) {
if (user.password != req.body.password) {
res.json({ success: false, message: 'Authentication failed. Wrong password.' });
} else {
const payload = {
admin: user.admin
};
let token = jwt.sign(payload, app.get('secret'), {
expiresInMinutes: 1440 // 24 hours
});
res.json({
success: true,
message: 'Authentication granted.',
token: token
});
}
}
});
});
routes.use(function(req, res, next) {
let token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
jwt.verify(token, app.get('secret'), function(err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
routes.get('/', function(req, res) {
res.json({ message: 'This is the API default home route.' });
})
routes.get('/users', function(req, res) {
User.find({}, function(err, users) {
res.json(users);
});
});
app.use('/api', routes);
app.get('/', function(req, res) {
res.send(`Hello! This is the default homepage.`);
});
app.listen(PORT);
console.log(`Listening on port: ${PORT}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment