import express from 'express'; import { database } from '../Classes/Database'; import jwt from 'jsonwebtoken'; const router = express.Router(); // POST to login using username and password router.post('/login', async (req, res) => { try { const { username, password } = req.body; if (!username || !password) { res.status(400).json({ error: 'Bad Request' }); } const rows = await database.execute('SELECT * FROM users WHERE username = ?', [username]); if (rows.length === 0) { res.status(401).json({ error: 'Unauthorized' }); } else { const isPasswordValid = await Bun.password.verify(password, rows[0].password); if (!isPasswordValid) { res.status(401).json({ error: 'Unauthorized' }); } else { const token = jwt.sign({ username, password }, process.env.SECRET); res.status(200).json({ token }); } } } catch (error) { res.status(500).json({ error: 'Internal Server Error' }); } }); // POST to check if token is valid router.post('/verify', async (req, res) => { try { const token = req.body.token; if (!token) { res.status(401).json({ error: 'Unauthorized' }); } else { jwt.verify(token, process.env.SECRET, async (err, decoded) => { if (err) res.status(401).json({ error: 'Unauthorized' }); const rows = await database.execute('SELECT * FROM users WHERE username = ?', [decoded.username]); if (rows.length === 0) res.status(401).json({ error: 'Unauthorized' }); const isPasswordValid = await Bun.password.verify(decoded.password, rows[0].password); if (!isPasswordValid) res.status(401).json({ error: 'Unauthorized' }); res.status(200).json({ message: 'Authorized' }); }); } } catch (error) { res.status(500).json({ error: 'Internal Server Error' }); } }); // POST to register a new user router.post('/register', async (req, res) => { try { const { username, password } = req.body; if (!username || !password) { res.status(400).json({ error: 'Bad Request' }); } const hashedPassword = await Bun.password.hash(password); await database.execute('INSERT INTO users (username, password) VALUES (?, ?)', [username, hashedPassword]); res.status(201).json({ message: 'User created successfully' }); } catch (error) { res.status(500).json({ error: 'Internal Server Error' }); } }); export default router;