Skip to content

Instantly share code, notes, and snippets.

@rebolyte
Created March 9, 2016 20:26
Show Gist options
  • Save rebolyte/88b30fd0effb7c518a6f to your computer and use it in GitHub Desktop.
Save rebolyte/88b30fd0effb7c518a6f to your computer and use it in GitHub Desktop.
Quick Express test
/* jshint esversion:6, node: true */
// https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens
// http://www.sitepoint.com/using-json-web-tokens-node-js/
'use strict';
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let morgan = require('morgan');
let jwt = require('jsonwebtoken');
let fs = require('fs');
let config = require('./config');
app.set('superSecret', config.secret);
// Populates `req.body` with the value of POST or URL parameters.
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
// You can also attach body parsers to specific routes (might be preferred):
// var jsonParser = bodyParser.json()
// app.post('/api/users', jsonParser, function (req, res) {
// if (!req.body) return res.sendStatus(400)
// })
// -- https://github.com/expressjs/body-parser#express-route-specific
// Logs output to the console
app.use(morgan('dev'));
// Get an instance of Express's Router
let apiRoutes = express.Router();
app.get('/', (req, res) => {
// res.send will set header, etc, as JSON with object literal passed in
res.send({ message: 'The API lives at this path + /api' });
});
apiRoutes.get('/', (req, res) => {
res.send({ message: 'Hello world' });
});
apiRoutes.post('/authenticate', (req, res) => {
if (!req.body.name) {
res.send({
success: false,
message: 'Authentication failed. Name not found.'
});
} else {
if (req.body.name !== 'rebolyte') {
res.send({
success: false,
message: 'Authentication failed. Incorrect username.'
});
}
if (req.body.password !== 'testing') {
res.send({
success: false,
message: 'Authentication failed. Incorrect password.'
});
}
if (req.body.name === 'rebolyte' && req.body.password === 'testing') {
let token = jwt.sign({
name: req.body.name,
}, app.get('superSecret'), {
expiresIn: '30s'
});
res.send({
success: true,
token: token
});
}
}
});
// register route middleware to verify a token on all routes listed below
apiRoutes.use((req, res, next) => {
let token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
jwt.verify(token, app.get('superSecret'), (err, decoded) => {
if (err) {
// TokenExpiredError / JsonWebTokenError
return res.json(err);
} else {
// If all is well, save to request for use in other routes
req.decoded = decoded;
next();
}
});
} else {
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
apiRoutes.get('/cameras', (req, res) => {
res.send({
success: true,
cameras: [100, 220, 45, 6]
});
});
apiRoutes.get('/image', (req, res) => {
fs.readFile('./poster.jpg', (err, data) => {
if (err) { console.error(err); }
// Otherwise sets header as 'application/octet-stream'
res.set('Content-Type', 'image/jpeg');
res.send(data);
});
});
// Attach routes above to the /api endpoint
app.use('/api', apiRoutes);
app.listen(config.port);
console.log(`Server running at http://localhost:${config.port}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment