"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.auth_router = exports.handle_logout = exports.handle_login = void 0;
const api_client_1 = require("@cross-lab-project/api-client");
const logging_1 = require("@crosslab/service-common/logging");
const express_1 = require("express");
const express_async_handler_1 = __importDefault(require("express-async-handler"));
const config_1 = require("./config");
async function handle_login(req, res, next) {
    let loggedIn = false;
    for (const method of ["tui", "local"]) {
        try {
            await req.apiClient.login(req.body.username, req.body.password, {
                method,
            });
            res.cookie("token", req.apiClient.accessToken, {
                secure: true,
                httpOnly: true,
                sameSite: "strict",
            });
            loggedIn = true;
            break;
        }
        catch (error) {
            logging_1.logger.log("info", `Could not login with method '${method}`);
        }
    }
    if (loggedIn) {
        try {
            req.user = await req.apiClient.getIdentity();
            if (req.query.redirect) {
                res.redirect(303, req.query.redirect);
            }
            else {
                res.redirect(303, "index.html");
            }
        }
        catch (e) {
            logging_1.logger.warn(e);
            res.clearCookie("token");
            next();
        }
    }
    else {
        res.clearCookie("token");
        logging_1.logger.warn("user could not be logged in!");
        next();
    }
}
exports.handle_login = handle_login;
async function handle_logout(req, res, _next) {
    res.clearCookie("token");
    if (req.query.redirect) {
        res.redirect(303, req.query.redirect);
    }
    else {
        res.redirect(303, "/index.html");
    }
}
exports.handle_logout = handle_logout;
function auth_router() {
    const router = (0, express_1.Router)();
    router.use("/", (0, express_async_handler_1.default)(async (req, res, next) => {
        req.apiClient = new api_client_1.APIClient(config_1.config.API_URL);
        req.user = undefined;
        req.initApiClient = async (token) => {
            if (!token) {
                res.clearCookie("token");
            }
            else {
                req.apiClient.accessToken = token;
                try {
                    req.user = {
                        ...(await req.apiClient.getIdentity()),
                        token: req.cookies.token,
                    };
                    //res.cookie("token", token, {
                    //  sameSite: "strict",
                    //  secure: true,
                    //  httpOnly: true,
                    //});
                }
                catch (e) {
                    logging_1.logger.info("Could not get identity, token seems invalid.");
                    //res.clearCookie("token");
                }
            }
        };
        // handle token query parameter
        if (req.query.token && typeof req.query.token === "string") {
            await req.initApiClient(req.query.token);
        }
        else if (req.cookies.token) {
            await req.initApiClient(req.cookies.token);
        }
        next();
    }));
    return router;
}
exports.auth_router = auth_router;
//# sourceMappingURL=auth.js.map