50 lines
1.8 KiB
JavaScript

import { Router } from 'express';
import bcrypt from 'bcrypt';
import { v4 as uuidv4 } from 'uuid';
import db from '../db.js';
import { generateToken, authenticateToken } from '../middleware/auth.js';
const router = Router();
router.post('/register', (req, res) => {
const { username, email, password } = req.body;
if (!username || !email || !password) {
return res.status(400).json({ error: 'Username, email, and password are required' });
}
const existing = db.prepare('SELECT id FROM users WHERE username = ? OR email = ?').get(username, email);
if (existing) {
return res.status(409).json({ error: 'Username or email already exists' });
}
const id = uuidv4();
const passwordHash = bcrypt.hashSync(password, 10);
db.prepare('INSERT INTO users (id, username, email, password_hash) VALUES (?, ?, ?, ?)').run(id, username, email, passwordHash);
const token = generateToken(id);
res.status(201).json({ token, user: { id, username, email } });
});
router.post('/login', (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ error: 'Username and password are required' });
}
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
if (!user || !bcrypt.compareSync(password, user.password_hash)) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const token = generateToken(user.id);
res.json({ token, user: { id: user.id, username: user.username, email: user.email } });
});
router.get('/me', authenticateToken, (req, res) => {
const user = db.prepare('SELECT id, username, email, discord_id, global_name, avatar, created_at FROM users WHERE id = ?').get(req.userId);
if (!user) return res.status(404).json({ error: 'User not found' });
res.json({ user });
});
export default router;