northwind-rest-api
Version:
Local REST API Exposing 'Northwind Traders' Database.
41 lines (36 loc) • 1.21 kB
JavaScript
const jwt = require("jsonwebtoken");
const dal = require("../data-access-layer/dal");
async function isEmailTaken(email) {
const users = await dal.getAllUsers();
const index = users.findIndex(u => u.email === email);
return index !== -1;
}
async function register(user) {
const users = await dal.getAllUsers();
const maxId = users.reduce((maxId, u) => u.id > maxId ? u.id : maxId, 0);
user.id = maxId + 1;
user.role = "User";
users.push(user);
await dal.saveAllUsers(users);
delete user.password;
const token = jwt.sign({ user }, config.jwtKey, { expiresIn: "5h" });
return token;
};
async function login(credentials) {
const users = await dal.getAllUsers();
const user = users.find(u => u.email === credentials.email && u.password === credentials.password);
if(!user) return null;
delete user.password;
const token = jwt.sign({ user }, config.jwtKey, { expiresIn: "5h" });
return token;
}
function refreshToken(user) {
const token = jwt.sign({ user }, config.jwtKey, { expiresIn: "5h" });
return token;
};
module.exports = {
isEmailTaken,
register,
login,
refreshToken
};