feat: use api route and redis cache for finding tenant

This commit is contained in:
DIYgod 2022-10-11 23:10:47 +01:00
parent 04f78876df
commit a98f2d9c7c
No known key found for this signature in database
GPG Key ID: D159328F47A80DCA
2 changed files with 74 additions and 6 deletions

View File

@ -15,11 +15,6 @@ const ALWAYS_REPLAY_ROUTES = [
export default async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl
console.log(
`x-forwarded-proto: ${req.headers.get(
"x-forwarded-proto",
)}, cf-visitor: ${req.headers.get("cf-visitor")}`,
)
if (IS_PROD && req.headers.get("x-forwarded-proto") !== "https") {
let cfHttps = false
try {
@ -50,7 +45,17 @@ export default async function middleware(req: NextRequest) {
return NextResponse.next()
}
const tenant = await getTenant(req, req.nextUrl.searchParams)
let tenant: {
subdomain?: string
redirect?: string
} = {}
try {
tenant = await (
await fetch(
new URL(`/api/host2handle?host=${req.headers.get("host")}`, req.url),
)
).json()
} catch (error) {}
if (tenant?.redirect && IS_PROD) {
return NextResponse.redirect(

View File

@ -0,0 +1,63 @@
import { NextApiRequest, NextApiResponse } from "next"
import { OUR_DOMAIN } from "~/lib/env"
import { cacheGet } from "~/lib/redis.server"
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
let { host } = req.query
let realHost: string
if (Array.isArray(host)) {
realHost = host[0]
} else {
realHost = host || ""
}
let result = {}
const OUR_DOMAIN_SUFFIX = `.${OUR_DOMAIN}`
if (realHost && realHost !== OUR_DOMAIN) {
result = await cacheGet(["host2handle", realHost], async () => {
if (realHost.endsWith(OUR_DOMAIN_SUFFIX)) {
const subdomain = realHost.replace(OUR_DOMAIN_SUFFIX, "")
const res = await fetch(
`https://indexer.crossbell.io/v1/handles/${subdomain}/character`,
)
const char = await res.json()
const customDomain =
char?.metadata?.content?.attributes?.find(
(a: any) => a.trait_type === "xlog_custom_domain",
)?.value || ""
if (customDomain) {
return {
redirect: /^https?:\/\//.test(customDomain)
? customDomain
: `https://${customDomain}`,
subdomain: subdomain,
}
} else {
return {
subdomain: subdomain,
}
}
} else {
const res = await fetch(
`https://cloudflare-dns.com/dns-query?name=_xlog-challenge.${realHost}&type=TXT`,
{
headers: {
accept: "application/dns-json",
},
},
)
const txt = await res.json()
const tenant = txt?.Answer?.[0]?.data.replace(/^"|"$/g, "")
return {
subdomain: tenant,
}
}
})
}
res.status(200).json(result)
}