27 lines
689 B
JavaScript
27 lines
689 B
JavaScript
const jwt = require("jsonwebtoken")
|
|
|
|
function getBearerToken(req) {
|
|
const h = req.headers.authorization
|
|
if (!h) return null
|
|
const [type, token] = h.split(" ")
|
|
if (type !== "Bearer" || !token) return null
|
|
return token
|
|
}
|
|
|
|
module.exports = function optionalAuth(req, res, next) {
|
|
const token = getBearerToken(req)
|
|
if (!token) return next()
|
|
|
|
try {
|
|
const decoded = jwt.verify(token, process.env.JWT_ACCESS_SECRET)
|
|
req.auth = {
|
|
userId: typeof decoded.sub === "string" ? Number(decoded.sub) : decoded.sub,
|
|
role: decoded.role,
|
|
jti: decoded.jti,
|
|
}
|
|
return next()
|
|
} catch (err) {
|
|
return res.status(401).json({ error: "Token geçersiz" })
|
|
}
|
|
}
|