express-blog-api/controllers/login.js
ak e69fe69d90 revised to use httpOnly cookie to store jwt
comments can no longer be updated or deleted - out of scope
users can now be created, updated and deleted
2023-09-27 16:50:58 -07:00

27 lines
984 B
JavaScript

const asyncHandler = require("express-async-handler");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const User = require("../models/user.js");
let opts = {};
exports.post = asyncHandler(async (req, res, next) => {
const { username, password } = req.body; // get fields from body
const user = await User.findOne({ username: username }).lean().exec(); // gets user based on username
if (user) {
const match = await bcrypt.compare(password, user.password); // compare bcrypt hashed passwords
if (match) {
opts.expiresIn = "1d";
const token = jwt.sign({ username }, process.env.SECRET_KEY, opts); // create token and return below
return res
.cookie("JWT_TOKEN", token, {
httpOnly: true,
})
.status(200)
.json({
message: "Authentication complete", // a winrar is you
});
}
}
return res.status(401).json({ message: "Authentication failed" }); // epic fail
});