diff --git a/apps/web/.env.development b/apps/web/.env.development index 1bfdaca2..cd55dbf3 100644 --- a/apps/web/.env.development +++ b/apps/web/.env.development @@ -4,3 +4,4 @@ VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3 VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863 VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback +VITE_MSAL_SILENT_REDIRECT_URI=http://localhost:5173/auth/silent-callback.html diff --git a/apps/web/.env.example b/apps/web/.env.example index e9bcecef..969d2d5c 100644 --- a/apps/web/.env.example +++ b/apps/web/.env.example @@ -4,3 +4,4 @@ VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3 VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/ VITE_MSAL_API_SCOPE=api://lolympus-api/access_as_user VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback +VITE_MSAL_SILENT_REDIRECT_URI=http://localhost:5173/auth/silent-callback.html diff --git a/apps/web/.env.production b/apps/web/.env.production index b25a5200..64d88a8a 100644 --- a/apps/web/.env.production +++ b/apps/web/.env.production @@ -4,4 +4,5 @@ VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3 VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863 VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev VITE_MSAL_REDIRECT_URI=https://lolympus.dahyeon.us/auth/callback +VITE_MSAL_SILENT_REDIRECT_URI=https://lolympus.dahyeon.us/auth/silent-callback.html diff --git a/apps/web/public/auth/silent-callback.html b/apps/web/public/auth/silent-callback.html new file mode 100644 index 00000000..5db0a78d --- /dev/null +++ b/apps/web/public/auth/silent-callback.html @@ -0,0 +1,8 @@ + + + + + Silent Auth + + + diff --git a/apps/web/public/riot.txt b/apps/web/public/riot.txt new file mode 100644 index 00000000..3028f46b --- /dev/null +++ b/apps/web/public/riot.txt @@ -0,0 +1 @@ +c47e5251-44c8-4569-a3f6-3cab42fdec98 \ No newline at end of file diff --git a/apps/web/src/api/hooks.ts b/apps/web/src/api/hooks.ts index b2df8121..1286c0d6 100644 --- a/apps/web/src/api/hooks.ts +++ b/apps/web/src/api/hooks.ts @@ -6,6 +6,7 @@ import { apiFetch } from '../lib/api'; import { isMsalConfigured, MSAL_API_SCOPE, + MSAL_SILENT_REDIRECT_URI, } from '../lib/auth/msal.config'; import type { ApiAuction, @@ -53,7 +54,8 @@ function createMatchesPath( export function useCommunity(communityId = DEFAULT_COMMUNITY_ID) { return useQuery({ queryKey: ['community', communityId], - queryFn: () => apiFetch(`/communities/${communityId}`), + queryFn: () => + apiFetch(`/communities/${communityId}`, { auth: 'none' }), enabled: Boolean(communityId), }); } @@ -67,6 +69,7 @@ export function useMatches( queryFn: async () => { const response = await apiFetch( createMatchesPath(communityId, options), + { auth: 'none' }, ); return response.matches; }, @@ -78,7 +81,9 @@ export function useMatch(matchId: string | undefined, communityId = DEFAULT_COMM return useQuery({ queryKey: ['match', communityId, matchId ?? null], queryFn: () => - apiFetch(`/communities/${communityId}/matches/${matchId}`), + apiFetch(`/communities/${communityId}/matches/${matchId}`, { + auth: 'none', + }), enabled: Boolean(communityId && matchId), retry: false, }); @@ -91,7 +96,10 @@ export function useAuction( return useQuery({ queryKey: ['auction', communityId, matchId ?? null], queryFn: () => - apiFetch(`/communities/${communityId}/matches/${matchId}/auction`), + apiFetch( + `/communities/${communityId}/matches/${matchId}/auction`, + { auth: 'none' }, + ), enabled: Boolean(communityId && matchId), retry: false, }); @@ -128,6 +136,7 @@ export function useUserHistoryProfile( queryFn: () => apiFetch( `/communities/${communityId}/users/${userId}/history-profile`, + { auth: 'none' }, ), enabled: Boolean(communityId && userId), retry: false, @@ -151,6 +160,7 @@ export function useChampionStats( queryFn: () => apiFetch( createUserHistoryPath(communityId, userId ?? '', 'champion-stats', filters), + { auth: 'none' }, ), enabled: Boolean(communityId && userId), }); @@ -174,6 +184,7 @@ export function useRecentSummary( queryFn: () => apiFetch( createUserHistoryPath(communityId, userId ?? '', 'recent-summary', filters), + { auth: 'none' }, ), enabled: Boolean(communityId && userId), }); @@ -200,6 +211,7 @@ export function useRecentMatches( cursor: pageParam, limit: 10, }), + { auth: 'none' }, ), initialPageParam: null as number | null, getNextPageParam: (lastPage) => lastPage.nextCursor, @@ -232,6 +244,7 @@ export function useDdragonManifest(locale = 'ko_KR') { queryFn: () => apiFetch( `/riot/ddragon/manifest?locale=${encodeURIComponent(locale)}`, + { auth: 'none' }, ), staleTime: DDRAGON_MANIFEST_STALE_MS, gcTime: DDRAGON_MANIFEST_STALE_MS, @@ -260,6 +273,7 @@ export function useMe() { const response = await instance.acquireTokenSilent({ account, scopes: [MSAL_API_SCOPE], + redirectUri: MSAL_SILENT_REDIRECT_URI, }); return apiFetch('/me', { headers: { diff --git a/apps/web/src/pages/UserHistoryPage.tsx b/apps/web/src/pages/UserHistoryPage.tsx index 4d21ace4..02b29c70 100644 --- a/apps/web/src/pages/UserHistoryPage.tsx +++ b/apps/web/src/pages/UserHistoryPage.tsx @@ -1,6 +1,6 @@ -import { useMemo, useState } from 'react'; -import { useQueryClient } from '@tanstack/react-query'; -import { Link, useParams, useSearchParams } from 'react-router'; +import { useMemo, useState } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { Link, useParams, useSearchParams } from "react-router"; import { useChampionStats, useDdragonManifest, @@ -9,12 +9,9 @@ import { useRefreshUserHistory, useUserHistoryProfile, type UserHistoryFilters, -} from '../api/hooks'; -import { useRiotRefreshSocket } from '../api/useRiotRefreshSocket'; -import { - formatTierLabel, - getTierColorToken, -} from '../api/mappers'; +} from "../api/hooks"; +import { useRiotRefreshSocket } from "../api/useRiotRefreshSocket"; +import { formatTierLabel, getTierColorToken } from "../api/mappers"; import type { ApiChampionStatsRow, ApiEnqueueRefreshResult, @@ -23,54 +20,54 @@ import type { DdragonManifest, RiotQueueGroup, RiotRankFilter, -} from '../api/types'; -import { DEFAULT_COMMUNITY_ID } from '../config'; -import { ApiError } from '../lib/api'; +} from "../api/types"; +import { DEFAULT_COMMUNITY_ID } from "../config"; +import { ApiError } from "../lib/api"; import { championDisplayName, championIconUrl, itemIconUrl, profileIconUrl, -} from '../lib/ddragon'; +} from "../lib/ddragon"; import { isRiotQueueGroup, isRiotRankFilter, LANE_LABELS, QUEUE_GROUP_TABS, RANK_FILTER_TABS, -} from '../lib/riot-history'; +} from "../lib/riot-history"; -type ChampionSortKey = 'games' | 'winRate' | 'kda' | 'avgCsPerMin'; +type ChampionSortKey = "games" | "winRate" | "kda" | "avgCsPerMin"; const SORT_LABELS: Record = { - games: '게임 수', - winRate: '승률', - kda: 'KDA', - avgCsPerMin: '분당 CS', + games: "게임 수", + winRate: "승률", + kda: "KDA", + avgCsPerMin: "분당 CS", }; function formatDuration(seconds: number) { const minutes = Math.floor(seconds / 60); const rest = seconds % 60; - return `${minutes}:${String(rest).padStart(2, '0')}`; + return `${minutes}:${String(rest).padStart(2, "0")}`; } function formatDate(ms: number) { - return new Intl.DateTimeFormat('ko-KR', { - month: 'long', - day: 'numeric', - hour: '2-digit', - minute: '2-digit', + return new Intl.DateTimeFormat("ko-KR", { + month: "long", + day: "numeric", + hour: "2-digit", + minute: "2-digit", }).format(new Date(ms)); } function formatLastFetched(value: string | null | undefined) { - if (!value) return '저장된 갱신 시각 없음'; - return new Intl.DateTimeFormat('ko-KR', { - month: 'long', - day: 'numeric', - hour: '2-digit', - minute: '2-digit', + if (!value) return "저장된 갱신 시각 없음"; + return new Intl.DateTimeFormat("ko-KR", { + month: "long", + day: "numeric", + hour: "2-digit", + minute: "2-digit", }).format(new Date(value)); } @@ -83,28 +80,28 @@ function formatRefreshError(error: unknown) { if (error instanceof ApiError) { const data = error.data; if ( - typeof data === 'object' && + typeof data === "object" && data !== null && - 'retryAfterSeconds' in data && - typeof data.retryAfterSeconds === 'number' + "retryAfterSeconds" in data && + typeof data.retryAfterSeconds === "number" ) { return `잠시 후 다시 시도해 주세요. 약 ${formatEta(data.retryAfterSeconds)} 뒤에 요청할 수 있습니다.`; } return error.message; } - return error instanceof Error ? error.message : '갱신 요청에 실패했습니다.'; + return error instanceof Error ? error.message : "갱신 요청에 실패했습니다."; } function ratioClass(value: number) { - if (value >= 55) return 'text-blue-400'; - if (value >= 50) return 'text-amber-400'; - return 'text-base-content/50'; + if (value >= 55) return "text-blue-400"; + if (value >= 50) return "text-amber-400"; + return "text-base-content/50"; } function kdaClass(value: number) { - if (value >= 4) return 'text-amber-400'; - if (value >= 3) return 'text-emerald-400'; - return 'text-base-content/60'; + if (value >= 4) return "text-amber-400"; + if (value >= 3) return "text-emerald-400"; + return "text-base-content/60"; } function FilterButton({ @@ -122,8 +119,8 @@ function FilterButton({ onClick={onClick} className={`px-3 py-2 text-[12px] font-semibold border-b-2 transition-colors ${ active - ? 'border-primary text-primary bg-primary/5' - : 'border-transparent text-base-content/45 hover:text-base-content' + ? "border-primary text-primary bg-primary/5" + : "border-transparent text-base-content/45 hover:text-base-content" }`} > {children} @@ -134,15 +131,17 @@ function FilterButton({ function ChampionIcon({ championId, manifest, - size = 'md', + size = "md", }: { championId: number; manifest: DdragonManifest | null | undefined; - size?: 'sm' | 'md' | 'lg'; + size?: "sm" | "md" | "lg"; }) { const iconUrl = championIconUrl(manifest, championId); - const displayName = championDisplayName(manifest, championId) ?? String(championId); - const sizeClass = size === 'lg' ? 'w-12 h-12' : size === 'sm' ? 'w-5 h-5' : 'w-8 h-8'; + const displayName = + championDisplayName(manifest, championId) ?? String(championId); + const sizeClass = + size === "lg" ? "w-12 h-12" : size === "sm" ? "w-5 h-5" : "w-8 h-8"; return (
@@ -175,7 +174,9 @@ function SummaryCard({
{value}
- {sub &&
{sub}
} + {sub && ( +
{sub}
+ )}
); } @@ -231,23 +232,30 @@ function ChampionStatsTable({ >
- + {displayName}
- + {row.winRate}% {row.games} - {row.wins} /{' '} + {row.wins} /{" "} {row.losses} - + {row.kda} @@ -260,7 +268,8 @@ function ChampionStatsTable({ {row.totalAssists} - {row.doubleKills}/{row.tripleKills}/{row.quadraKills}/{row.pentaKills} + {row.doubleKills}/{row.tripleKills}/{row.quadraKills}/ + {row.pentaKills} {row.avgCs} · {row.avgCsPerMin}/m @@ -270,12 +279,14 @@ function ChampionStatsTable({ type="button" className={`text-[11px] px-2 py-1 border ${ selected - ? 'border-primary/40 bg-primary/10 text-primary' - : 'border-base-content/10 text-base-content/40 hover:text-base-content' + ? "border-primary/40 bg-primary/10 text-primary" + : "border-base-content/10 text-base-content/40 hover:text-base-content" }`} - onClick={() => onChampionSelect(selected ? null : row.championId)} + onClick={() => + onChampionSelect(selected ? null : row.championId) + } > - {selected ? '해제' : '보기'} + {selected ? "해제" : "보기"} @@ -332,7 +343,7 @@ function TeamMini({ {match.teams.map((team) => (
{team.participants.map((participant) => { const championName = @@ -369,15 +380,17 @@ function RecentMatchCard({ }) { const championName = championDisplayName(manifest, match.championId) ?? String(match.championId); - const accent = match.win ? 'border-l-blue-500' : 'border-l-red-500'; - const resultClass = match.win ? 'text-blue-400' : 'text-red-400'; + const accent = match.win ? "border-l-blue-500" : "border-l-red-500"; + const resultClass = match.win ? "text-blue-400" : "text-red-400"; return ( -
+
- {match.remake ? '다시하기' : match.win ? '승리' : '패배'} + {match.remake ? "다시하기" : match.win ? "승리" : "패배"}
{match.queueLabel} @@ -391,17 +404,22 @@ function RecentMatchCard({
- +
{championName}
- Lv.{match.championLevel} ·{' '} - {(LANE_LABELS[match.teamPosition] ?? match.teamPosition) || '포지션 없음'} + Lv.{match.championLevel} ·{" "} + {(LANE_LABELS[match.teamPosition] ?? match.teamPosition) || + "포지션 없음"}
- 스펠 {match.summonerSpells.join(' / ')} + 스펠 {match.summonerSpells.join(" / ")}
@@ -414,8 +432,10 @@ function RecentMatchCard({ / {match.assists}
-
- {match.deaths === 0 ? 'Perfect' : `${match.kda} 평점`} +
+ {match.deaths === 0 ? "Perfect" : `${match.kda} 평점`}
킬 관여 {match.killParticipation}% @@ -425,15 +445,21 @@ function RecentMatchCard({
- CS {match.totalCs}{' '} + CS{" "} + + {match.totalCs} + {" "} ({match.csPerMin}/m)
- 시야 {match.visionScore}{' '} + 시야{" "} + + {match.visionScore} + {" "} 제어와드 {match.controlWardsBought}
- 피해량{' '} + 피해량{" "} {match.damageDealtToChampions.toLocaleString()} @@ -446,7 +472,9 @@ function RecentMatchCard({
-
+
@@ -457,26 +485,27 @@ export default function UserHistoryPage() { const { userId } = useParams(); const queryClient = useQueryClient(); const [searchParams, setSearchParams] = useSearchParams(); - const [championSearch, setChampionSearch] = useState(''); - const [sortKey, setSortKey] = useState('games'); + const [championSearch, setChampionSearch] = useState(""); + const [sortKey, setSortKey] = useState("games"); const [refreshResult, setRefreshResult] = useState(null); const [refreshNotice, setRefreshNotice] = useState(null); - const queueGroupParam = searchParams.get('queueGroup'); - const rankParam = searchParams.get('rank'); + const queueGroupParam = searchParams.get("queueGroup"); + const rankParam = searchParams.get("rank"); const queueGroup: RiotQueueGroup = isRiotQueueGroup(queueGroupParam) ? queueGroupParam - : 'summoners-rift'; - const rank: RiotRankFilter = isRiotRankFilter(rankParam) ? rankParam : 'all'; - const championIdParam = Number(searchParams.get('championId')); - const championId = Number.isFinite(championIdParam) && championIdParam > 0 - ? championIdParam - : undefined; + : "summoners-rift"; + const rank: RiotRankFilter = isRiotRankFilter(rankParam) ? rankParam : "all"; + const championIdParam = Number(searchParams.get("championId")); + const championId = + Number.isFinite(championIdParam) && championIdParam > 0 + ? championIdParam + : undefined; const filters: UserHistoryFilters = { queueGroup, rank, championId, - seasonId: searchParams.get('seasonId') ?? undefined, + seasonId: searchParams.get("seasonId") ?? undefined, }; const aggregateFilters: UserHistoryFilters = { queueGroup, @@ -491,17 +520,21 @@ export default function UserHistoryPage() { DEFAULT_COMMUNITY_ID, ); const summaryQuery = useRecentSummary(userId, filters, DEFAULT_COMMUNITY_ID); - const recentMatchesQuery = useRecentMatches(userId, filters, DEFAULT_COMMUNITY_ID); + const recentMatchesQuery = useRecentMatches( + userId, + filters, + DEFAULT_COMMUNITY_ID, + ); const refreshMutation = useRefreshUserHistory(userId, DEFAULT_COMMUNITY_ID); const profile = profileQuery.data; const primaryTier = - profile?.tiers.find((tier) => tier.queueType === 'RANKED_SOLO_5x5') ?? + profile?.tiers.find((tier) => tier.queueType === "RANKED_SOLO_5x5") ?? profile?.tiers[0]; const matches = recentMatchesQuery.data?.pages.flatMap((page) => page.matches) ?? []; const selectedChampionName = championId - ? championDisplayName(ddragon, championId) ?? String(championId) + ? (championDisplayName(ddragon, championId) ?? String(championId)) : null; const visibleChampionRows = useMemo(() => { @@ -511,7 +544,8 @@ export default function UserHistoryPage() { .filter((row) => { if (!keyword) return true; const displayName = - championDisplayName(ddragon, row.championId) ?? String(row.championId); + championDisplayName(ddragon, row.championId) ?? + String(row.championId); return displayName.toLowerCase().includes(keyword); }) .sort((left, right) => right[sortKey] - left[sortKey]); @@ -523,14 +557,14 @@ export default function UserHistoryPage() { onEvent: (event: ApiRiotRefreshEvent) => { if (!profile || event.puuid !== profile.puuid) return; void invalidateHistoryQueries(); - if (event.state === 'completed') { - setRefreshNotice('갱신이 완료되어 전적을 다시 불러왔습니다.'); + if (event.state === "completed") { + setRefreshNotice("갱신이 완료되어 전적을 다시 불러왔습니다."); } - if (event.state === 'failed') { + if (event.state === "failed") { setRefreshNotice( event.error ? `갱신 실패: ${event.error}` - : '갱신에 실패했습니다. 잠시 후 다시 시도해 주세요.', + : "갱신에 실패했습니다. 잠시 후 다시 시도해 주세요.", ); } }, @@ -539,7 +573,7 @@ export default function UserHistoryPage() { function updateSearch(next: Partial>) { const params = new URLSearchParams(searchParams); for (const [key, value] of Object.entries(next)) { - if (value === null || value === undefined || value === '') { + if (value === null || value === undefined || value === "") { params.delete(key); } else { params.set(key, String(value)); @@ -551,16 +585,20 @@ export default function UserHistoryPage() { async function invalidateHistoryQueries() { await Promise.all([ queryClient.invalidateQueries({ - queryKey: ['user-history-profile', DEFAULT_COMMUNITY_ID, userId ?? null], + queryKey: [ + "user-history-profile", + DEFAULT_COMMUNITY_ID, + userId ?? null, + ], }), queryClient.invalidateQueries({ - queryKey: ['user-champion-stats', DEFAULT_COMMUNITY_ID, userId ?? null], + queryKey: ["user-champion-stats", DEFAULT_COMMUNITY_ID, userId ?? null], }), queryClient.invalidateQueries({ - queryKey: ['user-recent-summary', DEFAULT_COMMUNITY_ID, userId ?? null], + queryKey: ["user-recent-summary", DEFAULT_COMMUNITY_ID, userId ?? null], }), queryClient.invalidateQueries({ - queryKey: ['user-recent-matches', DEFAULT_COMMUNITY_ID, userId ?? null], + queryKey: ["user-recent-matches", DEFAULT_COMMUNITY_ID, userId ?? null], }), ]); } @@ -568,11 +606,13 @@ export default function UserHistoryPage() { function handleRefresh() { if (!userId) return; refreshMutation.mutate( - { queueGroups: [queueGroup], priority: 'high' }, + { queueGroups: [queueGroup], priority: "high" }, { onSuccess: (result) => { setRefreshResult(result); - const alreadyQueued = result.subJobs.every((job) => job.alreadyQueued); + const alreadyQueued = result.subJobs.every( + (job) => job.alreadyQueued, + ); setRefreshNotice( alreadyQueued ? `이미 갱신 작업이 대기 중입니다. 예상 ${formatEta(result.totalEtaSeconds)} 후 반영됩니다.` @@ -659,9 +699,10 @@ export default function UserHistoryPage() {
- 이 페이지는 저장된 경기 DB만 조회합니다. + {/* 이 페이지는 저장된 경기 DB만 조회합니다. */}
- Riot API 갱신은 버튼 클릭 시 큐에서 처리합니다. + {/* Riot API 갱신은 버튼 클릭 시 큐에서 처리합니다. */} + 아래 버튼을 누르면 기록이 갱신됩니다.
갱신 소켓: {refreshSocket.connectionStatus} @@ -689,7 +730,9 @@ export default function UserHistoryPage() { updateSearch({ queueGroup: tab.value, championId: null })} + onClick={() => + updateSearch({ queueGroup: tab.value, championId: null }) + } > {tab.label} @@ -701,7 +744,9 @@ export default function UserHistoryPage() { updateSearch({ rank: tab.value, championId: null })} + onClick={() => + updateSearch({ rank: tab.value, championId: null }) + } > {tab.label} @@ -751,19 +796,19 @@ export default function UserHistoryPage() { /> @@ -777,7 +822,9 @@ export default function UserHistoryPage() { type="button" key={champion.championId} className="text-center group" - onClick={() => updateSearch({ championId: champion.championId })} + onClick={() => + updateSearch({ championId: champion.championId }) + } > ))} {(summaryQuery.data?.topChampions ?? []).length === 0 && ( - 기록 없음 + + 기록 없음 + )}
@@ -799,11 +848,10 @@ export default function UserHistoryPage() {
-

- 챔피언 통계 -

+

챔피언 통계

- 저장된 매치 기준으로 집계합니다. Riot API 갱신은 별도 큐 작업으로 분리 예정입니다. + 저장된 데이터를 기준으로 집계합니다. 최신 데이터가 반영되지 않을 + 수 있습니다.

@@ -815,7 +863,9 @@ export default function UserHistoryPage() { />