66 lines
2.1 KiB
JavaScript
66 lines
2.1 KiB
JavaScript
import { getDb } from '../models/db.js';
|
|
import bcrypt from 'bcryptjs';
|
|
|
|
export default function setupRoutes(app) {
|
|
// Login
|
|
app.post('/api/auth/login', (req, res) => {
|
|
const db = getDb();
|
|
const { username, password } = req.body;
|
|
|
|
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
|
|
if (!user) {
|
|
return res.status(401).json({ error: 'Invalid credentials' });
|
|
}
|
|
|
|
const valid = bcrypt.compareSync(password, user.password);
|
|
if (!valid) {
|
|
return res.status(401).json({ error: 'Invalid credentials' });
|
|
}
|
|
|
|
// Log the login
|
|
db.prepare('INSERT INTO activity_log (user_id, action, details) VALUES (?, ?, ?)').run(user.id, 'login', 'User logged in');
|
|
|
|
res.json({ id: user.id, username: user.username });
|
|
});
|
|
|
|
// Register
|
|
app.post('/api/auth/register', (req, res) => {
|
|
const db = getDb();
|
|
const { username, password } = req.body;
|
|
|
|
if (!username || !password) {
|
|
return res.status(400).json({ error: 'Username and password required' });
|
|
}
|
|
|
|
const existing = db.prepare('SELECT id FROM users WHERE username = ?').get(username);
|
|
if (existing) {
|
|
return res.status(400).json({ error: 'Username already exists' });
|
|
}
|
|
|
|
const hash = bcrypt.hashSync(password, 10);
|
|
const result = db.prepare('INSERT INTO users (username, password) VALUES (?, ?)').run(username, hash);
|
|
|
|
// Log registration
|
|
db.prepare('INSERT INTO activity_log (user_id, action, details) VALUES (?, ?, ?)').run(result.lastInsertRowid, 'register', 'New user registered');
|
|
|
|
res.json({ id: result.lastInsertRowid, username });
|
|
});
|
|
|
|
// Get current user
|
|
app.get('/api/auth/me', (req, res) => {
|
|
const userId = req.headers['x-user-id'];
|
|
if (!userId) {
|
|
return res.status(401).json({ error: 'Not authenticated' });
|
|
}
|
|
|
|
const db = getDb();
|
|
const user = db.prepare('SELECT id, username FROM users WHERE id = ?').get(userId);
|
|
|
|
if (!user) {
|
|
return res.status(401).json({ error: 'User not found' });
|
|
}
|
|
|
|
res.json(user);
|
|
});
|
|
}
|