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 };
    }
};
import { Box } from './../modules/box';
import { HttpClient } from 'aurelia-fetch-client';
import { Auth0Client } from '@auth0/auth0-spa-js';
import { Aurelia, Container, inject } from "aurelia-framework";
import { Router } from "aurelia-router";
import { Datacontext } from '../data/data-context';
import { Config } from '../config';
import { BaseOAuthService, OAuthClientWrapper } from './oauth-service';
import { I18N } from 'aurelia-i18n';
import { UIInternal } from '../utils/ui-internal';
var LOGIN_LOOP_DETECTION = 'LOGIN_LOOP_DETECTION';
var LOGIN_LOOP_DETECTION_LIMIT = 2;
var Auth0ClientWrapper = (function (_super) {
    __extends(Auth0ClientWrapper, _super);
    function Auth0ClientWrapper() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Auth0ClientWrapper.prototype.init = function () {
        return __awaiter(this, void 0, void 0, function () {
            var e_1, loginLoopDetectionValue, loginLoopDetectionCounter, i18n, t;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.client = new Auth0Client({
                            domain: this.config.domain,
                            clientId: this.config.clientId,
                            cacheLocation: this.getCacheLocation(),
                            authorizationParams: {
                                redirect_uri: this.config.callback_uri,
                                audience: this.config.audience,
                                scope: "openid profile",
                                ui_locales: "fr en nl",
                            }
                        });
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 9]);
                        return [4, this.accessToken()];
                    case 2:
                        _a.sent();
                        sessionStorage.removeItem(LOGIN_LOOP_DETECTION);
                        return [3, 9];
                    case 3:
                        e_1 = _a.sent();
                        if (!(['missing_refresh_token', 'invalid_grant', 'login_required'].indexOf(e_1.error) >= 0)) return [3, 7];
                        loginLoopDetectionValue = sessionStorage.getItem(LOGIN_LOOP_DETECTION);
                        loginLoopDetectionCounter = loginLoopDetectionValue == null ? 0 : parseInt(loginLoopDetectionValue);
                        if (!(++loginLoopDetectionCounter > LOGIN_LOOP_DETECTION_LIMIT)) return [3, 6];
                        i18n = Container.instance.get(I18N);
                        return [4, UIInternal.autoDetectAndSetLocale(i18n)];
                    case 4:
                        t = _a.sent();
                        return [4, Container.instance.get(Box)
                                .showError(t('common:clientExceptions.auth0LoginLoop.message'), t('common:clientExceptions.auth0LoginLoop.title'), null, false, true)
                                .whenClosed(function () { })];
                    case 5:
                        _a.sent();
                        loginLoopDetectionCounter = 0;
                        _a.label = 6;
                    case 6:
                        sessionStorage.setItem(LOGIN_LOOP_DETECTION, loginLoopDetectionCounter.toString());
                        this.login();
                        return [3, 8];
                    case 7: throw e_1;
                    case 8: return [3, 9];
                    case 9: return [2, this];
                }
            });
        });
    };
    Auth0ClientWrapper.prototype.accessToken = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.client.getTokenSilently()];
                    case 1: return [2, _a.sent()];
                }
            });
        });
    };
    Auth0ClientWrapper.prototype.loginWithRedirect = function () {
        var _a, _b;
        return this.client.loginWithRedirect({
            authorizationParams: {
                redirect_uri: this.config.callback_uri,
                scope: 'all app_metadata ',
                ui_locales: (_b = (_a = navigator === null || navigator === void 0 ? void 0 : navigator.language) === null || _a === void 0 ? void 0 : _a.slice(0, 2)) !== null && _b !== void 0 ? _b : "fr"
            }
        });
    };
    Auth0ClientWrapper.prototype.handleSignInRedirect = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.client.handleRedirectCallback()];
                    case 1:
                        _a.sent();
                        return [2];
                }
            });
        });
    };
    Auth0ClientWrapper.prototype.isAuthenticated = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.client.isAuthenticated()];
                    case 1: return [2, _a.sent()];
                }
            });
        });
    };
    Auth0ClientWrapper.prototype.logout = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                this.client.logout({
                    logoutParams: { returnTo: this.config.logout_uri }
                });
                return [2];
            });
        });
    };
    Auth0ClientWrapper.prototype.getUserProfile = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.client.getUser()];
                    case 1: return [2, _a.sent()];
                }
            });
        });
    };
    Auth0ClientWrapper.prototype.getCacheLocation = function () {
        var cacheLocation = this.isBrowserBuiltOnChromium() ? 'memory' : 'localstorage';
        if (this.cacheLocationCanBeOverwriten(cacheLocation)) {
            cacheLocation = this.config.cacheLocation;
        }
        return cacheLocation;
    };
    Auth0ClientWrapper.prototype.isBrowserBuiltOnChromium = function () {
        return !!window.chrome;
    };
    Auth0ClientWrapper.prototype.cacheLocationCanBeOverwriten = function (cacheLocation) {
        var _a, _b;
        return (((_a = this.config) === null || _a === void 0 ? void 0 : _a.cacheLocation) === 'localstorage' || ((_b = this.config) === null || _b === void 0 ? void 0 : _b.cacheLocation) === 'memory') && this.config.cacheLocation !== cacheLocation;
    };
    return Auth0ClientWrapper;
}(OAuthClientWrapper));
export var Auth0Service = (function (_super) {
    __extends(Auth0Service, _super);
    function Auth0Service(router, app, dataContext, config, httpClient) {
        return _super.call(this, router, app, dataContext, config, httpClient) || this;
    }
    Auth0Service.prototype.makeClient = function () {
        return new Auth0ClientWrapper(this.config.authConfig).init();
    };
    Object.defineProperty(Auth0Service.prototype, "usernameType", {
        get: function () {
            return "email";
        },
        enumerable: false,
        configurable: true
    });
    Auth0Service.prototype.onUserPermissionsChanged = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2];
            });
        });
    };
    Auth0Service = __decorate([
        inject(Router, Aurelia, Datacontext, Config, HttpClient),
        __metadata("design:paramtypes", [Router, Aurelia, Datacontext, Config, HttpClient])
    ], Auth0Service);
    return Auth0Service;
}(BaseOAuthService));

//# sourceMappingURL=auth0-service.js.map
