generated from lucien/api-template
24 lines
No EOL
808 B
JavaScript
24 lines
No EOL
808 B
JavaScript
const express = require('express');
|
|
const sha256 = require("sha256");
|
|
const jwt = require('jsonwebtoken');
|
|
const { getConnection, getUserByUsername } = require('../libs/mysql');
|
|
|
|
const router = express.Router();
|
|
|
|
router.post('/', async (req, res) => {
|
|
const { username, password } = req.body;
|
|
const connection = await getConnection();
|
|
const users = await getUserByUsername(connection, username);
|
|
connection.end();
|
|
if (users[0]) {
|
|
if (users[0].password === sha256(password)) {
|
|
const token = jwt.sign({ id: users[0].id }, process.env.JWT_SECRET, {
|
|
expiresIn: 1000 * 60 * 60 * 24 * 7,
|
|
});
|
|
res.send({ token: token });
|
|
}
|
|
}
|
|
res.status(401).send({ error: 'Invalid username or password' });
|
|
});
|
|
|
|
module.exports = router; |