Skip to content

Instantly share code, notes, and snippets.

@dev-cyprium
Last active August 1, 2019 14:41
Show Gist options
  • Select an option

  • Save dev-cyprium/d5b876633286585bcffe2d3b527f42c1 to your computer and use it in GitHub Desktop.

Select an option

Save dev-cyprium/d5b876633286585bcffe2d3b527f42c1 to your computer and use it in GitHub Desktop.
JWT
function work() {
console.log('Working');
setTimeout(work, 0);
}
work();
// This won't halt the MAIN JS THREAD!
// Because we keep adding to the JOB queue
// However, this will:
function halt() {
while(true) {}
}
setTimeout(halt, 2000)
import express from 'express'
import jwt from 'jsonwebtoken'
import fs from 'fs'
const app = express();
app.use(express.json());
function msg(msg) {
return {msg};
}
app.get('/', (req, resp) => {
resp.send(msg('Welcome to my order server!'));
})
app.post('/login', (req, resp) => {
fs.readFile('./users.json', {encoding: 'utf-8'}, (err, data) => {
if(err) {
resp.status(503);
resp.send(msg('Service is not avialable'));
return;
}
const {email} = req.body;
const users = JSON.parse(data);
const user = users.find(user => user.email === email);
if (user) {
jwt.sign({id: user.id}, 'secret', {expiresIn: 60}, (err, token) => {
if (err) {
resp.status(403);
resp.send(msg('Not Authorized'));
return;
}
resp.send({token});
});
} else {
resp.status(403);
resp.send(msg('Not Authorized'));
}
})
});
app.get('/orders', (req, resp) => {
const authHeader = req.headers['authorization'];
const token = authHeader.split(' ')[1];
jwt.verify(token, 'secret', (err, token_data) => {
if (err) {
resp.status(403);
resp.send(msg('Not Authorized'));
return;
}
fs.readFile('./orders.json', {encoding: 'utf-8'}, (err, data) => {
if(err) {
resp.status(503);
resp.send('Service is not avialable');
return;
}
resp.send({orders: JSON.parse(data), operator_id: token_data.id})
})
})
})
app.listen(3333, () => {
console.log('Listening at http://localhost:3333')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment