????
Current Path : C:/inetpub/vhost/invest.gdtsolutions.vn/api/dist/apps/auth/ |
Current File : C:/inetpub/vhost/invest.gdtsolutions.vn/api/dist/apps/auth/token.service.js |
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var TokenService_1; Object.defineProperty(exports, "__esModule", { value: true }); exports.TokenService = void 0; const crypto_1 = require("crypto"); const common_1 = require("@nestjs/common"); const typeorm_1 = require("@nestjs/typeorm"); const jwt_1 = require("@nestjs/jwt"); const config_1 = require("@nestjs/config"); const schedule_1 = require("@nestjs/schedule"); const typeorm_2 = require("typeorm"); const ms_1 = __importDefault(require("ms")); const user_token_entity_1 = require("./entities/user-token.entity"); let TokenService = TokenService_1 = class TokenService { constructor(repo, jwtService, configService, scheduleRegistry) { this.repo = repo; this.jwtService = jwtService; this.configService = configService; this.scheduleRegistry = scheduleRegistry; this.logger = new common_1.Logger(TokenService_1.name); } async createTokens(userId) { const accessTokenValue = await this.jwtService.signAsync({ userId }, { secret: this.configService.get('ACCESS_TOKEN_SECRET'), expiresIn: this.configService.get('ACCESS_TOKEN_LIFE'), subject: userId.toString(), }); const accessToken = new user_token_entity_1.UserToken(); accessToken.payload = accessTokenValue; accessToken.type = 'access_token'; accessToken.status = 'valid'; accessToken.expiresAt = new Date(Date.now() + (0, ms_1.default)(this.configService.get('ACCESS_TOKEN_LIFE'))); accessToken.refToken = this.generateRefToken(); accessToken.userId = userId; await this.repo.save(accessToken); const refreshTokenValue = await this.jwtService.signAsync({ userId }, { secret: this.configService.get('REFRESH_TOKEN_SECRET'), expiresIn: this.configService.get('REFRESH_TOKEN_LIFE'), subject: userId.toString(), }); const refreshToken = new user_token_entity_1.UserToken(); refreshToken.payload = refreshTokenValue; refreshToken.type = 'refresh_token'; refreshToken.status = 'valid'; refreshToken.expiresAt = new Date(Date.now() + (0, ms_1.default)(this.configService.get('REFRESH_TOKEN_LIFE'))); refreshToken.refToken = this.generateRefToken(); refreshToken.userId = userId; await this.repo.save(refreshToken); return { userId, accessToken: accessToken.refToken, accessTokenExpiresAt: accessToken.expiresAt, refreshToken: refreshToken.refToken, refreshTokenExpiresAt: refreshToken.expiresAt, }; } async revokeToken(token, type = 'access_token') { await this.repo.update({ refToken: token, type }, { status: 'revoked' }); } async getTokenPayload(token, type = 'access_token') { const userToken = await this.repo.findOneBy({ refToken: token, type, status: 'valid' }); return userToken?.payload; } async exchangeRefreshToken(token) { const refreshTokenPayload = await this.getTokenPayload(token, 'refresh_token'); if (!refreshTokenPayload) throw new common_1.UnauthorizedException('Refresh token không tồn tại hoặc đã bị thu hồi'); try { const decodedToken = await this.jwtService.verifyAsync(refreshTokenPayload, { secret: this.configService.get('REFRESH_TOKEN_SECRET'), }); await this.repo.update({ refToken: token, type: 'refresh_token' }, { status: 'redeemed' }); return this.createTokens(decodedToken.userId); } catch (err) { throw new common_1.UnauthorizedException(err.message); } } extractTokenFromHeader(req) { const [type, token] = req.headers.authorization?.split(' ') ?? []; return type === 'Bearer' ? token : undefined; } async pruneTokensTask() { try { await this.repo .createQueryBuilder() .delete() .where({ status: (0, typeorm_2.Not)('valid') }) .orWhere({ expiresAt: (0, typeorm_2.LessThan)(new Date()) }) .execute(); this.logger.log('Đã hoàn thành dọn dẹp kho token!'); } catch (err) { this.logger.error(`Dọn dẹp kho token bị lỗi: ${err.message}`); } } async runPruneTokens() { this.scheduleRegistry.getCronJob('pruneTokens').fireOnTick(); } generateRefToken(size = 256) { return (0, crypto_1.randomBytes)(size / 8).toString('base64'); } }; exports.TokenService = TokenService; __decorate([ (0, schedule_1.Cron)(schedule_1.CronExpression.EVERY_4_HOURS, { name: 'pruneTokens' }), __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", Promise) ], TokenService.prototype, "pruneTokensTask", null); __decorate([ (0, schedule_1.Timeout)(10000), __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", Promise) ], TokenService.prototype, "runPruneTokens", null); exports.TokenService = TokenService = TokenService_1 = __decorate([ (0, common_1.Injectable)(), __param(0, (0, typeorm_1.InjectRepository)(user_token_entity_1.UserToken)), __metadata("design:paramtypes", [typeorm_2.Repository, jwt_1.JwtService, config_1.ConfigService, schedule_1.SchedulerRegistry]) ], TokenService); //# sourceMappingURL=token.service.js.map