"use strict";
/*
 * server component for the TimeLimit App
 * Copyright (C) 2019 - 2022 Jonas Lochmann
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.createApi = void 0;
const basicAuth = require("basic-auth");
const express = require("express");
const admin_1 = require("./admin");
const auth_1 = require("./auth");
const child_1 = require("./child");
const parent_1 = require("./parent");
const purchase_1 = require("./purchase");
const sync_1 = require("./sync");
const adminToken = process.env.ADMIN_TOKEN || '';
const createApi = ({ database, websocket, connectedDevicesManager, eventHandler }) => {
    const app = express();
    app.disable('x-powered-by');
    app.get('/time', (_, res) => {
        res.json({
            ms: Date.now()
        });
    });
    app.use('/auth', (0, auth_1.createAuthRouter)(database));
    app.use('/child', (0, child_1.createChildRouter)({ database, websocket, eventHandler }));
    app.use('/parent', (0, parent_1.createParentRouter)({ database, websocket, eventHandler }));
    app.use('/purchase', (0, purchase_1.createPurchaseRouter)({ database, websocket }));
    app.use('/sync', (0, sync_1.createSyncRouter)({ database, websocket, connectedDevicesManager, eventHandler }));
    app.use('/admin', (req, res, next) => {
        // required for webbrowser CORS support
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Headers', 'Authorization, Content-Type, Accept');
        res.header('Access-Control-Allow-Methods', 'GET, POST');
        // without it, browsers ignore the cors headers
        if (req.method === 'OPTIONS') {
            res.sendStatus(204);
            return;
        }
        const user = basicAuth(req);
        if (adminToken !== '' && user && user.pass === adminToken) {
            next();
        }
        else {
            res.setHeader('WWW-Authenticate', 'Basic realm="login"');
            res.sendStatus(401);
        }
    }, (0, admin_1.createAdminRouter)({ database, websocket, eventHandler }));
    return app;
};
exports.createApi = createApi;
//# sourceMappingURL=index.js.map