28 lines
765 B
JavaScript
28 lines
765 B
JavaScript
const jwt = require('jsonwebtoken');
|
|
|
|
const JWT_SECRET = process.env.JWT_SECRET || 'dev-only-change-me-for-production';
|
|
const JWT_ALGORITHM = 'HS256';
|
|
const TOKEN_TTL_HOURS = 12;
|
|
|
|
function createAccessToken(user) {
|
|
const now = Math.floor(Date.now() / 1000);
|
|
const payload = {
|
|
sub: user.id,
|
|
username: user.username,
|
|
is_super_admin: !!user.is_super_admin,
|
|
iat: now,
|
|
exp: now + TOKEN_TTL_HOURS * 3600,
|
|
};
|
|
return jwt.sign(payload, JWT_SECRET, { algorithm: JWT_ALGORITHM });
|
|
}
|
|
|
|
function decodeToken(token) {
|
|
return jwt.verify(token, JWT_SECRET, { algorithms: [JWT_ALGORITHM] });
|
|
}
|
|
|
|
function getTokenTtlSeconds() {
|
|
return TOKEN_TTL_HOURS * 3600;
|
|
}
|
|
|
|
module.exports = { createAccessToken, decodeToken, getTokenTtlSeconds, TOKEN_TTL_HOURS };
|