"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AppAuthorizationProvider = void 0;
const tslib_1 = require("tslib");
const authentication_jwt_1 = require("@loopback/authentication-jwt");
const core_1 = require("@loopback/core");
const rest_1 = require("@loopback/rest");
const security_1 = require("@loopback/security");
const access_rights_service_1 = require("./access-rights/access-rights.service");
const application_service_1 = require("./application.service");
/*
 * Fix the service type. Possible options can be:
 * - import {AppAuthorization} from 'your-module';
 * - export type AppAuthorization = string;
 * - export interface AppAuthorization {}
 */
let AppAuthorizationProvider = class AppAuthorizationProvider {
    constructor(ctx, accessRightsService, user, request, jwtService) {
        this.ctx = ctx;
        this.accessRightsService = accessRightsService;
        this.user = user;
        this.request = request;
        this.jwtService = jwtService;
    }
    value() {
        return this.authorize.bind(this);
    }
    async authorize(context, metadata) {
        var _a;
        this.ctx.accessRightsContext.authorization.value = ('null' ===
            this.request.headers.authorization ||
            'undefined' === this.request.headers.authorization ||
            !this.request.headers.authorization
            ? undefined
            : this.request.headers.authorization);
        if (!this.user) {
            try {
                this.user = (await new authentication_jwt_1.JWTAuthenticationStrategy(this.jwtService).authenticate(this.request));
                context.principals[0] = {
                    ...this.user,
                    name: (_a = this.user.name) !== null && _a !== void 0 ? _a : this.user[security_1.securityId],
                    type: 'USER',
                };
                // eslint-disable-next-line no-empty
            }
            catch (error) { }
        }
        return this.accessRightsService.authorize(this.ctx, context, metadata);
    }
};
AppAuthorizationProvider = tslib_1.__decorate([
    tslib_1.__param(0, core_1.inject(application_service_1.CURRENT_CONTEXT)),
    tslib_1.__param(1, core_1.service(access_rights_service_1.AccessRightsService)),
    tslib_1.__param(2, core_1.inject(security_1.SecurityBindings.USER, { optional: true })),
    tslib_1.__param(3, core_1.inject(rest_1.RestBindings.Http.REQUEST)),
    tslib_1.__param(4, core_1.inject(authentication_jwt_1.TokenServiceBindings.TOKEN_SERVICE)),
    tslib_1.__metadata("design:paramtypes", [application_service_1.CurrentContext,
        access_rights_service_1.AccessRightsService, Object, Object, Object])
], AppAuthorizationProvider);
exports.AppAuthorizationProvider = AppAuthorizationProvider;
//# sourceMappingURL=app-authorization.service.js.map