Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(auth): handle when token is expired #14

Merged
merged 1 commit into from
Oct 7, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/middlewares/authenticate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const {AUTH_CLIENT_SECRET} = process.env;
const jwt = require('jsonwebtoken');

const authenticate = () => (req, res, next) => {
const {split} = require('lodash');
const header = req.get('Authorization');
if (!header) {
return res.sendStatus(401);
}
const token = split(header, /\s+/).pop();
if (!token) {
return res.sendStatus(401);
}
try {
req.user = jwt.verify(token, AUTH_CLIENT_SECRET);
next();
} catch (err) {
if (err instanceof jwt.TokenExpiredError) {
res.status(401).send({tokenExpired: true});
return;
}
if (err instanceof jwt.JsonWebTokenError) {
res.status(400).send({tokenError: err.message});
return;
}
next(err);
}
};

module.exports = authenticate;
24 changes: 2 additions & 22 deletions src/routes/index.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,12 @@
const {AUTH_CLIENT_SECRET} = process.env;
const {Router} = require('express');
const jwt = require('jsonwebtoken');
const pkg = require('../../package');

const authenticate = (req, res, next) => {
const {split} = require('lodash');
const header = req.get('Authorization');
if (!header) {
return res.sendStatus(401);
}
const token = split(header, /\s+/).pop();
if (!token) {
return res.sendStatus(401);
}
try {
req.user = jwt.decode(token);
jwt.verify(token, AUTH_CLIENT_SECRET);
next();
} catch (err) {
next(err);
}
};

const authenticate = require('../middlewares/authenticate');

class Routes {
static configure(app) {
app.get('/ping', (req, res) => res.send({version: pkg.version}));
app.use('/sync', authenticate, require('./sync')(Router()));
app.use('/sync', authenticate(), require('./sync')(Router()));
}
}

Expand Down