27 lines
640 B
JavaScript
27 lines
640 B
JavaScript
const jwt = require('jsonwebtoken')
|
|
|
|
const { SMOKE_TRACKER_TOKEN_KEY } = require('../const')
|
|
|
|
const authMiddleware = (req, res, next) => {
|
|
const authHeader = req.headers.authorization || ''
|
|
const token = authHeader.startsWith('Bearer ')
|
|
? authHeader.slice(7)
|
|
: null
|
|
|
|
if (!token) {
|
|
throw new Error('Требуется авторизация')
|
|
}
|
|
|
|
try {
|
|
const decoded = jwt.verify(token, SMOKE_TRACKER_TOKEN_KEY)
|
|
req.user = decoded
|
|
next()
|
|
} catch (e) {
|
|
throw new Error('Неверный или истекший токен авторизации')
|
|
}
|
|
}
|
|
|
|
module.exports.authMiddleware = authMiddleware
|
|
|
|
|