All files / owid-grapher/adminSiteServer adminRouter.tsx

40.54% Statements 90/222
100% Branches 1/1
50% Functions 1/2
40.54% Lines 90/222

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 2871x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x                                                 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x                                             1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x                                                               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                         1x 1x 1x                                                                                                                                            
// Misc non-SPA views
import { Request, Response, Router } from "express"
import * as express from "express"
import rateLimit from "express-rate-limit"
import filenamify from "filenamify"
import * as React from "react"
import { getConnection } from "typeorm"
import { expectInt, tryInt, renderToHtmlPage } from "../serverUtils/serverUtil"
import { logInWithCredentials, logOut } from "./authentication"
import { LoginPage } from "./LoginPage"
import { RegisterPage } from "./RegisterPage"
import * as db from "../db/db"
import { Dataset } from "../db/model/Dataset"
import { User } from "../db/model/User"
import { UserInvitation } from "../db/model/UserInvitation"
import { BAKED_BASE_URL, ENV } from "../settings/serverSettings"
import { ExplorerAdminServer } from "../explorerAdminServer/ExplorerAdminServer"
import { renderExplorerPage, renderPreview } from "../baker/siteRenderers"
import { JsonError } from "../clientUtils/owidTypes"
import { GitCmsServer } from "../gitCms/GitCmsServer"
import { GIT_CMS_DIR } from "../gitCms/GitCmsConstants"
import { slugify, stringifyUnkownError } from "../clientUtils/Util"
import {
    DefaultNewExplorerSlug,
    EXPLORERS_PREVIEW_ROUTE,
    GetAllExplorersRoute,
} from "../explorer/ExplorerConstants"
import {
    ExplorerProgram,
    EXPLORER_FILE_SUFFIX,
} from "../explorer/ExplorerProgram"
import { existsSync } from "fs-extra"
 
// Used for rate-limiting important endpoints (login, register) to prevent brute force attacks
const limiterMiddleware = (
    onFailRender: (req: Request, res: Response) => React.ReactElement
) =>
    rateLimit({
        windowMs: 60_000, // 1 minute
        max: 10, // max. 10 requests per minute
        handler: (req, res) =>
            res.status(429).send(renderToHtmlPage(onFailRender(req, res))),
    })
 
const adminRouter = Router()
 
// Parse incoming requests with JSON payloads http://expressjs.com/en/api.html
adminRouter.use(express.json({ limit: "50mb" }))
 
// None of these should be google indexed
adminRouter.use(async (req, res, next) => {
    res.set("X-Robots-Tag", "noindex")
    return next()
})
 
adminRouter.get("/", async (req, res) => {
    // Preview URLs generated by WP depend on the status of the post:
    // * PUBLISHED: owid.cloud/SLUG?preview=true --> run through WP singular.php
    //   and directly redirected to /admin/posts/preview/POST_ID
    // * DRAFT:
    //     - post: owid.cloud/?p=POST_ID&preview=true
    //     - page: owid.cloud/?page_id=PAGE_ID&preview=true
    //   --> "/" captured by NGINX and redirected here (/admin/)
    //
    // Ideally, the preview URL in WP would be pointing directly to
    // /admin/posts/preview/POST_ID (bypassing WP altogether, for published and
    // draft posts) but this is only partially possible for now, as the preview
    // URL of draft posts does not get rewritten by the preview_post_link filter
    // within Gutenberg.
    //
    // See:
    //  * https://github.com/WordPress/gutenberg/issues/13998
    //  * https://developer.wordpress.org/reference/hooks/preview_post_link/
    if (req.query.preview === "true" && (req.query.p || req.query.page_id)) {
        // HACK
        res.redirect(`/admin/posts/preview/${req.query.p || req.query.page_id}`)
    } else {
        res.redirect(`/admin/charts`)
    }
})
 
adminRouter.get("/login", async (req, res) => {
    res.send(renderToHtmlPage(<LoginPage next={req.query.next} />))
})
adminRouter.post(
    "/login",
    limiterMiddleware((req) => (
        <LoginPage
            errorMessage="Too many attempts, please try again in a minute."
            next={req.query.next}
        />
    )),
    async (req, res) => {
        try {
            const session = await logInWithCredentials(
                req.body.username,
                req.body.password
            )
            res.cookie("sessionid", session.id, {
                httpOnly: true,
                sameSite: "lax",
                secure: ENV === "production",
            })
            res.redirect(req.query.next || "/admin")
        } catch (err) {
            res.status(400).send(
                renderToHtmlPage(
                    <LoginPage
                        next={req.query.next}
                        errorMessage={stringifyUnkownError(err)}
                    />
                )
            )
        }
    }
)
 
adminRouter.get("/logout", logOut)
 
