Spaces:
Paused
Paused
Download server/src/auth.js from secutorpro/dispatch-console: direct link, hf CLI and curl.
- Browser
- Download file 1.67 kB
-
https://huggingface.co/spaces/secutorpro/dispatch-console/resolve/main/server/src/auth.js
- Command line
-
hf download hf://spaces/secutorpro/dispatch-console/server/src/auth.js
-
curl -L -o auth.js https://huggingface.co/spaces/secutorpro/dispatch-console/resolve/main/server/src/auth.js
1.67 kB
| 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; |