Server's Endpoints for Classic Login
In server.js
let's add the following endpoints:
Login
app.post("/auth/login", (req, res) => {
const user = findUser(req.body.email);
if (user) {
// user exists, check password
if (bcrypt.compareSync(req.body.password, user.password)) {
res.send({ok: true, email: user.email, name: user.name});
} else {
res.send({ok: false, message: 'Data is invalid'});
}
} else {
// User doesn't exist
res.send({ok: false, message: 'Data is invalid'});
}
});
Registration
function findUser(email) {
const results = db.data.users.filter(u=>u.email==email);
if (results.length==0) return undefined;
return results[0];
}
app.post("/auth/register", (req, res) => {
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync(req.body.password, salt);
const user = {
name: req.body.name,
email: req.body.email,
password: hash
};
const userFound = findUser(req.body.email);
if (userFound) {
// User already registered
res.send({ok: false, message: 'User already exists'});
} else {
// New User
db.data.users.push(user);
db.write();
res.send({ok: true});
}
});
Now in API.js
we need to add the client-side calls
login: async (user) => {
return await API.makePostRequest(API.endpoint + "login", user);
},
register: async (user) => {
return await API.makePostRequest(API.endpoint + "register", user);
},