generated from lucien/api-template
53 lines
No EOL
1.7 KiB
JavaScript
53 lines
No EOL
1.7 KiB
JavaScript
const express = require('express');
|
|
const sha256 = require("sha256");
|
|
const jwt = require('jsonwebtoken');
|
|
const { getConnection, getUserByUsername, addUser, getUser } = require('../libs/mysql');
|
|
|
|
const router = express.Router();
|
|
|
|
router.post('/login', 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,
|
|
});
|
|
return res.send({ token: token });
|
|
}
|
|
}
|
|
res.status(401).send({ error: 'Invalid username or password' });
|
|
});
|
|
|
|
router.post('/register', async (req, res) => {
|
|
const { username, password } = req.body;
|
|
const connection = await getConnection();
|
|
|
|
const use = await getUserByUsername(connection, username);
|
|
if (use[0]) {
|
|
connection.end();
|
|
return res.status(401).send({ error: 'Username already exists' });
|
|
}
|
|
|
|
const hash = sha256(password);
|
|
await addUser(connection, username, hash);
|
|
connection.end();
|
|
res.send({ message: 'User added' });
|
|
});
|
|
|
|
router.post('/me', async (req, res) => {
|
|
const { token } = req.body;
|
|
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
|
const connection = await getConnection();
|
|
const users = await getUser(connection, decoded.id);
|
|
connection.end();
|
|
if (users[0]) {
|
|
res.send({ id: users[0].id, username: users[0].username });
|
|
} else {
|
|
res.status(401).send({ error: 'Invalid token' });
|
|
}
|
|
});
|
|
|
|
module.exports = router; |