Access tokens generation

This commit is contained in:
2024-06-23 21:33:15 +08:00
parent 3a92792dc8
commit e208a0c400
2 changed files with 59 additions and 1 deletions

View File

@@ -1,7 +1,24 @@
#####################################
# Environment Variables configuration
# -----------------------------------
# Copy and paste the content below
# into a `.env` file at the root of
# the project, and modify the entries
# to match the development
# environment-specific needs.
#####################################
# Access address & ports
APP_PORT = 5183
CLIENT_URL = "http://localhost:5173"
# Database metadata
DB_HOST = "hostname"
DB_PORT = 3306
DB_USER = "username"
DB_PWD = "password"
DB_NAME = "FSDP_ECOCONNECT_DB"
# `jsonwebtoken` metadata
APP_SECRET = "7FB18313-476E-40E7-9257-D4F78B839FC6"
TOKEN_EXPIRES_IN = "90d"

View File

@@ -5,6 +5,9 @@ const { User } = require("../models");
const argon2 = require("argon2");
const router = express.Router();
const { v4: uuidV4 } = require("uuid");
const { sign } = require("jsonwebtoken");
require("dotenv").config();
let validationSchema = yup.object({
id: yup.string().trim().min(36).max(36).required(),
@@ -128,4 +131,42 @@ router.delete("/individual/:id", async (req, res) => {
}
});
router.post("/login", async (req, res) => {
let data = req.body;
let errorMessage = "Email or password is not correct.";
let user = await User.findOne({
where: { email: data.email },
});
if (!user) {
res.status(400).json({ message: errorMessage });
return;
}
let match = await argon2.verify(user.password, data.password);
if (!match) {
res.status(400).json({ message: errorMessage });
return;
}
let userInfo = {
id: user.id,
email: user.email,
name: {
firstName: user.firstName,
lastName: user.lastName,
},
};
let accessToken = sign(userInfo, process.env.APP_SECRET, {
expiresIn: process.env.TOKEN_EXPIRES_IN,
});
res.json({
accessToken: accessToken,
user: userInfo,
});
});
module.exports = router;