/
NeGaTiVe333
/
lab4
Обзор
Документация
Войти
/
NeGaTiVe333
/
lab4
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/middleware/auth.js
35 строк
1 KB
mmr97
upload files
01 дек 2025, 00:52
01 дек 2025, 00:52
844022e
Код
Авторство
О чём код?
const jwt = require('jsonwebtoken'); const { users } = require('../store'); const SECRET = process.env.JWT_SECRET || 'replace_this_secret_in_prod'; function signJwt(payload) { return jwt.sign(payload, SECRET, { expiresIn: '2h' }); } function verifyJwt(req, res, next) { const auth = req.headers.authorization; if (!auth || !auth.startsWith('Bearer ')) return res.status(401).json({ error: 'No token' }); const token = auth.slice(7); try { const decoded = jwt.verify(token, SECRET); req.user = users.find(u => u.id === decoded.sub); if (!req.user) return res.status(401).json({ error: 'User not found' }); next(); } catch (e) { return res.status(401).json({ error: 'Invalid token' }); } } // optional verifier (for endpoints that allow public access) function verifyJwtOptional(req, res, next) { const auth = req.headers.authorization; if (!auth) return next(); try { const token = auth.slice(7); const decoded = jwt.verify(token, SECRET); req.user = users.find(u => u.id === decoded.sub); } catch (e) { /* ignore */ } next(); } module.exports = { signJwt, verifyJwt, verifyJwtOptional };