UNPKG

@slickteam/nestjs-keycloak-admin

Version:
132 lines 5.93 kB
"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); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.KeycloakAdminService = exports.KeycloakActionsEmailEnum = void 0; const common_1 = require("@nestjs/common"); const config_1 = require("@nestjs/config"); const keycloak_admin_client_cjs_1 = require("@s3pweb/keycloak-admin-client-cjs"); const jwt_decode_1 = require("jwt-decode"); const logger = new common_1.Logger('KeycloakAdminService'); var KeycloakActionsEmailEnum; (function (KeycloakActionsEmailEnum) { KeycloakActionsEmailEnum["VERIFY_EMAIL"] = "VERIFY_EMAIL"; KeycloakActionsEmailEnum["UPDATE_PROFILE"] = "UPDATE_PROFILE"; KeycloakActionsEmailEnum["CONFIGURE_TOTP"] = "CONFIGURE_TOTP"; KeycloakActionsEmailEnum["UPDATE_PASSWORD"] = "UPDATE_PASSWORD"; KeycloakActionsEmailEnum["TERMS_AND_CONDITIONS"] = "TERMS_AND_CONDITIONS"; })(KeycloakActionsEmailEnum || (exports.KeycloakActionsEmailEnum = KeycloakActionsEmailEnum = {})); let KeycloakAdminService = class KeycloakAdminService { configService; KEYCLOAK_ADMIN_CLIENT_ID; KEYCLOAK_ADMIN_CLIENT_SECRET; KEYCLOAK_REALM; _client; constructor(configService) { this.configService = configService; const keycloakUrl = this.configService.getOrThrow('KEYCLOAK_URL'); this.KEYCLOAK_ADMIN_CLIENT_ID = this.configService.getOrThrow('KEYCLOAK_ADMIN_CLIENT_ID'); this.KEYCLOAK_ADMIN_CLIENT_SECRET = this.configService.getOrThrow('KEYCLOAK_ADMIN_CLIENT_SECRET'); this.KEYCLOAK_REALM = this.configService.getOrThrow('KEYCLOAK_ADMIN_REALM'); this._client = new keycloak_admin_client_cjs_1.KeycloakAdminClient({ baseUrl: keycloakUrl, realmName: this.KEYCLOAK_REALM, }); } async auth() { await this._client.auth({ grantType: 'client_credentials', clientId: this.KEYCLOAK_ADMIN_CLIENT_ID, clientSecret: this.KEYCLOAK_ADMIN_CLIENT_SECRET, }); } async getAccessToken() { let accessToken; try { accessToken = await this._client.getAccessToken(); } catch { } if (!accessToken) { logger.debug('Get an access token'); await this.auth(); } let newAccessToken = accessToken ?? this._client.accessToken; if (newAccessToken === undefined) { throw new Error(`Can't have access_token on keycloak by client_secret method`); } const decodedTokenExpTime = (0, jwt_decode_1.jwtDecode)(newAccessToken)?.exp ?? 0; const nowTmSecond = Math.ceil(Date.now() / 1000) + 2; if (decodedTokenExpTime < nowTmSecond) { logger.debug('Renew a new access token'); await this.auth(); newAccessToken = this._client.accessToken; } else { logger.verbose(`Remain time for this access token : ${decodedTokenExpTime - nowTmSecond} seconds`); } return newAccessToken; } async findAllUsers() { await this.getAccessToken(); logger.verbose('findAllUsers()'); return this._client.users.find(); } async findUserByEmail(email) { await this.getAccessToken(); logger.verbose(`findUserByEmail(email=${email})`); return this._client.users.find({ email }); } async findUserByUsername(username) { await this.getAccessToken(); logger.verbose(`findUserByUsername(username=${username})`); return this._client.users.find({ username }); } async findUserById(id) { await this.getAccessToken(); logger.verbose(`findUserById(id=${id})`); return this._client.users.findOne({ id: id }); } async createUser(email, firstName = undefined, lastName = undefined, username = undefined, attributes = {}) { await this.getAccessToken(); logger.verbose(`createUser(email=${email}, firstName=${firstName}, lastName=${lastName}, username=${username})`); return this._client.users.create({ username, email, firstName, lastName, attributes, enabled: true, emailVerified: true }); } async updateAttributesOfUser(id, user, attributes) { await this.getAccessToken(); await this._client.users.update({ id }, { ...user, attributes, }); } async updateUserPassword(userId, newPassword) { await this.getAccessToken(); await this._client.users.resetPassword({ id: userId, credential: { type: 'password', value: newPassword, temporary: false }, }); } async executeActionsEmail(sub, clientId, lifespan, redirectUri, actions) { await this.getAccessToken(); await this._client.users.executeActionsEmail({ id: sub, clientId, lifespan, redirectUri, actions, }); } }; exports.KeycloakAdminService = KeycloakAdminService; exports.KeycloakAdminService = KeycloakAdminService = __decorate([ (0, common_1.Injectable)(), __metadata("design:paramtypes", [config_1.ConfigService]) ], KeycloakAdminService); //# sourceMappingURL=keycloak-admin.service.js.map