Protect Tabularium with persistent authenticator-code login
Verify and deploy Tabularium / verify-and-deploy (push) Successful in 5m28s
Verify and deploy Tabularium / verify-and-deploy (push) Successful in 5m28s
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { authConfig, sessionCookie, signSession } from "@/lib/auth";
|
||||
import { consumeCode } from "@/lib/auth-store";
|
||||
export default async function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse,
|
||||
) {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
if (req.method !== "POST") {
|
||||
res.setHeader("Allow", "POST");
|
||||
return res.status(405).end();
|
||||
}
|
||||
try {
|
||||
const origin = req.headers.origin;
|
||||
if (
|
||||
!origin ||
|
||||
new URL(origin).host !== req.headers.host ||
|
||||
req.headers["sec-fetch-site"] === "cross-site"
|
||||
)
|
||||
return res.status(403).json({ error: "请求来源不受信任" });
|
||||
const config = authConfig();
|
||||
if (!config)
|
||||
return res
|
||||
.status(503)
|
||||
.json({ error: "尚未配置动态码登录,请联系管理员" });
|
||||
const code = typeof req.body?.code === "string" ? req.body.code.trim() : "";
|
||||
const result = await consumeCode(config, code);
|
||||
if (result === "limited") {
|
||||
res.setHeader("Retry-After", "300");
|
||||
return res.status(429).json({ error: "尝试次数过多,请五分钟后再试" });
|
||||
}
|
||||
if (result !== "ok")
|
||||
return res
|
||||
.status(401)
|
||||
.json({ error: "动态码不正确或已使用,请等待下一组动态码" });
|
||||
res.setHeader("Set-Cookie", sessionCookie(signSession(config)));
|
||||
return res.status(200).json({ ok: true });
|
||||
} catch {
|
||||
return res.status(503).json({ error: "登录服务暂时不可用,请稍后重试" });
|
||||
}
|
||||
}
|
||||
export const config = { api: { bodyParser: { sizeLimit: "1kb" } } };
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { sessionCookie } from "@/lib/auth";
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
if (req.method !== "POST") {
|
||||
res.setHeader("Allow", "POST");
|
||||
return res.status(405).end();
|
||||
}
|
||||
try {
|
||||
if (
|
||||
!req.headers.origin ||
|
||||
new URL(req.headers.origin).host !== req.headers.host ||
|
||||
req.headers["sec-fetch-site"] === "cross-site"
|
||||
)
|
||||
return res.status(403).end();
|
||||
} catch {
|
||||
return res.status(403).end();
|
||||
}
|
||||
res.setHeader("Set-Cookie", sessionCookie("", true));
|
||||
return res.status(200).json({ ok: true });
|
||||
}
|
||||
Reference in New Issue
Block a user