adminRouter.get(
    "/register",
    limiterMiddleware((req) => (
        <RegisterPage
            errorMessage="Too many attempts, please try again in a minute."
            body={req.query}
        />
    )),
    async (req, res) => {
        if (res.locals.user) {
            res.redirect("/admin")
            return
        }

        let errorMessage: string | undefined
        let invite: UserInvitation | undefined
        try {
            // Delete all expired invites before continuing
            await UserInvitation.createQueryBuilder()
                .where("validTill < NOW()")
                .delete()
                .execute()

            invite = await UserInvitation.findOne({ code: req.query.code })
            if (!invite) throw new JsonError("Invite code invalid or expired")
        } catch (err) {
            errorMessage = stringifyUnkownError(err)
            res.status(tryInt((err as any).code, 500))
        } finally {
            res.send(
                renderToHtmlPage(
                    <RegisterPage
                        inviteEmail={invite && invite.email}
                        errorMessage={errorMessage}
                        body={req.query}
                    />
                )
            )
        }
    }
)
 
adminRouter.post(
    "/register",
    limiterMiddleware((req) => (
        <RegisterPage
            errorMessage="Too many attempts, please try again in a minute."
            body={req.query}
        />
    )),
    async (req, res) => {
        try {
            // Delete all expired invites before continuing
            await UserInvitation.createQueryBuilder()
                .where("validTill < NOW()")
                .delete()
                .execute()

            const invite = await UserInvitation.findOne({ code: req.body.code })
            if (!invite) {
                throw new JsonError("Invite code invalid or expired", 403)
            }

            if (req.body.password !== req.body.confirmPassword) {
                throw new JsonError("Passwords don't match!", 400)
            }

            await getConnection().transaction(async (manager) => {
                const user = new User()
                user.email = req.body.email
                user.fullName = req.body.fullName
                user.createdAt = new Date()
                user.updatedAt = new Date()
                user.lastLogin = new Date()
                await user.setPassword(req.body.password)
                await manager.getRepository(User).save(user)

                // Remove the invite now that it has been used successfully
                await manager.remove(invite)
            })

            await logInWithCredentials(req.body.email, req.body.password)
            res.redirect("/admin")
        } catch (err) {
            res.status(tryInt((err as any).code, 500))
            res.send(
                renderToHtmlPage(
                    <RegisterPage
                        errorMessage={stringifyUnkownError(err)}
                        body={req.body}
                    />
                )
            )
        }
    }
)
 
adminRouter.get("/datasets/:datasetId.csv", async (req, res) => {
    const datasetId = expectInt(req.params.datasetId)

    const datasetName = (
        await db.mysqlFirst(`SELECT name FROM datasets WHERE id=?`, [datasetId])
    ).name
    res.attachment(filenamify(datasetName) + ".csv")
 
    return Dataset.writeCSV(datasetId, res)
})
 
adminRouter.get("/datasets/:datasetId/downloadZip", async (req, res) => {
    const datasetId = expectInt(req.params.datasetId)
 
    res.attachment("additional-material.zip")
 
    const file = await db.mysqlFirst(
        `SELECT filename, file FROM dataset_files WHERE datasetId=?`,
        [datasetId]
    )
    res.send(file.file)
})
 
adminRouter.get("/posts/preview/:postId", async (req, res) => {
    const postId = expectInt(req.params.postId)
 
    res.send(await renderPreview(postId))
})
 
adminRouter.get("/errorTest.csv", async (req, res) => {
    // Add `table /admin/errorTest.csv?code=404` to test fetch download failures
    const code =
        req.query.code && !isNaN(parseInt(req.query.code))
            ? req.query.code
            : 400
 
    res.status(code)
 
    return `Simulating code ${code}`
})
 
const explorerAdminServer = new ExplorerAdminServer(GIT_CMS_DIR)
 
adminRouter.get(`/${GetAllExplorersRoute}`, async (req, res) => {
    res.send(await explorerAdminServer.getAllExplorersCommand())
})
 
adminRouter.get(`/${EXPLORERS_PREVIEW_ROUTE}/:slug`, async (req, res) => {
    const slug = slugify(req.params.slug)
    const filename = slug + EXPLORER_FILE_SUFFIX
    if (slug === DefaultNewExplorerSlug)
        return res.send(
            await renderExplorerPage(
                new ExplorerProgram(DefaultNewExplorerSlug, "")
            )
        )
    if (!slug || !existsSync(explorerAdminServer.absoluteFolderPath + filename))
        return res.send(`File not found`)
    const explorer = await explorerAdminServer.getExplorerFromFile(filename)
    return res.send(await renderExplorerPage(explorer))
})
 
const gitCmsServer = new GitCmsServer({
    baseDir: GIT_CMS_DIR,
    shouldAutoPush: true,
})
gitCmsServer.createDirAndInitIfNeeded()
gitCmsServer.addToRouter(adminRouter)
 
export { adminRouter }