var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
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 __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 __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
import { Router } from 'aurelia-router';
import { HttpClient } from 'aurelia-fetch-client';
import * as msal from "@azure/msal-browser";
import { autoinject } from 'aurelia-framework';
import { AuthService } from './auth-service';
import { Datacontext } from '../data/data-context';
import { Config } from '../config';
import { UIInternal } from '../utils/ui-internal';
export var B2CAuthService = (function (_super) {
    __extends(B2CAuthService, _super);
    function B2CAuthService(dataContext, config, httpClient, router) {
        var _this = _super.call(this, config) || this;
        _this.dataContext = dataContext;
        _this.httpClient = httpClient;
        _this.router = router;
        _this.msalConfig = {
            auth: {
                clientId: _this.config.b2cConfig.clientId,
                redirectUri: _this.config.b2cConfig.redirectUri,
                authority: _this.config.b2cConfig.authorities.signin,
                knownAuthorities: [_this.config.b2cConfig.authorityDomain],
                navigateToLoginRequestUrl: false
            },
            cache: {
                cacheLocation: "localStorage",
                storeAuthStateInCookie: false,
            },
            system: {
                loggerOptions: {
                    loggerCallback: function (level, message, containsPii) {
                        if (containsPii) {
                            return;
                        }
                        switch (level) {
                            case msal.LogLevel.Error:
                                console.error(message);
                                return;
                            case msal.LogLevel.Info:
                                console.info(message);
                                return;
                            case msal.LogLevel.Verbose:
                                console.debug(message);
                                return;
                            case msal.LogLevel.Warning:
                                console.warn(message);
                                return;
                        }
                    }
                }
            }
        };
        _this.tokenRequest = {
            scopes: __spreadArray([], __read(_this.config.b2cConfig.scopes), false),
            forceRefresh: true
        };
        _this.loginRequest = {
            scopes: __spreadArray(["openid"], __read(_this.config.b2cConfig.scopes), false),
            prompt: 'consent'
        };
        _this.msalInstance = new msal.PublicClientApplication(_this.msalConfig);
        return _this;
    }
    Object.defineProperty(B2CAuthService.prototype, "usernameType", {
        get: function () {
            return "email";
        },
        enumerable: false,
        configurable: true
    });
    B2CAuthService.prototype.addBearerTokenToHttpClient = function () {
        var _this = this;
        var requestFn = function (message) { return __awaiter(_this, void 0, void 0, function () {
            var token, error_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 4, , 5]);
                        if (!this.requestRequiresAuth(message)) return [3, 3];
                        if (!this.isAuthenticated()) return [3, 2];
                        return [4, this.accessToken()];
                    case 1:
                        token = _a.sent();
                        console.log('append token to header : ' + token);
                        message.headers.append('Authorization', "Bearer ".concat(token));
                        _a.label = 2;
                    case 2: return [2, message];
                    case 3: return [2, message];
                    case 4:
                        error_1 = _a.sent();
                        console.log(error_1);
                        return [3, 5];
                    case 5: return [2];
                }
            });
        }); };
        this.httpClient.configure(function (config) {
            config
                .withInterceptor({
                request: requestFn
            });
        });
    };
    B2CAuthService.prototype.accessToken = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!!this.token) return [3, 2];
                        return [4, this.getTokenRedirect(this.tokenRequest)];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2, this.token];
                }
            });
        });
    };
    B2CAuthService.prototype.getTokenRedirect = function (request) {
        return __awaiter(this, void 0, void 0, function () {
            var response, error_2;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        request.account = this.msalInstance.getActiveAccount();
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 7]);
                        return [4, this.msalInstance.acquireTokenSilent(request)];
                    case 2:
                        response = _a.sent();
                        if (!response.accessToken || response.accessToken === "") {
                            throw new msal.InteractionRequiredAuthError;
                        }
                        else {
                            this.token = response.accessToken;
                            return [2, true];
                        }
                        return [3, 7];
                    case 3:
                        error_2 = _a.sent();
                        console.log("Silent token acquisition fails. Acquiring token using popup. \n", error_2);
                        if (!(error_2 instanceof msal.InteractionRequiredAuthError)) return [3, 5];
                        return [4, this.msalInstance.acquireTokenRedirect(request).catch(function (redirectError) {
                                console.error(redirectError);
                                _this.msalInstance.logoutRedirect({
                                    postLogoutRedirectUri: 'https://localhost:5001/logout'
                                });
                                return false;
                            })];
                    case 4:
                        _a.sent();
                        return [2, false];
                    case 5:
                        console.error(error_2);
                        return [2, false];
                    case 6: return [3, 7];
                    case 7: return [2];
                }
            });
        });
    };
    B2CAuthService.prototype.navigateToSavedInstruction = function () {
        var savedLocation = JSON.parse(sessionStorage.getItem('location'));
        var navigateTarget = (savedLocation === null || savedLocation === void 0 ? void 0 : savedLocation.url) || 'watchlist';
        sessionStorage.removeItem('location');
        this.router.navigate(navigateTarget);
    };
    B2CAuthService.prototype.login = function (navInstruction) {
        return __awaiter(this, void 0, void 0, function () {
            var response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.msalInstance.handleRedirectPromise()];
                    case 1:
                        response = _a.sent();
                        if (!(response == null)) return [3, 2];
                        console.log('login : no user authenticated, call loginRedirect');
                        sessionStorage.setItem('location', JSON.stringify({ url: navInstruction }));
                        this.msalInstance.loginRedirect(this.loginRequest);
                        return [3, 4];
                    case 2:
                        console.log('login : a user is already authenticated');
                        console.log(response);
                        return [4, this.handleResponse(response)];
                    case 3:
                        _a.sent();
                        _a.label = 4;
                    case 4: return [2];
                }
            });
        });
    };
    B2CAuthService.prototype.logout = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.msalInstance.logoutRedirect()];
                    case 1:
                        _a.sent();
                        return [2];
                }
            });
        });
    };
    B2CAuthService.prototype.equalsIgnoreOrder = function (a, b) {
        var e_1, _a;
        if (a.length !== b.length)
            return false;
        var uniqueValues = new (Array.bind.apply(Array, __spreadArray(__spreadArray([void 0], __read(a), false), __read(b), false)))();
        var _loop_1 = function (v) {
            var aCount = a.filter(function (e) { return e === v; }).length;
            var bCount = b.filter(function (e) { return e === v; }).length;
            if (aCount !== bCount)
                return { value: false };
        };
        try {
            for (var uniqueValues_1 = __values(uniqueValues), uniqueValues_1_1 = uniqueValues_1.next(); !uniqueValues_1_1.done; uniqueValues_1_1 = uniqueValues_1.next()) {
                var v = uniqueValues_1_1.value;
                var state_1 = _loop_1(v);
                if (typeof state_1 === "object")
                    return state_1.value;
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (uniqueValues_1_1 && !uniqueValues_1_1.done && (_a = uniqueValues_1.return)) _a.call(uniqueValues_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
        return true;
    };
    B2CAuthService.prototype.handleResponse = function (response) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var policyIdClaimName, _b, _c;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        if (!(response !== null)) return [3, 5];
                        policyIdClaimName = void 0;
                        if (Object.keys(response.idTokenClaims).indexOf('tfp') > -1) {
                            policyIdClaimName = 'tfp';
                        }
                        if (policyIdClaimName == null && Object.keys(response.idTokenClaims).indexOf('acr') > -1) {
                            policyIdClaimName = 'acr';
                        }
                        if (policyIdClaimName == null) {
                            throw Error('Cannot detect tfp or acr claim in authentication response');
                        }
                        if (!(response.idTokenClaims[policyIdClaimName].toUpperCase() === this.config.b2cConfig.names.signUpSignIn.toUpperCase())) return [3, 4];
                        if (!this.equalsIgnoreOrder(response.scopes, this.tokenRequest.scopes)) {
                            alert('Access refused!');
                            this.msalInstance.logoutRedirect();
                        }
                        this.msalInstance.setActiveAccount(response.account);
                        _b = this;
                        if (!response.hasOwnProperty('accessToken')) return [3, 1];
                        _c = response.accessToken;
                        return [3, 3];
                    case 1: return [4, this.accessToken()];
                    case 2:
                        _c = _d.sent();
                        _d.label = 3;
                    case 3:
                        _b.token = _c;
                        if (((_a = this.token) === null || _a === void 0 ? void 0 : _a.length) > 0) {
                            UIInternal.broadcast(UIInternal.EVT_AUTH_CHANGE, { authenticated: true });
                        }
                        _d.label = 4;
                    case 4: return [3, 5];
                    case 5: return [2];
                }
            });
        });
    };
    B2CAuthService.prototype.handleAuthentication = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response, error_3;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        console.warn('handleAuthentication');
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 4, , 5]);
                        return [4, this.msalInstance.handleRedirectPromise()];
                    case 2:
                        response = _a.sent();
                        return [4, this.handleResponse(response)];
                    case 3:
                        _a.sent();
                        return [3, 5];
                    case 4:
                        error_3 = _a.sent();
                        console.error(error_3);
                        return [3, 5];
                    case 5: return [2];
                }
            });
        });
    };
    B2CAuthService.prototype.isAuthenticated = function () {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var ret;
            return __generator(this, function (_b) {
                if (this.msalInstance.getActiveAccount() == null) {
                    console.log('isAuthenticated : return false');
                    return [2, false];
                }
                else {
                    ret = ((_a = this.token) === null || _a === void 0 ? void 0 : _a.length) > 0;
                    console.log("isAuthenticated : return ".concat(ret));
                    return [2, ret];
                }
                return [2];
            });
        });
    };
    B2CAuthService.prototype.checkAccess = function (resource, action) {
        return true;
    };
    B2CAuthService.prototype.getProfile = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = this;
                        return [4, this.dataContext.getCurrentUserProfile()];
                    case 1:
                        _a.currentUser = _b.sent();
                        return [2];
                }
            });
        });
    };
    B2CAuthService.prototype.onUserPermissionsChanged = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2];
            });
        });
    };
    B2CAuthService = __decorate([
        autoinject,
        __metadata("design:paramtypes", [Datacontext, Config, HttpClient, Router])
    ], B2CAuthService);
    return B2CAuthService;
}(AuthService));

//# sourceMappingURL=b2c-auth-service.js.map
