- Optional Discord OAuth2 login (identify scope), enabled by DISCORD_CLIENT_SECRET, WEB_PUBLIC_URL and SESSION_SECRET; restricted to members of the configured guild, checked at login. - Stateless 30-day session in a signed HttpOnly SameSite=Lax cookie; the OAuth state is checked against its own short-lived cookie. - The jukebox API accepts the key or the session; with the session, changes must come from the site's own origin. The member's server name becomes the uploader name. - GET /auth/me tells the page whether the login is enabled and who is logged in. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
125 lines
4.3 KiB
JavaScript
125 lines
4.3 KiB
JavaScript
import { Router } from "express";
|
|
import { randomBytes } from "node:crypto";
|
|
import {
|
|
SESSION_COOKIE,
|
|
SESSION_DURATION,
|
|
STATE_COOKIE,
|
|
createSessionToken,
|
|
parseCookies,
|
|
readSessionToken,
|
|
serializeCookie,
|
|
} from "../auth/session.js";
|
|
|
|
const DISCORD_API = "https://discord.com/api/v10";
|
|
const STATE_DURATION = 10 * 60 * 1000;
|
|
|
|
// Lit la session (cookie signé) et place l'utilisateur dans req.user.
|
|
function sessionMiddleware(oauth) {
|
|
return function readSession(req, _res, next) {
|
|
if (oauth.enabled) {
|
|
const token = parseCookies(req.headers.cookie)[SESSION_COOKIE];
|
|
req.user = readSessionToken(token, oauth.sessionSecret);
|
|
}
|
|
next();
|
|
};
|
|
}
|
|
|
|
// Connexion avec Discord (OAuth2, portée « identify ») réservée aux membres du serveur.
|
|
// oauth : { enabled, clientId, clientSecret, publicUrl, sessionSecret }.
|
|
// findMember(userId) renvoie le membre du serveur ou null.
|
|
function authRouter({ oauth, findMember, fetchImpl = fetch }) {
|
|
const router = Router();
|
|
const secure = oauth.enabled && new URL(oauth.publicUrl).protocol === "https:";
|
|
const redirectUri = oauth.enabled ? `${oauth.publicUrl}/auth/discord/callback` : null;
|
|
const fail = (res, reason) => res.redirect(303, `/jukebox/?login=${reason}`);
|
|
|
|
router.get("/me", (req, res) => {
|
|
res.set("Cache-Control", "no-store");
|
|
res.json({ oauthEnabled: oauth.enabled, user: req.user ?? null });
|
|
});
|
|
|
|
router.get("/discord", (req, res) => {
|
|
if (!oauth.enabled) {
|
|
return res.status(404).json({ error: "Connexion avec Discord désactivée" });
|
|
}
|
|
|
|
const state = randomBytes(24).toString("base64url");
|
|
res.append(
|
|
"Set-Cookie",
|
|
serializeCookie(STATE_COOKIE, state, { maxAge: STATE_DURATION, path: "/auth", secure })
|
|
);
|
|
const params = new URLSearchParams({
|
|
client_id: oauth.clientId,
|
|
response_type: "code",
|
|
redirect_uri: redirectUri,
|
|
scope: "identify",
|
|
state,
|
|
prompt: "none",
|
|
});
|
|
res.redirect(303, `https://discord.com/oauth2/authorize?${params}`);
|
|
});
|
|
|
|
router.get("/discord/callback", async (req, res) => {
|
|
if (!oauth.enabled) {
|
|
return res.status(404).json({ error: "Connexion avec Discord désactivée" });
|
|
}
|
|
|
|
const expectedState = parseCookies(req.headers.cookie)[STATE_COOKIE];
|
|
res.append(
|
|
"Set-Cookie",
|
|
serializeCookie(STATE_COOKIE, "", { maxAge: 0, path: "/auth", secure })
|
|
);
|
|
if (req.query.error) return fail(res, "denied");
|
|
if (!expectedState || req.query.state !== expectedState) return fail(res, "state");
|
|
if (typeof req.query.code !== "string") return fail(res, "failed");
|
|
|
|
try {
|
|
const tokenResponse = await fetchImpl(`${DISCORD_API}/oauth2/token`, {
|
|
method: "POST",
|
|
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
body: new URLSearchParams({
|
|
client_id: oauth.clientId,
|
|
client_secret: oauth.clientSecret,
|
|
grant_type: "authorization_code",
|
|
code: req.query.code,
|
|
redirect_uri: redirectUri,
|
|
}),
|
|
});
|
|
if (!tokenResponse.ok) throw new Error(`token exchange: ${tokenResponse.status}`);
|
|
const { access_token: accessToken } = await tokenResponse.json();
|
|
|
|
const userResponse = await fetchImpl(`${DISCORD_API}/users/@me`, {
|
|
headers: { authorization: `Bearer ${accessToken}` },
|
|
});
|
|
if (!userResponse.ok) throw new Error(`user lookup: ${userResponse.status}`);
|
|
const user = await userResponse.json();
|
|
|
|
const member = await findMember(user.id);
|
|
if (!member) return fail(res, "not-member");
|
|
|
|
const name = member.displayName || user.global_name || user.username;
|
|
res.append(
|
|
"Set-Cookie",
|
|
serializeCookie(
|
|
SESSION_COOKIE,
|
|
createSessionToken({ id: user.id, name }, oauth.sessionSecret),
|
|
{ maxAge: SESSION_DURATION, secure }
|
|
)
|
|
);
|
|
console.log(`[${new Date().toLocaleString()}] Web login: ${user.id}`);
|
|
return res.redirect(303, "/jukebox/");
|
|
} catch (error) {
|
|
console.error("Discord login failed", error);
|
|
return fail(res, "failed");
|
|
}
|
|
});
|
|
|
|
router.post("/logout", (req, res) => {
|
|
res.append("Set-Cookie", serializeCookie(SESSION_COOKIE, "", { maxAge: 0, secure }));
|
|
res.status(204).end();
|
|
});
|
|
|
|
return router;
|
|
}
|
|
|
|
export { authRouter, sessionMiddleware };
|