"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createAuthMiddleware = createAuthMiddleware;
const axios_1 = __importDefault(require("axios"));
const authorization_1 = require("../utils/authorization");
const requestsSetup_1 = require("../components/requestsSetup");
const cluster_queries_1 = require("../components/cluster-queries");
const utils_1 = require("../utils");
class AuthError extends Error {
    constructor() {
        super('Authorization required');
    }
}
function isAuthError(e) {
    return e instanceof AuthError || (axios_1.default.isAxiosError(e) && e.response?.status === 401);
}
function createAuthMiddleware() {
    return async function authMiddleware(req, res, next) {
        const { ytAuthCluster } = req.params;
        try {
            if (!(0, authorization_1.isAuthorized)(req)) {
                throw new AuthError();
            }
            const cfg = (0, requestsSetup_1.getUserYTApiSetup)(ytAuthCluster, req);
            const { login } = await (0, cluster_queries_1.getXSRFToken)(req, cfg);
            req.yt.login = login;
        }
        catch (e) {
            const isAuthFailed = isAuthError(e);
            const error = isAuthFailed ? undefined : e;
            if (!req.routeInfo.ui && isAuthFailed) {
                (0, utils_1.sendError)(res, error, 401);
                return;
            }
        }
        next();
    };
}
