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);
};
import CookieUtil from "../Utils/Cookie";
import JSONWebToken from "../Utils/JsonWebToken";
import logger from "../Utils/Logger";
import DashboardLabelRuleEngineService from "./DashboardLabelRuleEngineService";
import DashboardOwnerRuleEngineService from "./DashboardOwnerRuleEngineService";
import DatabaseService from "./DatabaseService";
import BadDataException from "../../Types/Exception/BadDataException";
import NotAuthenticatedException from "../../Types/Exception/NotAuthenticatedException";
import ForbiddenException from "../../Types/Exception/ForbiddenException";
import MasterPasswordRequiredException from "../../Types/Exception/MasterPasswordRequiredException";
import Model from "../../Models/DatabaseModels/Dashboard";
import { IsBillingEnabled } from "../EnvironmentConfig";
import { PlanType } from "../../Types/Billing/SubscriptionPlan";
import DashboardViewConfigUtil from "../../Utils/Dashboard/DashboardViewConfig";
import { DashboardTemplateType, getTemplateConfig, } from "../../Types/Dashboard/DashboardTemplates";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import IP from "../../Types/IP/IP";
import { DASHBOARD_MASTER_PASSWORD_COOKIE_IDENTIFIER, DASHBOARD_MASTER_PASSWORD_REQUIRED_MESSAGE, } from "../../Types/Dashboard/MasterPassword";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onBeforeCreate(createBy) {
        var _a;
        if (IsBillingEnabled) {
            // then if free plan, make sure it can only have 1 dashboard.
            if (createBy.props.currentPlan === PlanType.Free) {
                // get count by project id.
                const count = (await this.countBy({
                    query: {
                        projectId: createBy.data.projectId,
                    },
                    props: {
                        isRoot: true,
                    },
                })).toNumber();
                if (count > 0) {
                    throw new BadDataException("Free plan can only have 1 dashboard. Please upgrade your plan.");
                }
            }
        }
        // Check if a template type was provided via miscDataProps
        const templateType = (_a = createBy.miscDataProps) === null || _a === void 0 ? void 0 : _a["dashboardTemplateType"];
        if (templateType &&
            templateType !== DashboardTemplateType.Blank &&
            Object.values(DashboardTemplateType).includes(templateType)) {
            const templateConfig = getTemplateConfig(templateType);
            if (templateConfig) {
                createBy.data.dashboardViewConfig = templateConfig;
            }
        }
        // use default empty config only if no template config was provided.
        if (!createBy.data.dashboardViewConfig ||
            !createBy.data.dashboardViewConfig.components ||
            createBy.data.dashboardViewConfig.components.length === 0) {
            createBy.data.dashboardViewConfig =
                DashboardViewConfigUtil.createDefaultDashboardViewConfig();
        }
        return Promise.resolve({ createBy, carryForward: null });
    }
    async onCreateSuccess(_onCreate, createdItem) {
        if (createdItem.projectId && createdItem.id) {
            /*
             * Run label rule first so rule-added labels are persisted before
             * owner rules run. Owner rules re-fetch labels, so this lets owner
             * rules key on rule-added labels.
             */
            Promise.resolve()
                .then(async () => {
                await DashboardLabelRuleEngineService.applyRulesToDashboard(createdItem);
            })
                .then(async () => {
                await DashboardOwnerRuleEngineService.applyRulesToDashboard(createdItem);
            })
                .catch((error) => {
                var _a, _b;
                logger.error(`Error applying dashboard rules in DashboardService.onCreateSuccess: ${error}`, {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                    dashboardId: (_b = createdItem.id) === null || _b === void 0 ? void 0 : _b.toString(),
                });
            });
        }
        return createdItem;
    }
    async hasReadAccess(data) {
        var _a, _b, _c;
        const dashboardId = data.dashboardId;
        const req = data.req;
        try {
            const dashboard = await this.findOneById({
                id: dashboardId,
                props: {
                    isRoot: true,
                },
                select: {
                    _id: true,
                    isPublicDashboard: true,
                    ipWhitelist: true,
                    enableMasterPassword: true,
                    masterPassword: true,
                },
            });
            // If dashboard is not public, deny access
            if (dashboard && !dashboard.isPublicDashboard) {
                return {
                    hasReadAccess: false,
                    error: new NotAuthenticatedException("This dashboard is not available."),
                };
            }
            if ((dashboard === null || dashboard === void 0 ? void 0 : dashboard.ipWhitelist) && dashboard.ipWhitelist.length > 0) {
                const ipWhitelist = (_a = dashboard.ipWhitelist) === null || _a === void 0 ? void 0 : _a.split("\n");
                const ipAccessedFrom = ((_b = req.headers["x-forwarded-for"]) === null || _b === void 0 ? void 0 : _b.toString()) ||
                    ((_c = req.headers["x-real-ip"]) === null || _c === void 0 ? void 0 : _c.toString()) ||
                    req.socket.remoteAddress ||
                    req.ip ||
                    req.ips[0];
                if (!ipAccessedFrom) {
                    logger.error("IP address not found in request.", {
                        dashboardId: dashboardId === null || dashboardId === void 0 ? void 0 : dashboardId.toString(),
                    });
                    return {
                        hasReadAccess: false,
                        error: new ForbiddenException("Unable to verify IP address for dashboard access."),
                    };
                }
                const isIPWhitelisted = IP.isInWhitelist({
                    ips: (ipAccessedFrom === null || ipAccessedFrom === void 0 ? void 0 : ipAccessedFrom.split(",").map((i) => {
                        return i.trim();
                    })) || [],
                    whitelist: ipWhitelist,
                });
                if (!isIPWhitelisted) {
                    logger.error(`IP address ${ipAccessedFrom} is not whitelisted for dashboard ${dashboardId.toString()}.`, { dashboardId: dashboardId === null || dashboardId === void 0 ? void 0 : dashboardId.toString() });
                    return {
                        hasReadAccess: false,
                        error: new ForbiddenException(`Your IP address ${ipAccessedFrom} is blocked from accessing this dashboard.`),
                    };
                }
            }
            const shouldEnforceMasterPassword = Boolean(dashboard &&
                dashboard.isPublicDashboard &&
                dashboard.enableMasterPassword &&
                dashboard.masterPassword);
            if (shouldEnforceMasterPassword) {
                const hasValidMasterPassword = this.hasValidMasterPasswordCookie({
                    req,
                    dashboardId,
                });
                if (hasValidMasterPassword) {
                    return {
                        hasReadAccess: true,
                    };
                }
                return {
                    hasReadAccess: false,
                    error: new MasterPasswordRequiredException(DASHBOARD_MASTER_PASSWORD_REQUIRED_MESSAGE),
                };
            }
            // Public dashboard without master password - grant access
            if (dashboard && dashboard.isPublicDashboard) {
                return {
                    hasReadAccess: true,
                };
            }
        }
        catch (err) {
            logger.error(err, {
                dashboardId: dashboardId === null || dashboardId === void 0 ? void 0 : dashboardId.toString(),
            });
        }
        return {
            hasReadAccess: false,
            error: new NotAuthenticatedException("You do not have access to this dashboard."),
        };
    }
    hasValidMasterPasswordCookie(data) {
        var _a;
        const token = CookieUtil.getCookieFromExpressRequest(data.req, CookieUtil.getDashboardMasterPasswordKey(data.dashboardId));
        if (!token) {
            return false;
        }
        try {
            const payload = JSONWebToken.decodeJsonPayload(token);
            return (payload["dashboardId"] === data.dashboardId.toString() &&
                payload["type"] === DASHBOARD_MASTER_PASSWORD_COOKIE_IDENTIFIER);
        }
        catch (err) {
            logger.error(err, {
                dashboardId: (_a = data.dashboardId) === null || _a === void 0 ? void 0 : _a.toString(),
            });
        }
        return false;
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeCreate", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Model]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onCreateSuccess", null);
export default new Service();
//# sourceMappingURL=DashboardService.js.map