Skip to content

Instantly share code, notes, and snippets.

@kilgarenone
Last active May 20, 2020 03:16
Show Gist options
  • Save kilgarenone/6d7b046573933c5568461cbbaeb7916d to your computer and use it in GitHub Desktop.
Save kilgarenone/6d7b046573933c5568461cbbaeb7916d to your computer and use it in GitHub Desktop.
user authentication
const Auth = require("../lib/auth");
const multer = require("multer");
const upload = multer();
const asyncHandler = require("express-async-handler");
router.post("/signin", upload.none(), asyncHandler(async (req, res, next) => {
const { email, plainTextPassword } = req.body;
// get the hashed password associated to the email entered by user
const query = `SELECT password FROM account WHERE email=($1)`;
const values = [email];
const { rows } = await db.query(query, values);
const hashedPassword = rows[0].password;
// (i love how they name the method to reflect its intention)
const isMatch = await Auth.comparePassword(plainTextPassword, hashedPassword);
// if 'isMatch' is TRUE, means user entered the correct password, then let her in, and vice versa.
if (!isMatch) {
return next(
createError(422, "Please enter a correct email and password")
);
}
// we will use this flag to determine if a user is still logged in
req.session.isLoggedIn = true;
// we can also store additional user data
req.session.user = { user_id, ...userProfile };
// up to you
res.sendStatus(isMatch ? 200 : 401);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment