api-server/src/modules/auth/token.service.ts

27 lines
795 B
TypeScript
Raw Normal View History

import * as crypto from 'crypto';
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class TokenService {
constructor(private readonly jwtService: JwtService) {}
generateAccessToken(user: { id: bigint; email?: string | null; role?: string | null }): Promise<string> {
return this.jwtService.signAsync({
sub: String(user.id),
email: user.email,
role: user.role,
});
}
generateRefreshToken(): { token: string; hash: string } {
const token = crypto.randomBytes(48).toString('hex');
const hash = crypto.createHash('sha256').update(token).digest('hex');
return { token, hash };
}
hashToken(token: string): string {
return crypto.createHash('sha256').update(token).digest('hex');
}
}