File size: 1,666 Bytes
ce89c62
 
 
 
 
 
 
 
 
 
cd8250c
 
ce89c62
cd8250c
 
 
 
 
ce89c62
cd8250c
ce89c62
cd8250c
ce89c62
cd8250c
ce89c62
 
 
cd8250c
ce89c62
cd8250c
ce89c62
 
 
cd8250c
 
 
 
ce89c62
 
 
 
 
cd8250c
ce89c62
 
cd8250c
ce89c62
 
 
cd8250c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { Router } from 'express';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import db from './db.js';

const DATA_DIR = process.env.DATA_DIR || path.join(process.cwd(), 'data');

let secret = process.env.JWT_SECRET;
if (!secret) {
  const file = path.join(DATA_DIR, 'jwt-secret');
  if (fs.existsSync(file)) secret = fs.readFileSync(file, 'utf8').trim();
  else {
    secret = crypto.randomBytes(32).toString('hex');
    fs.writeFileSync(file, secret);
  }
}
export { secret };

const router = Router();

router.post('/login', (req, res) => {
  const { username, password } = req.body || {};
  const u = db.prepare('SELECT * FROM users WHERE username = ?').get(String(username || ''));
  if (!u || !bcrypt.compareSync(String(password || ''), u.password_hash)) {
    return res.status(401).json({ error: 'Invalid credentials' });
  }
  const token = jwt.sign({ sub: u.id, username: u.username, role: u.role }, secret, { expiresIn: '12h' });
  res.json({ token, user: { id: u.id, username: u.username, role: u.role } });
});

router.get('/me', requireAuth, (req, res) => {
  res.json({ id: req.user.sub, username: req.user.username, role: req.user.role });
});

export function requireAuth(req, res, next) {
  const header = req.headers.authorization || '';
  const token = header.startsWith('Bearer ') ? header.slice(7) : null;
  if (!token) return res.status(401).json({ error: 'Missing token' });
  try {
    req.user = jwt.verify(token, secret);
    next();
  } catch {
    res.status(401).json({ error: 'Invalid token' });
  }
}

export default router;