Files
izyim-mockapi/server.js
2018-08-25 10:41:02 +08:00

146 lines
4.4 KiB
JavaScript

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;
}
// check if the number already exists in database
//this function's implementation is commented out for the time being because of the token mismatch issue, this will be implemanted later on.
function isInDatabase({phone}){
return userdb.users.findIndex(user => user.phone === phone) !== -1;
}
//create verification code for phone number
function verificationCode(){
var val = Math.floor(1000 + Math.random() * 9000);
//console.log(val);
return val;
}
// function findLatestID(data){
// theHighestQuantity = data[0]['id'];
// //console.log(theHighestQuantity);
// for (var i = 0; i< data.length; i++){
// console.log(data[i]['id']);
// if(data[i]['id'] > theHighestQuantity){
// theHighestQuantity = data[i]['id'];
// }
// }
// return theHighestQuantity;
// //return userdb.users.reduce((max, b) => Math.max(max, b.id),userdb.users[0].id);
// }
//Function to find a specific id in users.json file
//This function is depricted for the time being, in case we plan to use it in any way
function findUserId(data, id){
for (var i = 0; i<data.length; i++){
if(data[i]['id'] = id){
return i;
}
}
}
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.post('/send-verification', (req, res)=>{
const {phone} = req.body;
const id = userdb.users.length + 1;
//if(isInDatabase({phone} === false)){
userdb.users.push({id: id, phone: phone, password: null, name: null, role: null});
fs.writeFile('users.json', JSON.stringify(userdb),
function(err){
if(err) throw err;
console.log('added to json');
});
//}
// else{
// console.log('number exists');
// const status = 409;
// const message = 'Number already exists';
// res.status(status).json({status, message});
// }
const verification_code = verificationCode();
res.status(200).json({verification_code});
});
server.post('/update-user', (req, res)=>{
const {name, role, password, id} = req.body;
//var i = findUserId(userdb.users, id);
for (var i = 0; i<userdb.users.length; i++){
if(userdb.users[i]['id'] == id){
userdb.users[i].password = password;
userdb.users[i].name = name;
userdb.users[i].role = role;
}
}
fs.writeFile('users.json', JSON.stringify(userdb),
function(err){
if(err) throw err;
console.log('updated json');
});
const status = 200;
const message = 'Profile Updated';
res.status(status).json({status, message});
});
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');
})