6 changed files with 125 additions and 73 deletions
@ -1,47 +1,47 @@ |
|||||
const express = require('express'); |
const express = require('express'); |
||||
const bcrypt = require('bcryptjs'); |
const bcrypt = require('bcryptjs'); |
||||
const jwt = require('jsonwebtoken'); |
const jwt = require('jsonwebtoken'); |
||||
const pool = require('../config/databases'); |
const { pool } = require('../config/databases'); |
||||
require('dotenv').config(); |
require('dotenv').config(); |
||||
|
|
||||
const router = express.Router(); |
const router = express.Router(); |
||||
|
|
||||
router.post('/login', async (req, res) => { |
router.post('/login', async (req, res) => { |
||||
const { username, password } = req.body; |
const { username, password } = req.body; |
||||
|
|
||||
try { |
try { |
||||
const [rows] = await pool.query( |
const [rows] = await pool.query( |
||||
'SELECT * FROM users WHERE username = ?', |
'SELECT * FROM users WHERE username = ?', |
||||
[username] |
[username] |
||||
); |
); |
||||
|
|
||||
if (rows.length === 0) { |
if (rows.length === 0) { |
||||
return res.status(401).json({ message: 'Invalid credentials' }); |
return res.status(401).json({ message: 'Invalid credentials' }); |
||||
} |
} |
||||
|
|
||||
const user = rows[0]; |
const user = rows[0]; |
||||
|
|
||||
const isMatch = await bcrypt.compare(password, user.password); |
const isMatch = await bcrypt.compare(password, user.password); |
||||
|
|
||||
if (!isMatch) { |
if (!isMatch) { |
||||
return res.status(401).json({ message: 'Invalid credentials' }); |
return res.status(401).json({ message: 'Invalid credentials' }); |
||||
} |
} |
||||
|
|
||||
|
const payload = { |
||||
|
id: user.id, |
||||
|
username: user.username, |
||||
|
role: user.role, |
||||
|
}; |
||||
|
|
||||
const payload = { |
const token = jwt.sign(payload, process.env.JWT_SECRET, { |
||||
id: user.id, |
expiresIn: '2h', // max lifespan
|
||||
username: user.username, |
}); |
||||
role: user.role, |
|
||||
}; |
res.json({ token }); |
||||
|
} catch (err) { |
||||
const token = jwt.sign(payload, process.env.JWT_SECRET, { |
console.error(err); |
||||
expiresIn: '2h', // max lifespan
|
res.status(500).json({ message: 'Server error' }); |
||||
}); |
} |
||||
|
|
||||
res.json({ token }); |
|
||||
} catch (err) { |
|
||||
console.error(err); |
|
||||
res.status(500).json({ message: 'Server error' }); |
|
||||
} |
|
||||
}); |
}); |
||||
|
|
||||
module.exports = router; |
module.exports = router; |
||||
|
|||||
Loading…
Reference in new issue