erp-mecanicas-diesel-backen.../src/shared/utils/jwt.utils.ts
rckrdmrd 8ed7d24e96 Migración desde erp-mecanicas-diesel/backend - Estándar multi-repo v2
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-16 08:11:24 -06:00

66 lines
1.4 KiB
TypeScript

/**
* JWT Utilities
* Mecánicas Diesel - ERP Suite
*/
import jwt, { SignOptions } from 'jsonwebtoken';
import { JwtPayload } from '../types';
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production';
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '15m';
const JWT_REFRESH_EXPIRES_IN = process.env.JWT_REFRESH_EXPIRES_IN || '7d';
/**
* Generate access token (short-lived)
*/
export function generateAccessToken(user: Omit<JwtPayload, 'iat' | 'exp'>): string {
return jwt.sign(
{
userId: user.userId,
email: user.email,
tenantId: user.tenantId,
role: user.role,
},
JWT_SECRET,
{ expiresIn: JWT_EXPIRES_IN } as SignOptions
);
}
/**
* Generate refresh token (long-lived)
*/
export function generateRefreshToken(user: Omit<JwtPayload, 'iat' | 'exp'>): string {
return jwt.sign(
{
userId: user.userId,
email: user.email,
tenantId: user.tenantId,
role: user.role,
},
JWT_SECRET,
{ expiresIn: JWT_REFRESH_EXPIRES_IN } as SignOptions
);
}
/**
* Verify and decode JWT token
*/
export function verifyToken(token: string): JwtPayload | null {
try {
return jwt.verify(token, JWT_SECRET) as JwtPayload;
} catch (error) {
return null;
}
}
/**
* Decode JWT token without verification
*/
export function decodeToken(token: string): JwtPayload | null {
try {
return jwt.decode(token) as JwtPayload;
} catch (error) {
return null;
}
}