1단계 뼈대: joke-app에서 로그인(디스코드·게스트)·세션·권한·관리자·DB를 가져와 음악퀴즈용으로 정리, 새 디자인·아이콘, WS 연결·시계 맞추기, 테스트·e2e
- apps/server: Hono API(auth/me/config/admin), Bun WebSocket(welcome·ping/pong, 압축 끔), SQLite 마이그레이션 - 사이트 설정: 채팅 도배 방지 기본 꺼짐(관리자가 켬, 초당·순간 횟수) - apps/web: 첫 화면·로그인·관리자(대시보드·사이트·사용자·관리자·기록), 라이트/다크, 휴대폰, noindex - packages/shared: 닉네임 규칙, 프로토콜(zod), 시계 차이 계산 - 테스트 20개 + 브라우저 e2e 6단계 통과 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
59
apps/server/src/auth/discord.ts
Normal file
59
apps/server/src/auth/discord.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
/** Discord OAuth2 (authorization code + state), docs/02, ported from joke-app. */
|
||||
export interface DiscordUser {
|
||||
id: string;
|
||||
username: string;
|
||||
global_name: string | null;
|
||||
avatar: string | null;
|
||||
}
|
||||
|
||||
const API = 'https://discord.com/api/v10';
|
||||
|
||||
export function authorizeUrl(clientId: string, redirectUri: string, state: string): string {
|
||||
const p = new URLSearchParams({
|
||||
client_id: clientId,
|
||||
response_type: 'code',
|
||||
redirect_uri: redirectUri,
|
||||
scope: 'identify',
|
||||
state,
|
||||
prompt: 'none',
|
||||
});
|
||||
return `https://discord.com/oauth2/authorize?${p}`;
|
||||
}
|
||||
|
||||
export async function exchangeCode(
|
||||
cfg: { clientId: string; clientSecret: string },
|
||||
code: string,
|
||||
redirectUri: string,
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
): Promise<DiscordUser> {
|
||||
const tokenRes = await fetchImpl(`${API}/oauth2/token`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({
|
||||
client_id: cfg.clientId,
|
||||
client_secret: cfg.clientSecret,
|
||||
grant_type: 'authorization_code',
|
||||
code,
|
||||
redirect_uri: redirectUri,
|
||||
}),
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
if (!tokenRes.ok) throw new Error(`discord token exchange failed: ${tokenRes.status}`);
|
||||
const token = (await tokenRes.json()) as { access_token: string; token_type: string };
|
||||
const meRes = await fetchImpl(`${API}/users/@me`, {
|
||||
headers: { Authorization: `${token.token_type} ${token.access_token}` },
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
if (!meRes.ok) throw new Error(`discord /users/@me failed: ${meRes.status}`);
|
||||
return (await meRes.json()) as DiscordUser;
|
||||
}
|
||||
|
||||
export function avatarUrl(u: DiscordUser): string | null {
|
||||
return u.avatar ? `https://cdn.discordapp.com/avatars/${u.id}/${u.avatar}.png?size=128` : null;
|
||||
}
|
||||
|
||||
/** Only same-site relative paths are allowed as post-login redirect targets. */
|
||||
export function safeNext(next: string | null | undefined): string {
|
||||
if (!next || !next.startsWith('/') || next.startsWith('//') || next.includes('\\')) return '/';
|
||||
return next;
|
||||
}
|
||||
Reference in New Issue
Block a user