Skip to content

Instantly share code, notes, and snippets.

@nicovray
Created June 4, 2022 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicovray/a1cf38d1bf61953b7b9dd47c9684a8f1 to your computer and use it in GitHub Desktop.
Save nicovray/a1cf38d1bf61953b7b9dd47c9684a8f1 to your computer and use it in GitHub Desktop.
const authRouter = require('express').Router();
const User = require('../models/user');
authRouter.post('/checkCredentials', (req, res) => {
const { email, password } = req.body;
User.findByEmail(email).then((user) => {
if (!user) res.status(401).send('Invalid credentials');
else {
User.verifyPassword(password, user.hashedPassword).then(
(passwordIsCorrect) => {
if (passwordIsCorrect) res.status(200).send('Your credentials are valid !');
else res.status(401).send('Invalid credentials');
}
);
}
});
});
module.exports = authRouter;
const create = ({ firstname, lastname, city, language, email, password }) => {
return hashPassword(password).then((hashedPassword) => {
return db
.query('INSERT INTO users SET ?', {
firstname,
lastname,
city,
language,
email,
hashedPassword,
})
.then(([result]) => {
const id = result.insertId;
return { firstname, lastname, city, language, email, id };
});
});
};
const hashingOptions = {
type: argon2.argon2id,
memoryCost: 2 ** 16,
timeCost: 5,
parallelism: 1,
};
const hashPassword = (plainPassword) => {
return argon2.hash(plainPassword, hashingOptions);
};
const verifyPassword = (plainPassword, hashedPassword) => {
return argon2.verify(hashedPassword, plainPassword, hashingOptions);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment