updated token verification middleware reworked blog post POST controller username acquisition
29 lines
1 KiB
JavaScript
29 lines
1 KiB
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,
|
|
sameSite: "none",
|
|
secure: true,
|
|
})
|
|
.status(200)
|
|
.json({
|
|
message: "Authentication complete", // a winrar is you
|
|
});
|
|
}
|
|
}
|
|
return res.status(401).json({ message: "Authentication failed" }); // epic fail
|
|
});
|