Skip to content

Instantly share code, notes, and snippets.

@jsheridanwells
Last active January 29, 2019 16:45
Show Gist options
  • Save jsheridanwells/23ae0f3fde67ecfdd10db36e47b5de7b to your computer and use it in GitHub Desktop.
Save jsheridanwells/23ae0f3fde67ecfdd10db36e47b5de7b to your computer and use it in GitHub Desktop.
Using Json-Server with JWT
  1. Create public and private RSA keys (public.key, private.key). Generate them here.
  2. npm install --save-dev jsonwebtokens json-server faker
  3. create users.json with at least email and password for a fake user.
  4. Add these to package.json (assumes code is in a directory called api):
    "api-noAuth": "node_modules/.bin/json-server api/seed.js",
    "api-auth": "node ./api/server.js",
    "api-seed": "node ./api/seed.js > api/db.json"
  1. npm run api-seed will create db.json, npm run api-noAuth is just the api npm run api-auth will create and require tokens.
const faker = require('faker');
const seed = () => {
let data = {
teachers: [],
students: [],
tickets:[]
};
// generate 10 teachers
for (let i = 0; i < 10; i++){
data.teachers.push({
email: faker.internet.email(),
password: faker.internet.password(8, 1),
name: faker.name.findName(),
id: i + 1
});
}
// generate 200 students
for (let i = 0; i < 200; i++){
data.students.push({
name: faker.name.findName(),
dob: faker.date.past(10),
points: faker.random.number({min:5, max:100}),
id: i + 1
});
}
// generate 2000 tickets
for (let i = 0; i < 2000; i++){
data.tickets.push({
student_id: faker.random.number({ min: 1, max: 200 }),
teacher_id: faker.random.number({ min: 1, max: 10 }),
datetime: faker.date.recent(),
reason: faker.lorem.sentence(8),
id: i + 1
});
}
// return data;
console.log(JSON.stringify(data));
};
// module.exports = seed;
seed();
const fs = require('fs');
const bodyParser = require('body-parser');
const jsonServer = require('json-server');
const jwt = require('jsonwebtoken');
const tokenHelper = require('./tokenHelper');
const server = jsonServer.create();
const router = jsonServer.router('./api/db.json');
const userdb = JSON.parse(fs.readFileSync('./api/users.json', 'UTF-8'));
server.use(bodyParser.urlencoded({extended: true}));
server.use(bodyParser.json());
const isAuth = ({ email, password }) => {
let authStatus = userdb.users.findIndex(u => u.email === email && u.password === password);
return authStatus !== -1;
};
server.post('/auth/login', (req, res) => {
const {email, password} = req.body
if (!isAuth({ email, password })) {
const status = 401;
const message = 'Incorrect email or password';
res.status(status).json({status, message});
return;
}
const access_token = tokenHelper.sign({ email, password });
res.status(200).json({ access_token });
});
server.use(/^(?!\/auth).*$/, (req, res, next) => {
let token = '';
if (req.headers.authorization === undefined || req.headers.authorization.split(' ')[0] !== 'Bearer'){
const status = 401;
const msg = 'Bad authorization header';
res.status(status).json({ status, msg });
return;
}
if (req.headers.authorization.split(' ')[1].length > 0)
token = req.headers.authorization.split(' ')[1];
try {
if (tokenHelper.verify(token)) {
next();
} else {
const status = 401;
const msg = 'You are not authorized';
res.status(status).json({ status, msg });
};
}
catch (e) {
const status = 401;
const message = 'Auth token is not valid';
res.status(status).json({status, message});
}
});
server.use(router);
server.listen(3000, () => {
console.log('Running the api server with auth');
});
const fs = require('fs');
const jwt = require('jsonwebtoken');
const privateKey = fs.readFileSync('./api/private.key', 'utf8');
const publicKey = fs.readFileSync('./api/public.key', 'utf8');
module.exports = {
sign: payload => {
let options = {
expiresIn: '30d',
algorithm: 'RS256'
};
let token = jwt.sign(payload, privateKey, options);
return token;
},
verify: token => {
let options = {
expiresIn: '30d',
algorithm: ['RS256']
};
try {
return jwt.verify(token, publicKey, options);
}
catch (e) {
return false;
}
},
decode: token => jwt.decode(token, { complete: true })
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment