added login, follow the readme

This commit is contained in:
Aqeeb Imtiaz Harun
2018-08-09 12:39:44 +08:00
parent fc1b011160
commit 0d606489bf
5 changed files with 97 additions and 24 deletions
+67
View File
@@ -0,0 +1,67 @@
const fs = require('fs');
const bodyParser = require('body-parser');
const jsonServer = require('json-server');
const jwt = require('jsonwebtoken');
const server = jsonServer.create();
const router = jsonServer.router('./db.json');
const userdb = JSON.parse(fs.readFileSync('./users.json', 'UTF-8'));
server.use(bodyParser.urlencoded({extended: true}))
server.use(bodyParser.json())
//server.use(jsonServer.defaults());
const SECRET_KEY = '123456789';
const expiresIn = '1h';
// Create a token from a payload
function createToken(payload){
return jwt.sign(payload, SECRET_KEY, {expiresIn});
}
// Verify the token
function verifyToken(token){
return jwt.verify(token, SECRET_KEY, (err, decode) => decode !== undefined ? decode : err);
}
// Check if the user exists in database
function isAuthenticated({phone, password}){
return userdb.users.findIndex(user => user.phone === phone && user.password === password) !== -1;
}
server.post('/auth/login', (req, res) => {
const {phone, password} = req.body;
if (isAuthenticated({phone, password}) === false) {
const status = 401;
const message = 'Incorrect phone or password';
res.status(status).json({status, message});
return;
}
const access_token = createToken({phone, password});
res.status(200).json({access_token});
});
server.use(/^(?!\/auth).*$/, (req, res, next) => {
if (req.headers.authorization === undefined || req.headers.authorization.split(' ')[0] !== 'Bearer') {
const status = 401;
const message = 'Bad authorization header';
res.status(status).json({status, message});
return;
}
try {
verifyToken(req.headers.authorization.split(' ')[1]);
next();
} catch (err) {
const status = 401;
const message = 'Error: access_token is not valid';
res.status(status).json({status, message});
}
});
server.use(router);
server.listen(3000, () => {
console.log('Run Auth API Server');
})