UNPKG

@zigatech/keycloak-auth

Version:

Keycloak authorization library for NestJS. Works out of the box.

47 lines (46 loc) 2.38 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ApiKeyAuth = void 0; const axios_1 = __importDefault(require("axios")); const common_1 = require("@nestjs/common"); const principal_js_1 = require("./principal.js"); const keycloak_auth_js_1 = require("../constant/keycloak.auth.js"); class ApiKeyAuth { constructor(keycloakConfig) { Object.defineProperty(this, "keycloakConfig", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.keycloakConfig = keycloakConfig; } validate(apiKey) { var _a; return __awaiter(this, void 0, void 0, function* () { try { const apiKeyValidationResponse = yield axios_1.default.get(`${this.keycloakConfig.getAuthServerUrl()}/realms/${this.keycloakConfig.getRealm()}/api-keys/validations?key=${apiKey}`); common_1.Logger.log("Api key verified!", keycloak_auth_js_1.KeycloakAuth.NAME); const data = (_a = apiKeyValidationResponse.data) === null || _a === void 0 ? void 0 : _a.data; return new principal_js_1.Principal(data.id, data.email, data.emailVerified, data.lastName, data.firstName, data.phone, data.roles); } catch (e) { common_1.Logger.debug("Api Key verification failed.", keycloak_auth_js_1.KeycloakAuth.NAME); throw new common_1.UnauthorizedException(); } }); } } exports.ApiKeyAuth = ApiKeyAuth;