"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 __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 (_) 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 };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CachedUser = exports.Auth = void 0;
var Crypt_1 = require("./Crypt");
var openflow_api_1 = require("@openiap/openflow-api");
var DBHelper_1 = require("./DBHelper");
var Logger_1 = require("./Logger");
var Config_1 = require("./Config");
var Auth = /** @class */ (function () {
    function Auth() {
    }
    Auth.ValidateByPassword = function (username, password, parent) {
        return __awaiter(this, void 0, void 0, function () {
            var span, user, error_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        span = Logger_1.Logger.otel.startSubSpan("Auth.ValidateByPassword", parent);
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 4, 5, 6]);
                        if (username === null || username === undefined || username === "") {
                            throw Error("Username cannot be null");
                        }
                        span.setAttribute("username", username);
                        if (password === null || password === undefined || password === "") {
                            throw Error("Password cannot be null");
                        }
                        return [4 /*yield*/, DBHelper_1.DBHelper.FindByUsername(username, null, span)];
                    case 2:
                        user = _a.sent();
                        if (user === null || user === undefined) {
                            return [2 /*return*/, null];
                        }
                        return [4 /*yield*/, Crypt_1.Crypt.compare(password, user.passwordhash, span)];
                    case 3:
                        if ((_a.sent()) !== true) {
                            return [2 /*return*/, null];
                        }
                        return [2 /*return*/, user];
                    case 4:
                        error_1 = _a.sent();
                        span.recordException(error_1);
                        throw error_1;
                    case 5:
                        Logger_1.Logger.otel.endSpan(span);
                        return [7 /*endfinally*/];
                    case 6: return [2 /*return*/];
                }
            });
        });
    };
    Auth.getUser = function (key, type) {
        if (openflow_api_1.NoderedUtil.IsNullUndefinded(this.cacheTimer))
            this.cacheTimer = setInterval(this.cleanCache, 60000);
        var res = this.authorizationCache[key + type];
        if (res === null || res === undefined)
            return null;
        var begin = res.firstsignin.getTime();
        var end = new Date().getTime();
        var seconds = Math.round((end - begin) / 1000);
        var cache_seconds = Config_1.Config.api_credential_cache_seconds;
        if (type == "grafana")
            cache_seconds = Config_1.Config.grafana_credential_cache_seconds;
        if (type == "dashboard")
            cache_seconds = Config_1.Config.dashboard_credential_cache_seconds;
        if (type == "cleanacl")
            cache_seconds = Config_1.Config.cleanacl_credential_cache_seconds;
        if (seconds < cache_seconds) {
            // Logger.instanse.info("Return user " + res.user.username + " from cache");
            return res.user;
        }
        this.RemoveUser(key, type);
        return null;
    };
    Auth.cleanCache = function () {
        return __awaiter(this, void 0, void 0, function () {
            var keys, i, key, res, begin, end, seconds, cache_seconds;
            return __generator(this, function (_a) {
                try {
                    if (this.authorizationCache == null)
                        return [2 /*return*/];
                    keys = Object.keys(this.authorizationCache);
                    for (i = keys.length - 1; i >= 0; i--) {
                        key = keys[i];
                        res = this.authorizationCache[key];
                        if (res === null || res === undefined)
                            continue;
                        begin = res.firstsignin.getTime();
                        end = new Date().getTime();
                        seconds = Math.round((end - begin) / 1000);
                        cache_seconds = Config_1.Config.api_credential_cache_seconds;
                        if (res.type == "grafana")
                            cache_seconds = Config_1.Config.grafana_credential_cache_seconds;
                        if (res.type == "dashboard")
                            cache_seconds = Config_1.Config.dashboard_credential_cache_seconds;
                        if (res.type == "cleanacl")
                            cache_seconds = Config_1.Config.cleanacl_credential_cache_seconds;
                        if (seconds >= cache_seconds) {
                            this.RemoveUser(key, res.type);
                        }
                    }
                }
                catch (error) {
                    Logger_1.Logger.instanse.error(error);
                }
                return [2 /*return*/];
            });
        });
    };
    Auth.RemoveUser = function (key, type) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, semaphore.down()];
                    case 1:
                        _a.sent();
                        if (!openflow_api_1.NoderedUtil.IsNullUndefinded(this.authorizationCache[key + type])) {
                            Logger_1.Logger.instanse.info("Delete user with key " + key + " from cache");
                            delete this.authorizationCache[key + type];
                        }
                        semaphore.up();
                        return [2 /*return*/];
                }
            });
        });
    };
    Auth.AddUser = function (user, key, type) {
        return __awaiter(this, void 0, void 0, function () {
            var cuser;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, semaphore.down()];
                    case 1:
                        _a.sent();
                        if (openflow_api_1.NoderedUtil.IsNullUndefinded(this.authorizationCache[key + type])) {
                            Logger_1.Logger.instanse.info("Adding user " + user.name + " to cache with key " + key);
                            cuser = new CachedUser(user, user._id, type);
                            this.authorizationCache[key + type] = cuser;
                        }
                        semaphore.up();
                        return [2 /*return*/];
                }
            });
        });
    };
    Auth.authorizationCache = {};
    return Auth;
}());
exports.Auth = Auth;
var CachedUser = /** @class */ (function () {
    function CachedUser(user, _id, type) {
        this.user = user;
        this._id = _id;
        this.type = type;
        this.firstsignin = new Date();
    }
    return CachedUser;
}());
exports.CachedUser = CachedUser;
var Semaphore = function (n) { return ({
    n: n,
    down: function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(this.n <= 0)) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.wait()];
                    case 1:
                        _a.sent();
                        return [3 /*break*/, 0];
                    case 2:
                        this.n--;
                        return [2 /*return*/];
                }
            });
        });
    },
    up: function () {
        this.n++;
    },
    wait: function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(this.n <= 0)) return [3 /*break*/, 2];
                        return [4 /*yield*/, new Promise(function (res, req) {
                                setImmediate(function () { return __awaiter(_this, void 0, void 0, function () { var _a; return __generator(this, function (_b) {
                                    switch (_b.label) {
                                        case 0:
                                            _a = res;
                                            return [4 /*yield*/, this.wait()];
                                        case 1: return [2 /*return*/, _a.apply(void 0, [_b.sent()])];
                                    }
                                }); }); });
                            })];
                    case 1: return [2 /*return*/, _a.sent()];
                    case 2: return [2 /*return*/];
                }
            });
        });
    },
}); };
var semaphore = Semaphore(1);
//# sourceMappingURL=Auth.js.map