"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.CachedToken = exports.OAuthProvider = void 0;
var OAuthServer = require("oauth2-server");
var openflow_api_1 = require("@openiap/openflow-api");
var Config_1 = require("./Config");
var Crypt_1 = require("./Crypt");
var Request = OAuthServer.Request;
var Response = OAuthServer.Response;
var OAuthProvider = /** @class */ (function () {
    function OAuthProvider() {
        this.clients = [];
        this.codes = {};
        this.oauthServer = null;
        this.authorizationCodeStore = {};
    }
    OAuthProvider.configure = function (logger, app) {
        var _this = this;
        var instance = new OAuthProvider();
        try {
            OAuthProvider.instance = instance;
            instance._logger = logger;
            instance.app = app;
            instance.oauthServer = new OAuthServer({
                model: instance,
                grants: ['authorization_code', 'refresh_token'],
                accessTokenLifetime: (60 * 60 * 24) * 7,
                refreshTokenLifetime: (60 * 60 * 24) * 7,
                allowEmptyState: true,
                allowExtendedTokenAttributes: true,
                allowBearerTokensInQueryString: true
            });
            Config_1.Config.db.query({ _type: "oauthclient" }, null, 10, 0, null, "config", Crypt_1.Crypt.rootToken()).then(function (result) {
                instance.clients = result;
            }).catch(function (error) {
                instance._logger.error(error);
            });
            app.oauth = instance.oauthServer;
            app.all('/oauth/token', instance.obtainToken.bind(instance));
            app.get('/oauth/login', function (req, res) { return __awaiter(_this, void 0, void 0, function () {
                var _a, state, access_type, client_id, redirect_uri, response_type, scope, client, _b, code;
                return __generator(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            if (!openflow_api_1.NoderedUtil.IsNullUndefinded(instance.clients)) return [3 /*break*/, 2];
                            _a = instance;
                            return [4 /*yield*/, Config_1.Config.db.query({ _type: "oauthclient" }, null, 10, 0, null, "config", Crypt_1.Crypt.rootToken())];
                        case 1:
                            _a.clients = _c.sent();
                            if (instance.clients == null || instance.clients.length == 0)
                                return [2 /*return*/, res.status(500).json({ message: 'OAuth not configured' })];
                            _c.label = 2;
                        case 2:
                            state = (req.params.state ? req.params.state : req.params["amp;state"]);
                            if (state == null)
                                state = encodeURIComponent((req.query.state ? req.query.state : req.query["amp;state"]));
                            access_type = (req.query.access_type ? req.query.access_type : req.query["amp;access_type"]);
                            client_id = (req.query.client_id ? req.query.client_id : req.query["amp;client_id"]);
                            redirect_uri = (req.query.redirect_uri ? req.query.redirect_uri : req.query["amp;redirect_uri"]);
                            response_type = (req.query.response_type ? req.query.response_type : req.query["amp;response_type"]);
                            scope = (req.query.scope ? req.query.scope : req.query["amp;scope"]);
                            client = instance.getClientById(client_id);
                            if (!openflow_api_1.NoderedUtil.IsNullUndefinded(client)) return [3 /*break*/, 4];
                            _b = instance;
                            return [4 /*yield*/, Config_1.Config.db.query({ _type: "oauthclient" }, null, 10, 0, null, "config", Crypt_1.Crypt.rootToken())];
                        case 3:
                            _b.clients = _c.sent();
                            if (instance.clients == null || instance.clients.length == 0)
                                return [2 /*return*/, res.status(500).json({ message: 'OAuth not configured' })];
                            _c.label = 4;
                        case 4:
                            if (req.user) {
                                if (!openflow_api_1.NoderedUtil.IsNullUndefinded(client) && !Array.isArray(client.redirectUris)) {
                                    client.redirectUris = [];
                                }
                                if (!openflow_api_1.NoderedUtil.IsNullUndefinded(client) && client.redirectUris.length > 0) {
                                    if (client.redirectUris.indexOf(redirect_uri) == -1) {
                                        return [2 /*return*/, res.status(500).json({ message: 'illegal redirect_uri ' + redirect_uri })];
                                        // client.redirectUris.push(redirect_uri);
                                    }
                                }
                                code = Math.random().toString(36).substr(2, 9);
                                instance._logger.info("[OAuth][" + req.user.username + "] /oauth/login " + state);
                                instance.saveAuthorizationCode(code, client, req.user, redirect_uri);
                                res.redirect(redirect_uri + "?state=" + state + "&code=" + code);
                            }
                            else {
                                instance._logger.info("[OAuth][anon] /oauth/login " + state);
                                res.cookie("originalUrl", req.originalUrl, { maxAge: 900000, httpOnly: true });
                                res.redirect("/login");
                            }
                            return [2 /*return*/];
                    }
                });
            }); });
            // app.get('/oauth/authorize', instance.authorize.bind(instance));
            app.all('/oauth/authorize', function (req, res) {
                var request = new Request(req);
                var response = new Response(res);
                return instance.oauthServer.authenticate(request, response)
                    .then(function (token) {
                    res.json(token.user);
                }).catch(function (err) {
                    console.error(err);
                    res.status(err.code || 500).json(err);
                });
            });
            // app.all('/oauth/authorize', instance.oauthServer.authenticate.bind(instance));
            // app.all('/oauth/authorize/emails', instance.oauthServer.authenticate.bind(instance));
        }
        catch (error) {
            console.error(error);
            var json = JSON.stringify(error, null, 3);
            console.error(json);
            throw error;
        }
        return instance;
    };
    OAuthProvider.prototype.authorize = function (req, res) {
        this._logger.info("[OAuth] authorize");
        var request = new Request(req);
        var response = new Response(res);
        console.log(request.headers);
        return this.oauthServer.authorize(request, response)
            .then(function (token) {
            res.json(token);
        }).catch(function (err) {
            console.error(err);
            res.status(err.code || 500).json(err);
        });
    };
    OAuthProvider.prototype.authenticateHandler = function () {
        return {
            handle: function (request, response) {
                //in this example, we store the logged-in user as the 'loginUser' attribute in session
                if (request.session.loginUser) {
                    return { username: request.session.loginUser.username };
                }
                return null;
            }
        };
    };
    OAuthProvider.prototype.obtainToken = function (req, res) {
        var _this = this;
        this._logger.info("[OAuth] obtainToken");
        var request = new Request(req);
        var response = new Response(res);
        return this.oauthServer.token(request, response)
            .then(function (token) {
            _this._logger.info("[OAuth] obtainToken::success: token:");
            res.json(token);
        }).catch(function (err) {
            _this._logger.info("[OAuth] obtainToken::failed: token:");
            console.error(err);
            res.status(err.code || 500).json(err);
        });
    };
    OAuthProvider.prototype.getAccessToken = function (accessToken) {
        return __awaiter(this, void 0, void 0, function () {
            var token, tokens;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this._logger.info("[OAuth] getAccessToken " + accessToken);
                        return [4 /*yield*/, OAuthProvider.getCachedAccessToken(accessToken)];
                    case 1:
                        token = _a.sent();
                        if (token != null)
                            return [2 /*return*/, token];
                        return [4 /*yield*/, Config_1.Config.db.query({ _type: "token", "accessToken": accessToken }, null, 10, 0, null, "oauthtokens", Crypt_1.Crypt.rootToken())];
                    case 2:
                        tokens = _a.sent();
                        token = tokens.length ? tokens[0] : null;
                        return [4 /*yield*/, OAuthProvider.addToken(token)];
                    case 3:
                        _a.sent();
                        if (token == null)
                            return [2 /*return*/, false];
                        return [2 /*return*/, token];
                }
            });
        });
    };
    OAuthProvider.prototype.getRefreshToken = function (refreshToken) {
        return __awaiter(this, void 0, void 0, function () {
            var token, tokens;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this._logger.info("[OAuth] getRefreshToken " + refreshToken);
                        return [4 /*yield*/, OAuthProvider.getCachedAccessToken(refreshToken)];
                    case 1:
                        token = _a.sent();
                        if (token != null)
                            return [2 /*return*/, token];
                        return [4 /*yield*/, Config_1.Config.db.query({ _type: "token", "refreshToken": refreshToken }, null, 10, 0, null, "oauthtokens", Crypt_1.Crypt.rootToken())];
                    case 2:
                        tokens = _a.sent();
                        token = tokens.length ? tokens[0] : null;
                        return [4 /*yield*/, OAuthProvider.addToken(token)];
                    case 3:
                        _a.sent();
                        if (token == null)
                            return [2 /*return*/, false];
                        return [2 /*return*/, token];
                }
            });
        });
    };
    OAuthProvider.prototype.getClient = function (clientId, clientSecret) {
        this._logger.info("[OAuth] getClient " + clientId);
        var clients = this.clients.filter(function (client) {
            return client.clientId === clientId && client.clientSecret === clientSecret;
        });
        return clients.length ? clients[0] : false;
    };
    OAuthProvider.prototype.getClientById = function (clientId) {
        this._logger.info("[OAuth] getClientById " + clientId);
        var clients = this.clients.filter(function (client) {
            return client.clientId === clientId;
        });
        return clients.length ? clients[0] : null;
    };
    OAuthProvider.prototype.saveToken = function (token, client, user) {
        return __awaiter(this, void 0, void 0, function () {
            var result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this._logger.info("[OAuth] saveToken for " + user.name + " in " + client.clientId);
                        result = {
                            name: "Token for " + user.name,
                            accessToken: token.accessToken,
                            access_token: token.accessToken,
                            accessTokenExpiresAt: token.accessTokenExpiresAt,
                            clientId: client.clientId,
                            refreshToken: token.refreshToken,
                            refresh_token: token.refreshToken,
                            refreshTokenExpiresAt: token.refreshTokenExpiresAt,
                            userId: user.id,
                            user: user,
                            client: client,
                            _type: "token"
                        };
                        return [4 /*yield*/, OAuthProvider.addToken(result)];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, Config_1.Config.db.InsertOne(result, "oauthtokens", 0, false, Crypt_1.Crypt.rootToken())];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, result];
                }
            });
        });
    };
    OAuthProvider.prototype.saveAuthorizationCode = function (code, client, user, redirect_uri) {
        return __awaiter(this, void 0, void 0, function () {
            var codeobject;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this._logger.info("[OAuth] saveAuthorizationCode " + code);
                        codeobject = Object.assign({}, user);
                        delete codeobject._id;
                        codeobject._type = 'code';
                        codeobject.code = code;
                        codeobject.id = user._id;
                        codeobject.username = user.username;
                        codeobject.email = user.email;
                        if (openflow_api_1.NoderedUtil.IsNullEmpty(codeobject.email))
                            codeobject.email = user.username;
                        codeobject.fullname = user.name;
                        codeobject.redirect_uri = redirect_uri;
                        codeobject.client_id = client.clientId;
                        codeobject.name = "Code " + code + " for " + user.name;
                        this.codes[code] = codeobject;
                        return [4 /*yield*/, Config_1.Config.db.InsertOne(codeobject, "oauthtokens", 1, false, Crypt_1.Crypt.rootToken())];
                    case 1:
                        _a.sent();
                        this._logger.info("[OAuth] saveAuthorizationCode " + code + " saved");
                        // instance.codes[code].client_id = client_id;
                        // await Config.db.InsertOne(result, "oauthtokens", 0, false, Crypt.rootToken());
                        // // const codeToSave: any = this.codes[code];
                        // const codeToSave: any = {
                        //     'authorizationCode': code.authorizationCode,
                        //     'expiresAt': code.expiresAt,
                        //     'redirectUri': code.redirectUri,
                        //     'scope': code.scope,
                        //     'client': client.id,
                        //     'user': user.username
                        // };
                        // this.codes[code] = codeToSave;
                        // this.revokeAuthorizationCode(code);
                        // code = Object.assign({}, code, {
                        //     'client': client.id,
                        //     'user': user.username
                        // });
                        return [2 /*return*/, codeobject];
                }
            });
        });
    };
    OAuthProvider.prototype.sleep = function (ms) {
        return new Promise(function (resolve) {
            setTimeout(resolve, ms);
        });
    };
    OAuthProvider.prototype.getAuthorizationCode = function (code) {
        return __awaiter(this, void 0, void 0, function () {
            var user, users, client_id, redirect_uri, expiresAt, tuser, client, role, keys, i, result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this._logger.info("[OAuth] getAuthorizationCode " + code);
                        user = this.codes[code];
                        if (!(user == null)) return [3 /*break*/, 8];
                        return [4 /*yield*/, Config_1.Config.db.query({ _type: "code", "code": code }, null, 10, 0, null, "oauthtokens", Crypt_1.Crypt.rootToken())];
                    case 1:
                        users = _a.sent();
                        user = users.length ? users[0] : null;
                        if (!(user == null)) return [3 /*break*/, 4];
                        return [4 /*yield*/, this.sleep(1000)];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, Config_1.Config.db.query({ _type: "code", "code": code }, null, 10, 0, null, "oauthtokens", Crypt_1.Crypt.rootToken())];
                    case 3:
                        users = _a.sent();
                        user = users.length ? users[0] : null;
                        _a.label = 4;
                    case 4:
                        if (!(user == null)) return [3 /*break*/, 7];
                        return [4 /*yield*/, this.sleep(1000)];
                    case 5:
                        _a.sent();
                        return [4 /*yield*/, Config_1.Config.db.query({ _type: "code", "code": code }, null, 10, 0, null, "oauthtokens", Crypt_1.Crypt.rootToken())];
                    case 6:
                        users = _a.sent();
                        user = users.length ? users[0] : null;
                        _a.label = 7;
                    case 7:
                        if (user == null) {
                            this._logger.error("[OAuth] getAuthorizationCode, unkown code '" + code + "'");
                            return [2 /*return*/, null];
                        }
                        if (user != null) {
                            this.codes[code] = user;
                        }
                        _a.label = 8;
                    case 8:
                        client_id = this.codes[code].client_id;
                        if (user == null)
                            return [2 /*return*/, null];
                        this.revokeAuthorizationCode(code);
                        redirect_uri = user.redirect_uri;
                        expiresAt = new Date((new Date).getTime() + (1000 * Config_1.Config.oauth_access_token_lifetime));
                        tuser = openflow_api_1.TokenUser.From(user);
                        client = this.getClientById(client_id);
                        if (openflow_api_1.NoderedUtil.IsNullUndefinded(client))
                            return [2 /*return*/, null];
                        role = client.defaultrole;
                        keys = Object.keys(client.rolemappings);
                        for (i = 0; i < keys.length; i++) {
                            if (tuser.HasRoleName(keys[i]))
                                role = client.rolemappings[keys[i]];
                        }
                        result = {
                            code: code,
                            client: this.clients[0],
                            user: {
                                id: user.id,
                                _id: user.id,
                                name: user.fullname,
                                username: user.username,
                                email: user.username,
                                role: role
                            },
                            expiresAt: expiresAt,
                            redirectUri: redirect_uri
                        };
                        // node-bb username hack
                        if (result.user.name == result.user.email && result.user.email.indexOf("@") > -1) {
                            result.user.name = result.user.email.substr(0, result.user.email.indexOf("@") - 1);
                        }
                        if (result.user.name == result.user.email && result.user.email.indexOf("@") == -1) {
                            result.user.email = result.user.email + "@unknown.local";
                        }
                        if (result.user.name == result.user.email) {
                            result.user.name = "user " + result.user.email;
                        }
                        return [2 /*return*/, result];
                }
            });
        });
    };
    OAuthProvider.prototype.revokeAuthorizationCode = function (code) {
        return __awaiter(this, void 0, void 0, function () {
            var refreshTokenExpiresAt, accessTokenExpiresAt, codeExpiresAt;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (typeof code !== "string") {
                            code = code.code;
                        }
                        this._logger.info("[OAuth] revokeAuthorizationCode " + code);
                        delete this.codes[code];
                        refreshTokenExpiresAt = new Date((new Date).getTime() - (1000 * Config_1.Config.oauth_refresh_token_lifetime)).toISOString();
                        accessTokenExpiresAt = new Date((new Date).getTime() - (1000 * Config_1.Config.oauth_access_token_lifetime)).toISOString();
                        codeExpiresAt = new Date((new Date).getTime() - (1000 * 120)).toISOString();
                        return [4 /*yield*/, Config_1.Config.db.DeleteMany({
                                "$or": [
                                    { "_type": "code", "_created": { "$lte": codeExpiresAt } },
                                    { "_type": "token", "refreshTokenExpiresAt": { "$lte": refreshTokenExpiresAt } },
                                    { "_type": "token", "accessTokenExpiresAt": { "$lte": accessTokenExpiresAt } }
                                ]
                            }, null, "oauthtokens", Crypt_1.Crypt.rootToken())];
                    case 1:
                        _a.sent();
                        // await Config.db.DeleteMany({ "_type": "code", "code": code }, null, "oauthtokens", Crypt.rootToken());
                        return [4 /*yield*/, Config_1.Config.db.DeleteMany({ "_type": "code", "_created": { "$lte": codeExpiresAt } }, null, "oauthtokens", Crypt_1.Crypt.rootToken())];
                    case 2:
                        // await Config.db.DeleteMany({ "_type": "code", "code": code }, null, "oauthtokens", Crypt.rootToken());
                        _a.sent();
                        return [2 /*return*/, true];
                }
            });
        });
    };
    OAuthProvider.getCachedAccessToken = function (accessToken) {
        return __awaiter(this, void 0, void 0, function () {
            var i, res, begin, end, seconds;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, semaphore.down()];
                    case 1:
                        _a.sent();
                        for (i = this.tokenCache.length - 1; i >= 0; i--) {
                            res = this.tokenCache[i];
                            begin = res.firstsignin.getTime();
                            end = new Date().getTime();
                            seconds = Math.round((end - begin) / 1000);
                            if (seconds > Config_1.Config.oauth_token_cache_seconds) {
                                this.tokenCache.splice(i, 1);
                            }
                            else if (res.token.accessToken == accessToken) {
                                // console.log("Return token from cache, using accessToken " + accessToken);
                                semaphore.up();
                                return [2 /*return*/, res.token];
                            }
                        }
                        semaphore.up();
                        return [2 /*return*/, null];
                }
            });
        });
    };
    OAuthProvider.getCachedRefreshToken = function (refreshToken) {
        return __awaiter(this, void 0, void 0, function () {
            var i, res, begin, end, seconds;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, semaphore.down()];
                    case 1:
                        _a.sent();
                        for (i = this.tokenCache.length - 1; i >= 0; i--) {
                            res = this.tokenCache[i];
                            begin = res.firstsignin.getTime();
                            end = new Date().getTime();
                            seconds = Math.round((end - begin) / 1000);
                            if (seconds > Config_1.Config.oauth_token_cache_seconds) {
                                this.tokenCache.splice(i, 1);
                            }
                            else if (res.token.refreshToken == refreshToken) {
                                // console.log("Return token from cache, using refreshToken " + refreshToken);
                                semaphore.up();
                                return [2 /*return*/, res.token];
                            }
                        }
                        semaphore.up();
                        return [2 /*return*/, null];
                }
            });
        });
    };
    OAuthProvider.addToken = function (token) {
        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();
                        cuser = new CachedToken(token);
                        this.tokenCache.push(cuser);
                        semaphore.up();
                        return [2 /*return*/];
                }
            });
        });
    };
    OAuthProvider.instance = null;
    OAuthProvider.tokenCache = [];
    return OAuthProvider;
}());
exports.OAuthProvider = OAuthProvider;
var CachedToken = /** @class */ (function () {
    function CachedToken(token) {
        this.token = token;
        this.firstsignin = new Date();
    }
    return CachedToken;
}());
exports.CachedToken = CachedToken;
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=OAuthProvider.js.map