Compare commits

...

2 Commits

Author SHA1 Message Date
0a7e5618ee feat: some changes and admin 2026-03-31 16:09:03 +09:00
7e07c7ea99 feat: modernized web application 2026-03-31 15:21:08 +09:00
87 changed files with 3717 additions and 103 deletions

21
.dockerignore Normal file
View File

@@ -0,0 +1,21 @@
# Dependencies and build outputs (reinstalled / rebuilt in image)
node_modules
**/node_modules
.next
**/.next
# Git
.git
.gitignore
# Other projects in the repo (not needed for the Next.js image)
main-web
tools
twitch_chat_reader
infra
# Misc
*.md
.env
.env.*
!.env.example

View File

@@ -1,63 +1,2 @@
#!/bin/sh
# create folder to pack all
echo "Starting build process..."
mkdir build
# build janken tool and move
cd tools/janken
echo "Starting janken tool build..."
npm run build
cd ../../
mv tools/janken/tool build
echo "Finished janken tool build..."
# build client and move
cd main-web/client
echo "Starting client build..."
npm run build
cd ../../
mv main-web/client/client build
echo "Finished client build..."
# build admin and move
cd main-web/admin
echo "Starting admin ui build..."
npm run build
cd ../../
mv main-web/admin/build build/admin
echo "Finished admin ui build..."
# build server and move
cd main-web/server
echo "Starting server build..."
npm run build
cd ../../
cd build/
echo "Starting retrieval of db credentials..."
export catherine_db_endpoint=$(aws --region=ap-northeast-1 ssm get-parameter --name "db-endpoint" --with-decryption --output text --query Parameter.Value)
export catherine_db_user=$(aws --region=ap-northeast-1 ssm get-parameter --name "db-username" --with-decryption --output text --query Parameter.Value)
export catherine_db_pass=$(aws --region=ap-northeast-1 ssm get-parameter --name "db-password" --with-decryption --output text --query Parameter.Value)
echo "Saving db credentials to .env file..."
cat > .env <<EOL
DB_ENDPOINT=${catherine_db_endpoint}
DB_USER=${catherine_db_user}
DB_PASS=${catherine_db_pass}
EOL
cd ../
cp main-web/server/package.json build/
cp main-web/server/tsconfig.json build/
cp main-web/server/tslint.json build/
mv main-web/server/build build/server
echo "Finished server build..."
echo "Compressing all files..."
tar czf build.tar.gz build/
echo "Finished compressing all files..."
echo "Removing workfolder..."
rm -rf build/
echo "Removed workfolder..."
echo "Upload built files to s3..."
aws s3 cp build.tar.gz s3://catherine-fc-infra/
echo "Finished build process..."
APP_VERSION=1.0.1
docker buildx build --platform linux/arm64 -f nextjs/Dockerfile -t cfc-web:$APP_VERSION .

View File

@@ -1,40 +0,0 @@
#!/bin/sh
# create folder to pack all
echo "Starting build process..."
mkdir build
# build janken tool and move
cd tools/janken
echo "Starting janken tool build..."
npm install
npm run build
cd ../../
mv tools/janken/tool build
echo "Finished janken tool build..."
# build client and move
cd main-web/client
echo "Starting client build..."
npm install
npm run build
cd ../../
mv main-web/client/client build/client
echo "Finished client build..."
# build server and move
cd main-web/server
echo "Starting server build..."
npm install
npm run build
cd ../../
cd build/
echo "Saving db credentials to .env file..."
cd ../
cp main-web/server/package.json build/
cp main-web/server/tsconfig.json build/
cp main-web/server/tslint.json build/
mv main-web/server/build build/server
echo "Finished server build..."

42
infra/db/admin_auth.sql Normal file
View File

@@ -0,0 +1,42 @@
-- Admin users and sessions for the Next.js admin area.
-- Run after catherine_league schema exists: mysql ... < admin_auth.sql
USE `catherine_league`;
-- Passwords stored as bcrypt hashes (e.g. from bcryptjs), never plaintext.
CREATE TABLE IF NOT EXISTS `admin_users` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`email` VARCHAR(255) NOT NULL,
`password_hash` VARCHAR(255) NOT NULL,
`is_approved` TINYINT(1) NOT NULL DEFAULT 0,
`is_admin` TINYINT(1) NOT NULL DEFAULT 0,
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_admin_users_email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Opaque session tokens: store SHA-256 hex of the cookie value; never store raw tokens.
CREATE TABLE IF NOT EXISTS `admin_sessions` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` INT UNSIGNED NOT NULL,
`token_hash` CHAR(64) NOT NULL,
`expires_at` DATETIME NOT NULL,
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_admin_sessions_token_hash` (`token_hash`),
KEY `idx_admin_sessions_user_id` (`user_id`),
KEY `idx_admin_sessions_expires_at` (`expires_at`),
CONSTRAINT `fk_admin_sessions_user`
FOREIGN KEY (`user_id`) REFERENCES `admin_users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Seed: first admin (change password immediately in production).
-- Default password: ChangeMeOnFirstLogin!
INSERT INTO `admin_users` (`email`, `password_hash`, `is_approved`, `is_admin`)
SELECT
'admin@localhost',
'$2b$12$H6Y71zX/nmefp33e0MaMaOOBGSiVwxVE3L.Ie3Pfq1/6QZdLR7bTa',
1,
1
WHERE NOT EXISTS (SELECT 1 FROM `admin_users` WHERE `email` = 'admin@localhost' LIMIT 1);

7
nextjs/.env.example Normal file
View File

@@ -0,0 +1,7 @@
# MySQL (same as main-web/server)
DB_ENDPOINT=localhost
DB_PORT=3306
DB_USER=
DB_PASS=
# After DB is up, apply admin tables (see infra/db/admin_auth.sql)

3
nextjs/.eslintrc.json Normal file
View File

@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}

7
nextjs/.gitignore vendored Normal file
View File

@@ -0,0 +1,7 @@
/node_modules
/.next/
/out/
.env
.env.local
.env.*.local
*.tsbuildinfo

66
nextjs/Dockerfile Normal file
View File

@@ -0,0 +1,66 @@
# syntax=docker/dockerfile:1
#
# Target: linux/arm64 (ARMv8 / aarch64). Build from the repository root:
# docker build -f nextjs/Dockerfile -t catherine-league-web .
# Cross-build from amd64 (optional, requires QEMU/binfmt, e.g. Docker Desktop / buildx):
# docker buildx build --platform linux/arm64 -f nextjs/Dockerfile -t catherine-league-web .
#
# Run (set DB_* env vars as needed):
# docker run --rm -p 3000:3000 \
# -e DB_ENDPOINT=host.docker.internal \
# -e DB_PORT=3306 \
# -e DB_USER=... \
# -e DB_PASS=... \
# catherine-league-web
FROM arm64v8/node:24-alpine AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json package-lock.json ./
COPY nextjs/package.json ./nextjs/
RUN npm ci
FROM arm64v8/node:24-alpine AS builder
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY --from=deps /app/package.json ./package.json
COPY --from=deps /app/package-lock.json ./package-lock.json
COPY nextjs ./nextjs
ENV NEXT_TELEMETRY_DISABLED=1
RUN npm run build -w catherine-league-nextjs
FROM arm64v8/node:24-alpine AS runner
RUN apk add --no-cache libc6-compat
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
RUN addgroup --system --gid 1001 nodejs \
&& adduser --system --uid 1001 nextjs
COPY --from=builder /app/nextjs/public ./nextjs/public
COPY --from=builder /app/nextjs/.next/standalone ./
COPY --from=builder /app/nextjs/.next/static ./nextjs/.next/static
RUN chown -R nextjs:nodejs /app
USER nextjs
EXPOSE 3000
ENV PORT=3000
ENV HOSTNAME=0.0.0.0
WORKDIR /app/nextjs
CMD ["node", "server.js"]

6
nextjs/next-env.d.ts vendored Normal file
View File

@@ -0,0 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.

15
nextjs/next.config.mjs Normal file
View File

@@ -0,0 +1,15 @@
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'standalone',
outputFileTracingRoot: path.join(__dirname, '..'),
sassOptions: {
includePaths: ['src/styles'],
},
};
export default nextConfig;

33
nextjs/package.json Normal file
View File

@@ -0,0 +1,33 @@
{
"name": "catherine-league-nextjs",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"bcryptjs": "^3.0.3",
"dotenv": "^16.4.5",
"i18next": "^23.10.1",
"mysql2": "^3.11.0",
"next": "^15.5.14",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-i18next": "^14.1.0",
"react-youtube": "^10.1.0",
"semantic-ui-css": "^2.5.0"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.6",
"@types/node": "^20.14.10",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"eslint": "^8.57.0",
"eslint-config-next": "^15.5.14",
"sass": "^1.77.8",
"typescript": "^5.5.4"
}
}

View File

@@ -0,0 +1,9 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [],
"start_url": ".",
"display": "standalone",
"theme_color": "#ff2d7c",
"background_color": "#ffffff"
}

3
nextjs/public/robots.txt Normal file
View File

@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View File

@@ -0,0 +1,34 @@
import style from '@/styles/web.module.scss';
export default function AboutPage() {
return (
<div className={style.guideBody}>
<h2>About</h2>
<hr />
<div className={style.aboutNoticeBlock}>
<br />
<p>
Covid-19
</p>
<p>
Switch版0
</p>
<p>
使
</p>
<p></p>
<p>
</p>
<p></p>
<div className={style.sheepAbout} />
<div className={style.aboutContactBox}>
<a href="https://forms.gle/Dn4p7cFEPLK1zcTz5" rel="noopener noreferrer" target="_blank">
&nbsp;
</a>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,9 @@
import { ArchiveVideoList } from '@/components/ArchiveVideoList';
import { getArchiveItems } from '@/lib/data';
export const dynamic = 'force-dynamic';
export default async function ArchivePage() {
const items = await getArchiveItems();
return <ArchiveVideoList items={items} />;
}

View File

@@ -0,0 +1,9 @@
import { ContactList } from '@/components/ContactList';
import { getContactItems } from '@/lib/data';
export const dynamic = 'force-dynamic';
export default async function ContactPage() {
const items = await getContactItems();
return <ContactList items={items} />;
}

View File

@@ -0,0 +1,9 @@
import { GuideVideoList } from '@/components/GuideVideoList';
import { getGuideItems } from '@/lib/data';
export const dynamic = 'force-dynamic';
export default async function GuidePage() {
const items = await getGuideItems();
return <GuideVideoList items={items} />;
}

View File

@@ -0,0 +1,7 @@
import type { ReactNode } from 'react';
import { SiteLayout } from '@/components/SiteLayout';
export default function SiteChromeLayout({ children }: { children: ReactNode }) {
return <SiteLayout>{children}</SiteLayout>;
}

View File

@@ -0,0 +1,34 @@
import style from '@/styles/web.module.scss';
export default function HomePage() {
return (
<div className={style.mainBody}>
<div className={style.evojapan2026} />
<div className={style.padding} />
<div className={style.evojapan2023kaisaikettei} />
<div className={style.padding} />
<div className={style.group}>
<div className={style.evojapan2023catherinetonamel}>
<a href="https://tonamel.com/competition/u2GRP" rel="noopener noreferrer" target="_blank">
&nbsp;
</a>
</div>
<div className={style.evojapan2023catherinefullbodytonamel}>
<a href="https://tonamel.com/competition/BxuNE" rel="noopener noreferrer" target="_blank">
&nbsp;
</a>
</div>
</div>
<div className={style.padding} />
<div className={style.twitchHome}>
<a
href="https://www.twitch.tv/catherine_faito_crab"
rel="noopener noreferrer"
target="_blank"
>
&nbsp;
</a>
</div>
</div>
);
}

View File

@@ -0,0 +1,9 @@
import { PlayersList } from '@/components/PlayersList';
import { getAllPlayers } from '@/lib/data';
export const dynamic = 'force-dynamic';
export default async function PlayersPage() {
const players = await getAllPlayers();
return <PlayersList players={players} />;
}

View File

@@ -0,0 +1,19 @@
import { notFound } from 'next/navigation';
import { PlayersList } from '@/components/PlayersList';
import { getPlayersForTournament } from '@/lib/data';
export const dynamic = 'force-dynamic';
type PageProps = {
params: Promise<{ tournament_key: string }>;
};
export default async function TournamentPlayersPage({ params }: PageProps) {
const { tournament_key } = await params;
const players = await getPlayersForTournament(tournament_key);
if (players === null) {
notFound();
}
return <PlayersList players={players} />;
}

View File

@@ -0,0 +1,9 @@
import style from '@/styles/web.module.scss';
export default function ScoreboardPage() {
return (
<div className={style.mainBody}>
<div className={style.scoreboardImage} />
</div>
);
}

View File

@@ -0,0 +1,7 @@
export default function TournamentsPage() {
return (
<div>
<p>Tournaments</p>
</div>
);
}

View File

@@ -0,0 +1,147 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import style from '@/styles/admin.module.scss';
type ArchiveRow = {
id: number;
title: string;
youtube_id: string;
};
export function ArchiveAdminClient() {
const [items, setItems] = useState<ArchiveRow[]>([]);
const [error, setError] = useState('');
const [loading, setLoading] = useState(true);
const [title, setTitle] = useState('');
const [youtubeId, setYoutubeId] = useState('');
const load = useCallback(async () => {
setError('');
const res = await fetch('/api/admin/archive', { credentials: 'include' });
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError((data as { error?: string }).error ?? 'Failed to load');
setLoading(false);
return;
}
setItems((data as { items: ArchiveRow[] }).items ?? []);
setLoading(false);
}, []);
useEffect(() => {
load();
}, [load]);
function updateLocal(id: number, patch: Partial<ArchiveRow>) {
setItems((prev) => prev.map((r) => (r.id === id ? { ...r, ...patch } : r)));
}
async function save(row: ArchiveRow) {
setError('');
const res = await fetch(`/api/admin/archive/${row.id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ title: row.title, youtube_id: row.youtube_id }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError((data as { error?: string }).error ?? 'Save failed');
return;
}
await load();
}
async function remove(id: number) {
if (!window.confirm('Delete?')) return;
setError('');
const res = await fetch(`/api/admin/archive/${id}`, { method: 'DELETE', credentials: 'include' });
if (!res.ok) {
const data = await res.json().catch(() => ({}));
setError((data as { error?: string }).error ?? 'Delete failed');
return;
}
await load();
}
async function add(e: React.FormEvent) {
e.preventDefault();
setError('');
const res = await fetch('/api/admin/archive', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ title, youtube_id: youtubeId }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError((data as { error?: string }).error ?? 'Create failed');
return;
}
setTitle('');
setYoutubeId('');
await load();
}
return (
<div className={style.card}>
<p>
<Link href="/admin"> Dashboard</Link>
</p>
<h1 className={style.title}>Archive</h1>
{error ? <p className={style.error}>{error}</p> : null}
{loading ? <p>Loading</p> : null}
{!loading &&
items.map((row) => (
<div key={row.id} style={{ marginBottom: 24, paddingBottom: 16, borderBottom: '1px solid #eee' }}>
<label className={style.label}>
title
<input
className={style.input}
value={row.title}
onChange={(e) => updateLocal(row.id, { title: e.target.value })}
/>
</label>
<label className={style.label}>
youtube_id
<input
className={style.input}
value={row.youtube_id}
onChange={(e) => updateLocal(row.id, { youtube_id: e.target.value })}
/>
</label>
<div className={style.rowActions}>
<button type="button" className={style.btn} onClick={() => save(row)}>
Save
</button>
<button type="button" className={style.btnDanger} onClick={() => remove(row.id)}>
Delete
</button>
</div>
</div>
))}
<hr className={style.hr} />
<h2 className={style.title} style={{ fontSize: '1.1rem' }}>
New entry
</h2>
<form className={style.form} style={{ maxWidth: 480 }} onSubmit={add}>
<label className={style.label}>
title
<input className={style.input} value={title} onChange={(e) => setTitle(e.target.value)} required />
</label>
<label className={style.label}>
youtube_id
<input className={style.input} value={youtubeId} onChange={(e) => setYoutubeId(e.target.value)} required />
</label>
<button className={style.btn} type="submit">
Add
</button>
</form>
</div>
);
}

View File

@@ -0,0 +1,8 @@
import { requireAdmin } from '@/lib/auth/requireAdmin';
import { ArchiveAdminClient } from './ArchiveAdminClient';
export default async function AdminArchivePage() {
await requireAdmin();
return <ArchiveAdminClient />;
}

View File

@@ -0,0 +1,170 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import style from '@/styles/admin.module.scss';
type GuideRow = {
id: number;
title: string;
description: string | null;
youtube_id: string;
};
export function GuideAdminClient() {
const [items, setItems] = useState<GuideRow[]>([]);
const [error, setError] = useState('');
const [loading, setLoading] = useState(true);
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [youtubeId, setYoutubeId] = useState('');
const load = useCallback(async () => {
setError('');
const res = await fetch('/api/admin/guide', { credentials: 'include' });
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError((data as { error?: string }).error ?? 'Failed to load');
setLoading(false);
return;
}
setItems((data as { items: GuideRow[] }).items ?? []);
setLoading(false);
}, []);
useEffect(() => {
load();
}, [load]);
function updateLocal(id: number, patch: Partial<GuideRow>) {
setItems((prev) => prev.map((r) => (r.id === id ? { ...r, ...patch } : r)));
}
async function save(row: GuideRow) {
setError('');
const res = await fetch(`/api/admin/guide/${row.id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
title: row.title,
description: row.description ?? '',
youtube_id: row.youtube_id,
}),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError((data as { error?: string }).error ?? 'Save failed');
return;
}
await load();
}
async function remove(id: number) {
if (!window.confirm('Delete this entry?')) return;
setError('');
const res = await fetch(`/api/admin/guide/${id}`, { method: 'DELETE', credentials: 'include' });
if (!res.ok) {
const data = await res.json().catch(() => ({}));
setError((data as { error?: string }).error ?? 'Delete failed');
return;
}
await load();
}
async function add(e: React.FormEvent) {
e.preventDefault();
setError('');
const res = await fetch('/api/admin/guide', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ title, description, youtube_id: youtubeId }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError((data as { error?: string }).error ?? 'Create failed');
return;
}
setTitle('');
setDescription('');
setYoutubeId('');
await load();
}
return (
<div className={style.card}>
<p>
<Link href="/admin"> Dashboard</Link>
</p>
<h1 className={style.title}>Guide</h1>
{error ? <p className={style.error}>{error}</p> : null}
{loading ? <p>Loading</p> : null}
{!loading &&
items.map((row) => (
<div key={row.id} style={{ marginBottom: 24, paddingBottom: 16, borderBottom: '1px solid #eee' }}>
<label className={style.label}>
title
<input
className={style.input}
value={row.title}
onChange={(e) => updateLocal(row.id, { title: e.target.value })}
/>
</label>
<label className={style.label}>
description
<textarea
className={`${style.input} ${style.textarea}`}
value={row.description ?? ''}
onChange={(e) => updateLocal(row.id, { description: e.target.value })}
/>
</label>
<label className={style.label}>
youtube_id
<input
className={style.input}
value={row.youtube_id}
onChange={(e) => updateLocal(row.id, { youtube_id: e.target.value })}
/>
</label>
<div className={style.rowActions}>
<button type="button" className={style.btn} onClick={() => save(row)}>
Save
</button>
<button type="button" className={style.btnDanger} onClick={() => remove(row.id)}>
Delete
</button>
</div>
</div>
))}
<hr className={style.hr} />
<h2 className={style.title} style={{ fontSize: '1.1rem' }}>
New entry
</h2>
<form className={style.form} style={{ maxWidth: 480 }} onSubmit={add}>
<label className={style.label}>
title
<input className={style.input} value={title} onChange={(e) => setTitle(e.target.value)} required />
</label>
<label className={style.label}>
description
<textarea
className={`${style.input} ${style.textarea}`}
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</label>
<label className={style.label}>
youtube_id
<input className={style.input} value={youtubeId} onChange={(e) => setYoutubeId(e.target.value)} required />
</label>
<button className={style.btn} type="submit">
Add
</button>
</form>
</div>
);
}

View File

@@ -0,0 +1,8 @@
import { requireAdmin } from '@/lib/auth/requireAdmin';
import { GuideAdminClient } from './GuideAdminClient';
export default async function AdminGuidePage() {
await requireAdmin();
return <GuideAdminClient />;
}

View File

@@ -0,0 +1,8 @@
import type { ReactNode } from 'react';
import { requireLogin } from '@/lib/auth/requireAdmin';
export default async function AdminDashboardLayout({ children }: { children: ReactNode }) {
await requireLogin();
return <>{children}</>;
}

View File

@@ -0,0 +1,49 @@
import Link from 'next/link';
import { LogoutButton } from '@/components/admin/LogoutButton';
import { getSessionUser } from '@/lib/auth/session';
import style from '@/styles/admin.module.scss';
export default async function AdminDashboardPage() {
const user = await getSessionUser();
if (!user) {
return null;
}
return (
<div className={style.card}>
<h1 className={style.title}>Admin</h1>
<p className={style.sub}>
Signed in as <strong>{user.email}</strong>
{user.is_admin ? ' (administrator)' : ''}
</p>
{!user.is_admin && (
<p className={style.error}>
You do not have permission to edit content. Ask an administrator to grant admin access.
</p>
)}
{user.is_admin && (
<ul style={{ lineHeight: 1.8 }}>
<li>
<Link href="/admin/users">Users (approval &amp; roles)</Link>
</li>
<li>
<Link href="/admin/players">Players</Link>
</li>
<li>
<Link href="/admin/guide">Guide</Link>
</li>
<li>
<Link href="/admin/archive">Archive</Link>
</li>
<li>
<Link href="/admin/qa">Q&amp;A</Link>
</li>
</ul>
)}
<div style={{ marginTop: 16 }}>
<LogoutButton />
</div>
</div>
);
}

View File

@@ -0,0 +1,184 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import style from '@/styles/admin.module.scss';
type Char = { id: number; name_id: string; name: string; name_jp: string };
type PlayerRow = {
id: number;
player_key: string;
player_name: string;
description: string | null;
image: string | null;
character_id: string | null;
name_id?: string;
name_jp?: string;
};
export function PlayersAdminClient() {
const [players, setPlayers] = useState<PlayerRow[]>([]);
const [characters, setCharacters] = useState<Char[]>([]);
const [error, setError] = useState('');
const [loading, setLoading] = useState(true);
const [playerKey, setPlayerKey] = useState('');
const [playerName, setPlayerName] = useState('');
const [description, setDescription] = useState('');
const [image, setImage] = useState('');
const [characterId, setCharacterId] = useState('');
const load = useCallback(async () => {
setError('');
const [pr, cr] = await Promise.all([
fetch('/api/admin/players', { credentials: 'include' }),
fetch('/api/admin/characters', { credentials: 'include' }),
]);
const pj = await pr.json().catch(() => ({}));
const cj = await cr.json().catch(() => ({}));
if (!pr.ok) {
setError((pj as { error?: string }).error ?? 'Failed to load players');
setLoading(false);
return;
}
if (!cr.ok) {
setError((cj as { error?: string }).error ?? 'Failed to load characters');
setLoading(false);
return;
}
setPlayers((pj as { players: PlayerRow[] }).players ?? []);
setCharacters((cj as { characters: Char[] }).characters ?? []);
setLoading(false);
}, []);
useEffect(() => {
load();
}, [load]);
async function addPlayer(e: React.FormEvent) {
e.preventDefault();
setError('');
const res = await fetch('/api/admin/players', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
player_key: playerKey,
player_name: playerName,
description,
image: image || null,
character_id: characterId,
}),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError((data as { error?: string }).error ?? 'Create failed');
return;
}
setPlayerKey('');
setPlayerName('');
setDescription('');
setImage('');
setCharacterId('');
await load();
}
async function remove(id: number) {
if (!window.confirm('Delete this player?')) return;
setError('');
const res = await fetch(`/api/admin/players/${id}`, { method: 'DELETE', credentials: 'include' });
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError((data as { error?: string }).error ?? 'Delete failed');
return;
}
await load();
}
return (
<div className={style.card}>
<p>
<Link href="/admin"> Dashboard</Link>
</p>
<h1 className={style.title}>Players</h1>
{error ? <p className={style.error}>{error}</p> : null}
{loading ? <p>Loading</p> : null}
{!loading && (
<>
<table className={style.table}>
<thead>
<tr>
<th>Key</th>
<th>Name</th>
<th>Character</th>
<th />
</tr>
</thead>
<tbody>
{players.map((p) => (
<tr key={p.id}>
<td>{p.player_key}</td>
<td>{p.player_name}</td>
<td>{p.name_jp ?? p.character_id}</td>
<td>
<button type="button" className={style.btnDanger} onClick={() => remove(p.id)}>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
<hr className={style.hr} />
<h2 className={style.title} style={{ fontSize: '1.1rem' }}>
Add player
</h2>
<form className={style.form} style={{ maxWidth: 480 }} onSubmit={addPlayer}>
<label className={style.label}>
player_key
<input className={style.input} value={playerKey} onChange={(e) => setPlayerKey(e.target.value)} required />
</label>
<label className={style.label}>
player_name
<input className={style.input} value={playerName} onChange={(e) => setPlayerName(e.target.value)} required />
</label>
<label className={style.label}>
description
<textarea
className={`${style.input} ${style.textarea}`}
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</label>
<label className={style.label}>
image URL (optional)
<input className={style.input} value={image} onChange={(e) => setImage(e.target.value)} />
</label>
<label className={style.label}>
character
<select
className={style.input}
value={characterId}
onChange={(e) => setCharacterId(e.target.value)}
required
>
<option value=""></option>
{characters.map((c) => (
<option key={c.id} value={c.id}>
{c.name_jp} ({c.name_id})
</option>
))}
</select>
</label>
<button className={style.btn} type="submit">
Add
</button>
</form>
</>
)}
</div>
);
}

View File

@@ -0,0 +1,8 @@
import { requireAdmin } from '@/lib/auth/requireAdmin';
import { PlayersAdminClient } from './PlayersAdminClient';
export default async function AdminPlayersPage() {
await requireAdmin();
return <PlayersAdminClient />;
}

View File

@@ -0,0 +1,157 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import style from '@/styles/admin.module.scss';
type ContactRow = {
id: number;
question: string;
answer: string;
};
export function QaAdminClient() {
const [items, setItems] = useState<ContactRow[]>([]);
const [error, setError] = useState('');
const [loading, setLoading] = useState(true);
const [question, setQuestion] = useState('');
const [answer, setAnswer] = useState('');
const load = useCallback(async () => {
setError('');
const res = await fetch('/api/admin/contact', { credentials: 'include' });
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError((data as { error?: string }).error ?? 'Failed to load');
setLoading(false);
return;
}
setItems((data as { items: ContactRow[] }).items ?? []);
setLoading(false);
}, []);
useEffect(() => {
load();
}, [load]);
function updateLocal(id: number, patch: Partial<ContactRow>) {
setItems((prev) => prev.map((r) => (r.id === id ? { ...r, ...patch } : r)));
}
async function save(row: ContactRow) {
setError('');
const res = await fetch(`/api/admin/contact/${row.id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ question: row.question, answer: row.answer }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError((data as { error?: string }).error ?? 'Save failed');
return;
}
await load();
}
async function remove(id: number) {
if (!window.confirm('Delete?')) return;
setError('');
const res = await fetch(`/api/admin/contact/${id}`, { method: 'DELETE', credentials: 'include' });
if (!res.ok) {
const data = await res.json().catch(() => ({}));
setError((data as { error?: string }).error ?? 'Delete failed');
return;
}
await load();
}
async function add(e: React.FormEvent) {
e.preventDefault();
setError('');
const res = await fetch('/api/admin/contact', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ question, answer }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError((data as { error?: string }).error ?? 'Create failed');
return;
}
setQuestion('');
setAnswer('');
await load();
}
return (
<div className={style.card}>
<p>
<Link href="/admin"> Dashboard</Link>
</p>
<h1 className={style.title}>Q&amp;A</h1>
{error ? <p className={style.error}>{error}</p> : null}
{loading ? <p>Loading</p> : null}
{!loading &&
items.map((row) => (
<div key={row.id} style={{ marginBottom: 24, paddingBottom: 16, borderBottom: '1px solid #eee' }}>
<label className={style.label}>
question
<textarea
className={`${style.input} ${style.textarea}`}
value={row.question}
onChange={(e) => updateLocal(row.id, { question: e.target.value })}
/>
</label>
<label className={style.label}>
answer
<textarea
className={`${style.input} ${style.textarea}`}
value={row.answer}
onChange={(e) => updateLocal(row.id, { answer: e.target.value })}
/>
</label>
<div className={style.rowActions}>
<button type="button" className={style.btn} onClick={() => save(row)}>
Save
</button>
<button type="button" className={style.btnDanger} onClick={() => remove(row.id)}>
Delete
</button>
</div>
</div>
))}
<hr className={style.hr} />
<h2 className={style.title} style={{ fontSize: '1.1rem' }}>
New Q&amp;A
</h2>
<form className={style.form} style={{ maxWidth: 480 }} onSubmit={add}>
<label className={style.label}>
question
<textarea
className={`${style.input} ${style.textarea}`}
value={question}
onChange={(e) => setQuestion(e.target.value)}
required
/>
</label>
<label className={style.label}>
answer
<textarea
className={`${style.input} ${style.textarea}`}
value={answer}
onChange={(e) => setAnswer(e.target.value)}
required
/>
</label>
<button className={style.btn} type="submit">
Add
</button>
</form>
</div>
);
}

View File

@@ -0,0 +1,8 @@
import { requireAdmin } from '@/lib/auth/requireAdmin';
import { QaAdminClient } from './QaAdminClient';
export default async function AdminQaPage() {
await requireAdmin();
return <QaAdminClient />;
}

View File

@@ -0,0 +1,100 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import style from '@/styles/admin.module.scss';
type UserRow = {
id: number;
email: string;
is_approved: number | boolean;
is_admin: number | boolean;
created_at: string;
};
export function UsersAdminClient() {
const [users, setUsers] = useState<UserRow[]>([]);
const [error, setError] = useState('');
const [loading, setLoading] = useState(true);
const load = useCallback(async () => {
setError('');
const res = await fetch('/api/admin/users', { credentials: 'include' });
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError((data as { error?: string }).error ?? 'Failed to load');
setLoading(false);
return;
}
setUsers((data as { users: UserRow[] }).users ?? []);
setLoading(false);
}, []);
useEffect(() => {
load();
}, [load]);
async function patch(id: number, body: { is_approved?: boolean; is_admin?: boolean }) {
setError('');
const res = await fetch(`/api/admin/users/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(body),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError((data as { error?: string }).error ?? 'Update failed');
return;
}
await load();
}
return (
<div className={style.card}>
<p>
<Link href="/admin"> Dashboard</Link>
</p>
<h1 className={style.title}>Users</h1>
<p className={style.sub}>Approve new accounts and grant admin role.</p>
{error ? <p className={style.error}>{error}</p> : null}
{loading ? <p>Loading</p> : null}
{!loading && (
<table className={style.table}>
<thead>
<tr>
<th>Email</th>
<th>Approved</th>
<th>Admin</th>
<th>Created</th>
</tr>
</thead>
<tbody>
{users.map((u) => (
<tr key={u.id}>
<td>{u.email}</td>
<td>
<input
type="checkbox"
checked={Boolean(u.is_approved)}
onChange={(e) => patch(u.id, { is_approved: e.target.checked })}
/>
</td>
<td>
<input
type="checkbox"
checked={Boolean(u.is_admin)}
onChange={(e) => patch(u.id, { is_admin: e.target.checked })}
/>
</td>
<td>{String(u.created_at)}</td>
</tr>
))}
</tbody>
</table>
)}
</div>
);
}

View File

@@ -0,0 +1,8 @@
import { requireAdmin } from '@/lib/auth/requireAdmin';
import { UsersAdminClient } from './UsersAdminClient';
export default async function AdminUsersPage() {
await requireAdmin();
return <UsersAdminClient />;
}

View File

@@ -0,0 +1,25 @@
import type { Metadata } from 'next';
import type { ReactNode } from 'react';
import Link from 'next/link';
import style from '@/styles/admin.module.scss';
export const metadata: Metadata = {
title: 'Admin — Catherine League',
robots: 'noindex, nofollow',
};
export default function AdminRootLayout({ children }: { children: ReactNode }) {
return (
<div className={style.wrap}>
<nav className={style.nav}>
<Link href="/"> Site</Link>
<Link href="/admin/login">Login</Link>
<Link href="/admin/register">Register</Link>
<Link href="/admin">Dashboard</Link>
</nav>
{children}
</div>
);
}

View File

@@ -0,0 +1,78 @@
'use client';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import Link from 'next/link';
import style from '@/styles/admin.module.scss';
export default function AdminLoginPage() {
const router = useRouter();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
async function onSubmit(e: React.FormEvent) {
e.preventDefault();
setError('');
setLoading(true);
try {
const res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
credentials: 'include',
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError((data as { error?: string }).error ?? 'Login failed');
setLoading(false);
return;
}
router.push('/admin');
router.refresh();
} catch {
setError('Network error');
}
setLoading(false);
}
return (
<div className={style.card}>
<h1 className={style.title}>Admin login</h1>
<p className={style.sub}>
No account? <Link href="/admin/register">Register</Link> an administrator must approve you before you can sign in.
</p>
<form className={style.form} onSubmit={onSubmit}>
<label className={style.label}>
Email
<input
className={style.input}
type="email"
autoComplete="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</label>
<label className={style.label}>
Password
<input
className={style.input}
type="password"
autoComplete="current-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</label>
{error ? <p className={style.error}>{error}</p> : null}
<button className={style.btn} type="submit" disabled={loading}>
{loading ? 'Signing in…' : 'Sign in'}
</button>
</form>
</div>
);
}

View File

@@ -0,0 +1,18 @@
import Link from 'next/link';
import style from '@/styles/admin.module.scss';
export default function AdminNoAccessPage() {
return (
<div className={style.card}>
<h1 className={style.title}>No admin access</h1>
<p className={style.sub}>
Your account is approved, but you do not have administrator privileges for content management. Ask an existing admin to
grant you the admin role.
</p>
<p>
<Link href="/admin">Dashboard</Link>
</p>
</div>
);
}

View File

@@ -0,0 +1,18 @@
import Link from 'next/link';
import style from '@/styles/admin.module.scss';
export default function AdminPendingPage() {
return (
<div className={style.card}>
<h1 className={style.title}>Account pending</h1>
<p className={style.sub}>
Your account has not been approved yet, or approval was revoked. You cannot use the admin area until an administrator
approves you.
</p>
<p>
<Link href="/admin/login">Back to login</Link>
</p>
</div>
);
}

View File

@@ -0,0 +1,81 @@
'use client';
import { useState } from 'react';
import Link from 'next/link';
import style from '@/styles/admin.module.scss';
export default function AdminRegisterPage() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [success, setSuccess] = useState('');
const [loading, setLoading] = useState(false);
async function onSubmit(e: React.FormEvent) {
e.preventDefault();
setError('');
setSuccess('');
setLoading(true);
try {
const res = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError((data as { error?: string }).error ?? 'Registration failed');
setLoading(false);
return;
}
setSuccess((data as { message?: string }).message ?? 'Registered.');
setEmail('');
setPassword('');
} catch {
setError('Network error');
}
setLoading(false);
}
return (
<div className={style.card}>
<h1 className={style.title}>Register</h1>
<p className={style.sub}>
After registering, wait for an administrator to approve your account. Then you can{' '}
<Link href="/admin/login">sign in</Link>.
</p>
<form className={style.form} onSubmit={onSubmit}>
<label className={style.label}>
Email
<input
className={style.input}
type="email"
autoComplete="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</label>
<label className={style.label}>
Password (min. 8 characters)
<input
className={style.input}
type="password"
autoComplete="new-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
minLength={8}
required
/>
</label>
{error ? <p className={style.error}>{error}</p> : null}
{success ? <p className={style.success}>{success}</p> : null}
<button className={style.btn} type="submit" disabled={loading}>
{loading ? 'Submitting…' : 'Register'}
</button>
</form>
</div>
);
}

View File

@@ -0,0 +1,63 @@
import { NextResponse } from 'next/server';
import type { RowDataPacket } from 'mysql2';
import { requireAdminApi } from '@/lib/auth/apiAuth';
import { getPool } from '@/lib/db';
export const dynamic = 'force-dynamic';
type Ctx = { params: Promise<{ id: string }> };
export async function PATCH(request: Request, context: Ctx) {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const { id: idParam } = await context.params;
const id = parseInt(idParam, 10);
if (Number.isNaN(id)) {
return NextResponse.json({ error: 'Invalid id' }, { status: 400 });
}
const body = await request.json();
const updates: string[] = [];
const values: unknown[] = [];
if (body.title !== undefined) {
updates.push('title = ?');
values.push(String(body.title).trim());
}
if (body.youtube_id !== undefined) {
updates.push('youtube_id = ?');
values.push(String(body.youtube_id).trim());
}
if (updates.length === 0) {
return NextResponse.json({ error: 'No fields to update' }, { status: 400 });
}
values.push(id);
const pool = getPool();
await pool.query(`UPDATE archive SET ${updates.join(', ')} WHERE id = ?`, values);
const [rows] = await pool.query<RowDataPacket[]>('SELECT * FROM archive WHERE id = ?', [id]);
return NextResponse.json({ item: rows[0] });
}
export async function DELETE(_request: Request, context: Ctx) {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const { id: idParam } = await context.params;
const id = parseInt(idParam, 10);
if (Number.isNaN(id)) {
return NextResponse.json({ error: 'Invalid id' }, { status: 400 });
}
const pool = getPool();
await pool.query('DELETE FROM archive WHERE id = ?', [id]);
return NextResponse.json({ ok: true });
}

View File

@@ -0,0 +1,37 @@
import { NextResponse } from 'next/server';
import type { RowDataPacket } from 'mysql2';
import { requireAdminApi } from '@/lib/auth/apiAuth';
import { getPool } from '@/lib/db';
export const dynamic = 'force-dynamic';
export async function GET() {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const pool = getPool();
const [rows] = await pool.query<RowDataPacket[]>('SELECT * FROM archive ORDER BY id ASC');
return NextResponse.json({ items: rows });
}
export async function POST(request: Request) {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const body = await request.json();
const title = String(body.title ?? '').trim();
const youtubeId = String(body.youtube_id ?? '').trim();
if (!title || !youtubeId) {
return NextResponse.json({ error: 'title and youtube_id required' }, { status: 400 });
}
const pool = getPool();
await pool.query('INSERT INTO archive (title, youtube_id) VALUES (?, ?)', [title, youtubeId]);
return NextResponse.json({ ok: true });
}

View File

@@ -0,0 +1,20 @@
import { NextResponse } from 'next/server';
import type { RowDataPacket } from 'mysql2';
import { requireAdminApi } from '@/lib/auth/apiAuth';
import { getPool } from '@/lib/db';
export const dynamic = 'force-dynamic';
export async function GET() {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const pool = getPool();
const [rows] = await pool.query<RowDataPacket[]>(
'SELECT id, name_id, name, name_jp FROM characters ORDER BY id ASC'
);
return NextResponse.json({ characters: rows });
}

View File

@@ -0,0 +1,63 @@
import { NextResponse } from 'next/server';
import type { RowDataPacket } from 'mysql2';
import { requireAdminApi } from '@/lib/auth/apiAuth';
import { getPool } from '@/lib/db';
export const dynamic = 'force-dynamic';
type Ctx = { params: Promise<{ id: string }> };
export async function PATCH(request: Request, context: Ctx) {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const { id: idParam } = await context.params;
const id = parseInt(idParam, 10);
if (Number.isNaN(id)) {
return NextResponse.json({ error: 'Invalid id' }, { status: 400 });
}
const body = await request.json();
const updates: string[] = [];
const values: unknown[] = [];
if (body.question !== undefined) {
updates.push('question = ?');
values.push(String(body.question).trim());
}
if (body.answer !== undefined) {
updates.push('answer = ?');
values.push(String(body.answer).trim());
}
if (updates.length === 0) {
return NextResponse.json({ error: 'No fields to update' }, { status: 400 });
}
values.push(id);
const pool = getPool();
await pool.query(`UPDATE contact SET ${updates.join(', ')} WHERE id = ?`, values);
const [rows] = await pool.query<RowDataPacket[]>('SELECT * FROM contact WHERE id = ?', [id]);
return NextResponse.json({ item: rows[0] });
}
export async function DELETE(_request: Request, context: Ctx) {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const { id: idParam } = await context.params;
const id = parseInt(idParam, 10);
if (Number.isNaN(id)) {
return NextResponse.json({ error: 'Invalid id' }, { status: 400 });
}
const pool = getPool();
await pool.query('DELETE FROM contact WHERE id = ?', [id]);
return NextResponse.json({ ok: true });
}

View File

@@ -0,0 +1,37 @@
import { NextResponse } from 'next/server';
import type { RowDataPacket } from 'mysql2';
import { requireAdminApi } from '@/lib/auth/apiAuth';
import { getPool } from '@/lib/db';
export const dynamic = 'force-dynamic';
export async function GET() {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const pool = getPool();
const [rows] = await pool.query<RowDataPacket[]>('SELECT * FROM contact ORDER BY id ASC');
return NextResponse.json({ items: rows });
}
export async function POST(request: Request) {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const body = await request.json();
const question = String(body.question ?? '').trim();
const answer = String(body.answer ?? '').trim();
if (!question || !answer) {
return NextResponse.json({ error: 'question and answer required' }, { status: 400 });
}
const pool = getPool();
await pool.query('INSERT INTO contact (question, answer) VALUES (?, ?)', [question, answer]);
return NextResponse.json({ ok: true });
}

View File

@@ -0,0 +1,67 @@
import { NextResponse } from 'next/server';
import type { RowDataPacket } from 'mysql2';
import { requireAdminApi } from '@/lib/auth/apiAuth';
import { getPool } from '@/lib/db';
export const dynamic = 'force-dynamic';
type Ctx = { params: Promise<{ id: string }> };
export async function PATCH(request: Request, context: Ctx) {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const { id: idParam } = await context.params;
const id = parseInt(idParam, 10);
if (Number.isNaN(id)) {
return NextResponse.json({ error: 'Invalid id' }, { status: 400 });
}
const body = await request.json();
const updates: string[] = [];
const values: unknown[] = [];
if (body.title !== undefined) {
updates.push('title = ?');
values.push(String(body.title).trim());
}
if (body.description !== undefined) {
updates.push('description = ?');
values.push(String(body.description));
}
if (body.youtube_id !== undefined) {
updates.push('youtube_id = ?');
values.push(String(body.youtube_id).trim());
}
if (updates.length === 0) {
return NextResponse.json({ error: 'No fields to update' }, { status: 400 });
}
values.push(id);
const pool = getPool();
await pool.query(`UPDATE guide SET ${updates.join(', ')} WHERE id = ?`, values);
const [rows] = await pool.query<RowDataPacket[]>('SELECT * FROM guide WHERE id = ?', [id]);
return NextResponse.json({ item: rows[0] });
}
export async function DELETE(_request: Request, context: Ctx) {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const { id: idParam } = await context.params;
const id = parseInt(idParam, 10);
if (Number.isNaN(id)) {
return NextResponse.json({ error: 'Invalid id' }, { status: 400 });
}
const pool = getPool();
await pool.query('DELETE FROM guide WHERE id = ?', [id]);
return NextResponse.json({ ok: true });
}

View File

@@ -0,0 +1,41 @@
import { NextResponse } from 'next/server';
import type { RowDataPacket } from 'mysql2';
import { requireAdminApi } from '@/lib/auth/apiAuth';
import { getPool } from '@/lib/db';
export const dynamic = 'force-dynamic';
export async function GET() {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const pool = getPool();
const [rows] = await pool.query<RowDataPacket[]>('SELECT * FROM guide ORDER BY id ASC');
return NextResponse.json({ items: rows });
}
export async function POST(request: Request) {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const body = await request.json();
const title = String(body.title ?? '').trim();
const description = String(body.description ?? '');
const youtubeId = String(body.youtube_id ?? '').trim();
if (!title || !youtubeId) {
return NextResponse.json({ error: 'title and youtube_id required' }, { status: 400 });
}
const pool = getPool();
await pool.query(
'INSERT INTO guide (title, description, youtube_id) VALUES (?, ?, ?)',
[title, description, youtubeId]
);
return NextResponse.json({ ok: true });
}

View File

@@ -0,0 +1,124 @@
import { NextResponse } from 'next/server';
import type { RowDataPacket } from 'mysql2';
import { requireAdminApi } from '@/lib/auth/apiAuth';
import { getPool } from '@/lib/db';
export const dynamic = 'force-dynamic';
type Ctx = { params: Promise<{ id: string }> };
export async function GET(_request: Request, context: Ctx) {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const { id: idParam } = await context.params;
const id = parseInt(idParam, 10);
if (Number.isNaN(id)) {
return NextResponse.json({ error: 'Invalid id' }, { status: 400 });
}
const pool = getPool();
const [rows] = await pool.query<RowDataPacket[]>(
`SELECT p.id, p.player_key, p.player_name, p.description, p.image, p.character_id,
c.name_id, c.name, c.name_jp
FROM players p
LEFT JOIN characters c ON c.id = p.character_id
WHERE p.id = ?`,
[id]
);
if (rows.length === 0) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
return NextResponse.json({ player: rows[0] });
}
export async function PATCH(request: Request, context: Ctx) {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const { id: idParam } = await context.params;
const id = parseInt(idParam, 10);
if (Number.isNaN(id)) {
return NextResponse.json({ error: 'Invalid id' }, { status: 400 });
}
const body = await request.json();
const updates: string[] = [];
const values: unknown[] = [];
if (body.player_key !== undefined) {
updates.push('player_key = ?');
values.push(String(body.player_key).trim());
}
if (body.player_name !== undefined) {
updates.push('player_name = ?');
values.push(String(body.player_name).trim());
}
if (body.description !== undefined) {
updates.push('description = ?');
values.push(String(body.description));
}
if (body.image !== undefined) {
updates.push('image = ?');
values.push(body.image == null ? null : String(body.image));
}
if (body.character_id !== undefined) {
updates.push('character_id = ?');
values.push(String(parseInt(String(body.character_id), 10)));
}
if (updates.length === 0) {
return NextResponse.json({ error: 'No fields to update' }, { status: 400 });
}
values.push(id);
const pool = getPool();
await pool.query(`UPDATE players SET ${updates.join(', ')} WHERE id = ?`, values);
const [rows] = await pool.query<RowDataPacket[]>(
`SELECT p.id, p.player_key, p.player_name, p.description, p.image, p.character_id,
c.name_id, c.name, c.name_jp
FROM players p
LEFT JOIN characters c ON c.id = p.character_id
WHERE p.id = ?`,
[id]
);
return NextResponse.json({ player: rows[0] });
}
export async function DELETE(_request: Request, context: Ctx) {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const { id: idParam } = await context.params;
const id = parseInt(idParam, 10);
if (Number.isNaN(id)) {
return NextResponse.json({ error: 'Invalid id' }, { status: 400 });
}
const pool = getPool();
try {
await pool.query('DELETE FROM players WHERE id = ?', [id]);
} catch (e: unknown) {
const code = (e as { errno?: number })?.errno;
if (code === 1451) {
return NextResponse.json(
{ error: 'Cannot delete player: referenced by tournament or other records' },
{ status: 409 }
);
}
throw e;
}
return NextResponse.json({ ok: true });
}

View File

@@ -0,0 +1,52 @@
import { NextResponse } from 'next/server';
import type { RowDataPacket } from 'mysql2';
import { requireAdminApi } from '@/lib/auth/apiAuth';
import { getPool } from '@/lib/db';
export const dynamic = 'force-dynamic';
export async function GET() {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const pool = getPool();
const [rows] = await pool.query<RowDataPacket[]>(
`SELECT p.id, p.player_key, p.player_name, p.description, p.image, p.character_id,
c.name_id, c.name, c.name_jp
FROM players p
LEFT JOIN characters c ON c.id = p.character_id
ORDER BY p.id ASC`
);
return NextResponse.json({ players: rows });
}
export async function POST(request: Request) {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const body = await request.json();
const playerKey = String(body.player_key ?? '').trim();
const playerName = String(body.player_name ?? '').trim();
const description = String(body.description ?? '');
const image = body.image != null ? String(body.image) : null;
const characterId = parseInt(String(body.character_id), 10);
if (!playerKey || !playerName || Number.isNaN(characterId)) {
return NextResponse.json({ error: 'player_key, player_name, character_id required' }, { status: 400 });
}
const pool = getPool();
await pool.query(
`INSERT INTO players (player_key, player_name, description, image, character_id)
VALUES (?, ?, ?, ?, ?)`,
[playerKey, playerName, description, image, String(characterId)]
);
return NextResponse.json({ ok: true });
}

View File

@@ -0,0 +1,63 @@
import { NextResponse } from 'next/server';
import type { RowDataPacket } from 'mysql2';
import { requireAdminApi } from '@/lib/auth/apiAuth';
import { getPool } from '@/lib/db';
export const dynamic = 'force-dynamic';
type Ctx = { params: Promise<{ id: string }> };
export async function PATCH(request: Request, context: Ctx) {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const { id: idParam } = await context.params;
const id = parseInt(idParam, 10);
if (Number.isNaN(id)) {
return NextResponse.json({ error: 'Invalid id' }, { status: 400 });
}
const body = await request.json();
const isApproved = typeof body.is_approved === 'boolean' ? body.is_approved : undefined;
const isAdmin = typeof body.is_admin === 'boolean' ? body.is_admin : undefined;
if (isApproved === undefined && isAdmin === undefined) {
return NextResponse.json({ error: 'No changes' }, { status: 400 });
}
const pool = getPool();
if (id === auth.user.id && isApproved === false) {
return NextResponse.json({ error: 'Cannot revoke your own approval' }, { status: 400 });
}
if (id === auth.user.id && isAdmin === false) {
return NextResponse.json({ error: 'Cannot remove your own admin role' }, { status: 400 });
}
const updates: string[] = [];
const values: unknown[] = [];
if (isApproved !== undefined) {
updates.push('is_approved = ?');
values.push(isApproved ? 1 : 0);
}
if (isAdmin !== undefined) {
updates.push('is_admin = ?');
values.push(isAdmin ? 1 : 0);
}
values.push(id);
await pool.query(
`UPDATE admin_users SET ${updates.join(', ')} WHERE id = ?`,
values
);
const [rows] = await pool.query<RowDataPacket[]>(
'SELECT id, email, is_approved, is_admin, created_at FROM admin_users WHERE id = ?',
[id]
);
return NextResponse.json({ user: rows[0] ?? null });
}

View File

@@ -0,0 +1,23 @@
import { NextResponse } from 'next/server';
import type { RowDataPacket } from 'mysql2';
import { requireAdminApi } from '@/lib/auth/apiAuth';
import { getPool } from '@/lib/db';
export const dynamic = 'force-dynamic';
export async function GET() {
const auth = await requireAdminApi();
if (!auth.ok) {
return auth.response;
}
const pool = getPool();
const [rows] = await pool.query<RowDataPacket[]>(
`SELECT id, email, is_approved, is_admin, created_at
FROM admin_users
ORDER BY created_at DESC`
);
return NextResponse.json({ users: rows });
}

View File

@@ -0,0 +1,15 @@
import { NextResponse } from 'next/server';
import { getArchiveItems } from '@/lib/data';
export const dynamic = 'force-dynamic';
export async function GET() {
try {
const data = await getArchiveItems();
return NextResponse.json(data);
} catch (e) {
console.error(e);
return NextResponse.json([], { status: 500 });
}
}

View File

@@ -0,0 +1,58 @@
import { NextResponse } from 'next/server';
import { verifyPassword } from '@/lib/auth/password';
import { createSession } from '@/lib/auth/session';
import { getPool } from '@/lib/db';
import type { RowDataPacket } from 'mysql2';
export const dynamic = 'force-dynamic';
export async function POST(request: Request) {
try {
const body = await request.json();
const email = typeof body.email === 'string' ? body.email.trim().toLowerCase() : '';
const password = typeof body.password === 'string' ? body.password : '';
if (!email || !password) {
return NextResponse.json({ error: 'Email and password required' }, { status: 400 });
}
const pool = getPool();
const [rows] = await pool.query<RowDataPacket[]>(
'SELECT id, email, password_hash, is_approved, is_admin FROM admin_users WHERE email = ?',
[email]
);
if (rows.length === 0) {
return NextResponse.json({ error: 'Invalid email or password' }, { status: 401 });
}
const row = rows[0];
const ok = verifyPassword(password, row.password_hash as string);
if (!ok) {
return NextResponse.json({ error: 'Invalid email or password' }, { status: 401 });
}
if (!row.is_approved) {
return NextResponse.json(
{ error: 'Your account is not approved yet.', code: 'PENDING_APPROVAL' },
{ status: 403 }
);
}
await createSession(row.id as number);
return NextResponse.json({
ok: true,
user: {
id: row.id,
email: row.email,
is_approved: Boolean(row.is_approved),
is_admin: Boolean(row.is_admin),
},
});
} catch (e) {
console.error(e);
return NextResponse.json({ error: 'Login failed' }, { status: 500 });
}
}

View File

@@ -0,0 +1,10 @@
import { NextResponse } from 'next/server';
import { destroySession } from '@/lib/auth/session';
export const dynamic = 'force-dynamic';
export async function POST() {
await destroySession();
return NextResponse.json({ ok: true });
}

View File

@@ -0,0 +1,20 @@
import { NextResponse } from 'next/server';
import { getSessionUser } from '@/lib/auth/session';
export const dynamic = 'force-dynamic';
export async function GET() {
const user = await getSessionUser();
if (!user) {
return NextResponse.json({ user: null }, { status: 401 });
}
return NextResponse.json({
user: {
id: user.id,
email: user.email,
is_approved: user.is_approved,
is_admin: user.is_admin,
},
});
}

View File

@@ -0,0 +1,37 @@
import { NextResponse } from 'next/server';
import { hashPassword } from '@/lib/auth/password';
import { getPool } from '@/lib/db';
export const dynamic = 'force-dynamic';
export async function POST(request: Request) {
try {
const body = await request.json();
const email = typeof body.email === 'string' ? body.email.trim().toLowerCase() : '';
const password = typeof body.password === 'string' ? body.password : '';
if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
return NextResponse.json({ error: 'Valid email is required' }, { status: 400 });
}
if (password.length < 8) {
return NextResponse.json({ error: 'Password must be at least 8 characters' }, { status: 400 });
}
const passwordHash = hashPassword(password);
const pool = getPool();
await pool.query(
`INSERT INTO admin_users (email, password_hash, is_approved, is_admin) VALUES (?, ?, 0, 0)`,
[email, passwordHash]
);
return NextResponse.json({ ok: true, message: 'Registration submitted. Wait for an administrator to approve your account.' });
} catch (e: unknown) {
const code = (e as { code?: string })?.code;
if (code === 'ER_DUP_ENTRY') {
return NextResponse.json({ error: 'Email already registered' }, { status: 409 });
}
console.error(e);
return NextResponse.json({ error: 'Registration failed' }, { status: 500 });
}
}

View File

@@ -0,0 +1,15 @@
import { NextResponse } from 'next/server';
import { getContactItems } from '@/lib/data';
export const dynamic = 'force-dynamic';
export async function GET() {
try {
const data = await getContactItems();
return NextResponse.json(data);
} catch (e) {
console.error(e);
return NextResponse.json([], { status: 500 });
}
}

View File

@@ -0,0 +1,15 @@
import { NextResponse } from 'next/server';
import { getGuideItems } from '@/lib/data';
export const dynamic = 'force-dynamic';
export async function GET() {
try {
const data = await getGuideItems();
return NextResponse.json(data);
} catch (e) {
console.error(e);
return NextResponse.json([], { status: 500 });
}
}

View File

@@ -0,0 +1,23 @@
import { NextResponse } from 'next/server';
import { getPlayersForTournament } from '@/lib/data';
export const dynamic = 'force-dynamic';
type RouteContext = {
params: Promise<{ key: string }>;
};
export async function GET(_request: Request, context: RouteContext) {
try {
const { key } = await context.params;
const data = await getPlayersForTournament(key);
if (data === null) {
return NextResponse.json({ error: 'Tournament not found' }, { status: 404 });
}
return NextResponse.json(data);
} catch (e) {
console.error(e);
return NextResponse.json([], { status: 500 });
}
}

View File

@@ -0,0 +1,15 @@
import { NextResponse } from 'next/server';
import { getAllPlayers } from '@/lib/data';
export const dynamic = 'force-dynamic';
export async function GET() {
try {
const data = await getAllPlayers();
return NextResponse.json(data);
} catch (e) {
console.error(e);
return NextResponse.json([], { status: 500 });
}
}

View File

@@ -0,0 +1,17 @@
body {
margin: 0;
font-family: var(--font-mplus), -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
html,
body {
min-height: 100%;
}

43
nextjs/src/app/layout.tsx Normal file
View File

@@ -0,0 +1,43 @@
import type { Metadata, Viewport } from 'next';
import { Indie_Flower, M_PLUS_Rounded_1c } from 'next/font/google';
import type { ReactNode } from 'react';
import { I18nProvider } from '@/components/I18nProvider';
import 'semantic-ui-css/semantic.min.css';
import './globals.css';
const indieFlower = Indie_Flower({
weight: '400',
subsets: ['latin'],
variable: '--font-indie',
display: 'swap',
});
const mPlusRounded = M_PLUS_Rounded_1c({
weight: ['400', '700'],
subsets: ['latin'],
variable: '--font-mplus',
display: 'swap',
adjustFontFallback: false,
});
export const metadata: Metadata = {
title: 'キャサリン faito crab',
description: 'キャサリン faito crab',
manifest: '/manifest.json',
};
export const viewport: Viewport = {
themeColor: '#ff2d7c',
};
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="ja" className={`${indieFlower.variable} ${mPlusRounded.variable}`}>
<body>
<I18nProvider>{children}</I18nProvider>
</body>
</html>
);
}

View File

@@ -0,0 +1,7 @@
export default function NotFound() {
return (
<div>
<p>404</p>
</div>
);
}

View File

@@ -0,0 +1,43 @@
'use client';
import { useTranslation } from 'react-i18next';
import YouTube from 'react-youtube';
import type { IGuideItem } from '@/models/IGuideItem';
import style from '@/styles/web.module.scss';
type Props = {
items: IGuideItem[];
};
const opts = {
height: '195',
width: '320',
};
export function ArchiveVideoList({ items }: Props) {
const { t } = useTranslation();
return (
<div className={style.guideBody}>
<h2>{t('archive')}</h2>
<hr />
<br />
{items.map((el) => (
<div
key={`archiveItemsLoop-${el.id}`}
className={style.characterBlock}
style={{
animationDelay: `${el.id * 0.2}s`,
}}
>
<h4>{el.title}</h4>
<hr />
<div className={style.centerVideo}>
<YouTube videoId={el.youtube_id} opts={opts} />
</div>
</div>
))}
</div>
);
}

View File

@@ -0,0 +1,39 @@
'use client';
import { useTranslation } from 'react-i18next';
import type { IContactQuestion } from '@/models/IContactQuestion';
import style from '@/styles/web.module.scss';
type Props = {
items: IContactQuestion[];
};
export function ContactList({ items }: Props) {
const { t } = useTranslation();
return (
<div className={style.guideBody}>
<h2>{t('qanda')}</h2>
<hr />
<div className={style.contactBox}>
<a href="https://forms.gle/Dn4p7cFEPLK1zcTz5" rel="noopener noreferrer" target="_blank">
&nbsp;
</a>
</div>
{items.map((el) => (
<div
key={`contactItemsLoop-${el.id}`}
className={style.characterBlock}
style={{
animationDelay: `${el.id * 0.2}s`,
}}
>
<h4>{el.question}</h4>
<hr />
<div>{el.answer}</div>
</div>
))}
</div>
);
}

View File

@@ -0,0 +1,44 @@
'use client';
import { useTranslation } from 'react-i18next';
import YouTube from 'react-youtube';
import type { IGuideItem } from '@/models/IGuideItem';
import style from '@/styles/web.module.scss';
type Props = {
items: IGuideItem[];
};
const opts = {
height: '195',
width: '320',
};
export function GuideVideoList({ items }: Props) {
const { t } = useTranslation();
return (
<div className={style.guideBody}>
<h2>{t('guide')}</h2>
<hr />
<br />
{items.map((el) => (
<div
key={`guideItemsLoop-${el.id}`}
className={style.characterBlock}
style={{
animationDelay: `${el.id * 0.2}s`,
}}
>
<h4>{el.title}</h4>
<hr />
<div>{el.description}</div>
<div className={style.centerVideo}>
<YouTube videoId={el.youtube_id} opts={opts} />
</div>
</div>
))}
</div>
);
}

View File

@@ -0,0 +1,10 @@
'use client';
import { I18nextProvider } from 'react-i18next';
import type { ReactNode } from 'react';
import i18n from '@/i18n/client';
export function I18nProvider({ children }: { children: ReactNode }) {
return <I18nextProvider i18n={i18n}>{children}</I18nextProvider>;
}

View File

@@ -0,0 +1,49 @@
'use client';
import { useTranslation } from 'react-i18next';
import type { IPlayerInfo } from '@/models/IPlayerInfo';
import style from '@/styles/web.module.scss';
type Props = {
players: IPlayerInfo[];
};
export function PlayersList({ players }: Props) {
const { t } = useTranslation();
return (
<div className={style.guideBody}>
<h2>Players</h2>
<hr />
<br />
{players.map((el) => {
const charClass =
style[`character-${el.name_id}` as keyof typeof style] ?? '';
return (
<div
key={`playerInfoLoop-${el.id}`}
className={style.characterBlock}
style={{
animationDelay: `${el.id * 0.2}s`,
}}
>
<div className={charClass} />
<div className={style.titlePlayer}>
<span className={style.titlePlayerBlock}>{t('player_name')}</span>
</div>
<div>{el.player_name}</div>
<div className={style.titlePlayer}>
<span className={style.titlePlayerBlock}>{t('use_character')}</span>
</div>
<div>{el.name_jp}</div>
<div className={style.titlePlayer}>
<span className={style.titlePlayerBlock}>{t('description')}</span>
</div>
<div>{el.description}</div>
</div>
);
})}
</div>
);
}

View File

@@ -0,0 +1,114 @@
import Link from 'next/link';
import type { ReactNode } from 'react';
import style from '@/styles/web.module.scss';
export function SiteLayout({ children }: { children: ReactNode }) {
return (
<div className={style.main}>
<div className={style.header}>
<div className={style.background} />
<div className={style.buynow}>
<a
href="https://www.atlus.co.jp/news/13264/"
rel="noopener noreferrer"
target="_blank"
>
&nbsp;
</a>
</div>
<div className={style.logoHeader} />
<div className={style.logoSwitch} />
<div className={style.waveContainer}>
<svg
className={style.waves}
viewBox="0 24 150 28"
preserveAspectRatio="none"
shapeRendering="auto"
>
<defs>
<path
id="gentle-wave"
d="M-160 44c30 0 58-18 88-18s 58 18 88 18 58-18 88-18 58 18 88 18 v44h-352z"
/>
</defs>
<g>
<use
className={style.firstWave}
x={48}
y={7}
href="#gentle-wave"
fill="rgba(255,45,124,0.7)"
/>
<use
className={style.secondWave}
x={48}
y={0}
href="#gentle-wave"
fill="#ff2d7c"
/>
</g>
</svg>
</div>
</div>
<nav className={style.navigation}>
<ul>
<li>
<Link href="/">Home</Link>
</li>
<li>
<Link href="/players">Players</Link>
</li>
<li>
<Link href="/guide">Guide</Link>
</li>
<li>
<Link href="/archive">Archive</Link>
</li>
<li>
<Link href="/about">About</Link>
</li>
<li>
<Link href="/contact">Q&A</Link>
</li>
</ul>
</nav>
<div className={style.contents}>{children}</div>
<div className={style.footer}>
<div className={style.footerText}>
<p>
<a href="https://www.atlus.co.jp/copyright/" rel="noopener noreferrer" target="_blank">
©ATLUS
</a>{' '}
©SEGA All Rights Reserved.
</p>
<p>ATLUS様のページとは異なるユーザーサイトです</p>
<p>ATLUS様に出されないよう</p>
</div>
<div className={style.twitter}>
<a href="https://twitter.com/catherine_f_c" rel="noopener noreferrer" target="_blank">
&nbsp;
</a>
</div>
<div className={style.twitch}>
<a
href="https://www.twitch.tv/catherine_faito_crab"
rel="noopener noreferrer"
target="_blank"
>
&nbsp;
</a>
</div>
<div className={style.youtube}>
<a
href="https://www.youtube.com/channel/UC5cvyvCdOMbxwZqCT09cGNA/"
rel="noopener noreferrer"
target="_blank"
>
&nbsp;
</a>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,18 @@
'use client';
import style from '@/styles/admin.module.scss';
export function LogoutButton() {
return (
<button
type="button"
className={style.btnGhost}
onClick={async () => {
await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' });
window.location.href = '/admin/login';
}}
>
Log out
</button>
);
}

22
nextjs/src/i18n/client.ts Normal file
View File

@@ -0,0 +1,22 @@
'use client';
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import en from './en.json';
import ja from './ja.json';
if (!i18n.isInitialized) {
i18n.use(initReactI18next).init({
fallbackLng: 'ja',
resources: {
en: { translation: en },
ja: { translation: ja },
},
interpolation: {
escapeValue: false,
},
});
}
export default i18n;

9
nextjs/src/i18n/en.json Normal file
View File

@@ -0,0 +1,9 @@
{
"use_character": "Character",
"player_name": "Playername",
"description": "Description",
"archive": "Archive",
"guide": "Guide",
"about": "About",
"qanda": "Q&A"
}

9
nextjs/src/i18n/ja.json Normal file
View File

@@ -0,0 +1,9 @@
{
"use_character": "使用キャラクター",
"player_name": "プレイヤー名",
"description": "紹介文",
"archive": "Archive",
"guide": "Guide",
"about": "About",
"qanda": "Q&A"
}

View File

@@ -0,0 +1,20 @@
import { NextResponse } from 'next/server';
import type { AdminUserRow } from '@/lib/auth/session';
import { getSessionUser } from '@/lib/auth/session';
export async function requireAdminApi(): Promise<
{ ok: true; user: AdminUserRow } | { ok: false; response: NextResponse }
> {
const user = await getSessionUser();
if (!user) {
return { ok: false, response: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) };
}
if (!user.is_approved) {
return { ok: false, response: NextResponse.json({ error: 'Pending approval' }, { status: 403 }) };
}
if (!user.is_admin) {
return { ok: false, response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }) };
}
return { ok: true, user };
}

View File

@@ -0,0 +1,11 @@
import bcrypt from 'bcryptjs';
const SALT_ROUNDS = 12;
export function hashPassword(plain: string): string {
return bcrypt.hashSync(plain, SALT_ROUNDS);
}
export function verifyPassword(plain: string, passwordHash: string): boolean {
return bcrypt.compareSync(plain, passwordHash);
}

View File

@@ -0,0 +1,22 @@
import { redirect } from 'next/navigation';
import { getSessionUser } from '@/lib/auth/session';
export async function requireLogin(): Promise<NonNullable<Awaited<ReturnType<typeof getSessionUser>>>> {
const user = await getSessionUser();
if (!user) {
redirect('/admin/login');
}
if (!user.is_approved) {
redirect('/admin/pending');
}
return user;
}
export async function requireAdmin(): Promise<NonNullable<Awaited<ReturnType<typeof getSessionUser>>>> {
const user = await requireLogin();
if (!user.is_admin) {
redirect('/admin/no-access');
}
return user;
}

View File

@@ -0,0 +1,88 @@
import { createHash, randomBytes } from 'crypto';
import type { RowDataPacket } from 'mysql2';
import { cookies } from 'next/headers';
import { getPool } from '@/lib/db';
export const SESSION_COOKIE = 'admin_session';
const SESSION_MAX_AGE_SEC = 60 * 60 * 24 * 7; // 7 days
export type AdminUserRow = {
id: number;
email: string;
password_hash: string;
is_approved: boolean;
is_admin: boolean;
};
function hashToken(token: string): string {
return createHash('sha256').update(token, 'utf8').digest('hex');
}
export async function createSession(userId: number): Promise<string> {
const token = randomBytes(32).toString('hex');
const tokenHash = hashToken(token);
const expiresAt = new Date(Date.now() + SESSION_MAX_AGE_SEC * 1000);
const pool = getPool();
await pool.query(
`INSERT INTO admin_sessions (user_id, token_hash, expires_at) VALUES (?, ?, ?)`,
[userId, tokenHash, expiresAt]
);
const cookieStore = await cookies();
cookieStore.set(SESSION_COOKIE, token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: SESSION_MAX_AGE_SEC,
path: '/',
});
return token;
}
export async function destroySession(): Promise<void> {
const cookieStore = await cookies();
const token = cookieStore.get(SESSION_COOKIE)?.value;
if (token) {
const pool = getPool();
await pool.query(
'DELETE FROM admin_sessions WHERE token_hash = ?',
[hashToken(token)]
);
}
cookieStore.delete(SESSION_COOKIE);
}
export async function getSessionUser(): Promise<AdminUserRow | null> {
const cookieStore = await cookies();
const token = cookieStore.get(SESSION_COOKIE)?.value;
if (!token) {
return null;
}
const tokenHash = hashToken(token);
const pool = getPool();
const [rows] = await pool.query<RowDataPacket[]>(
`SELECT u.id, u.email, u.password_hash, u.is_approved, u.is_admin
FROM admin_sessions s
JOIN admin_users u ON u.id = s.user_id
WHERE s.token_hash = ? AND s.expires_at > NOW()`,
[tokenHash]
);
if (rows.length === 0) {
cookieStore.delete(SESSION_COOKIE);
return null;
}
const row = rows[0] as Record<string, unknown>;
return {
id: row.id as number,
email: row.email as string,
password_hash: row.password_hash as string,
is_approved: Boolean(row.is_approved),
is_admin: Boolean(row.is_admin),
};
}

74
nextjs/src/lib/data.ts Normal file
View File

@@ -0,0 +1,74 @@
import type { RowDataPacket } from 'mysql2';
import { getPool } from './db';
import type { IContactQuestion } from '@/models/IContactQuestion';
import type { IGuideItem } from '@/models/IGuideItem';
import type { IPlayerInfo } from '@/models/IPlayerInfo';
let tournamentIdByKeyPromise: Promise<Record<string, number>> | null = null;
async function loadTournamentMap(): Promise<Record<string, number>> {
const pool = getPool();
const [rows] = await pool.query<RowDataPacket[]>(
'SELECT id, tournament_key FROM tournaments'
);
const map: Record<string, number> = {};
for (const row of rows) {
map[row.tournament_key as string] = row.id as number;
}
return map;
}
export async function getTournamentIdByKey(): Promise<Record<string, number>> {
if (!tournamentIdByKeyPromise) {
tournamentIdByKeyPromise = loadTournamentMap();
}
return tournamentIdByKeyPromise;
}
export async function getAllPlayers(): Promise<IPlayerInfo[]> {
const pool = getPool();
const [rows] = await pool.query<RowDataPacket[]>(
`SELECT p.id, p.player_key, p.player_name, p.description, p.image, c.name_id, c.name, c.name_jp
FROM players p
JOIN characters c ON c.id = p.character_id`
);
return rows as IPlayerInfo[];
}
export async function getPlayersForTournament(
tournamentKey: string
): Promise<IPlayerInfo[] | null> {
const tournaments = await getTournamentIdByKey();
const tournamentId = tournaments[tournamentKey];
if (tournamentId === undefined) {
return null;
}
const pool = getPool();
const [rows] = await pool.query<RowDataPacket[]>(
`SELECT p.id, p.player_key, p.player_name, p.description, p.image, c.name_id, c.name, c.name_jp
FROM players p
JOIN player_to_tournament ptt ON p.id = ptt.player_id
JOIN characters c ON c.id = p.character_id
WHERE ptt.tournament_id = ?`,
[tournamentId]
);
return rows as IPlayerInfo[];
}
export async function getGuideItems(): Promise<IGuideItem[]> {
const pool = getPool();
const [rows] = await pool.query<RowDataPacket[]>('SELECT * FROM guide');
return rows as IGuideItem[];
}
export async function getArchiveItems(): Promise<IGuideItem[]> {
const pool = getPool();
const [rows] = await pool.query<RowDataPacket[]>('SELECT * FROM archive');
return rows as IGuideItem[];
}
export async function getContactItems(): Promise<IContactQuestion[]> {
const pool = getPool();
const [rows] = await pool.query<RowDataPacket[]>('SELECT * FROM contact');
return rows as IContactQuestion[];
}

23
nextjs/src/lib/db.ts Normal file
View File

@@ -0,0 +1,23 @@
import mysql from 'mysql2/promise';
function createPool(): mysql.Pool {
const port = process.env.DB_PORT ? parseInt(process.env.DB_PORT, 10) : 3306;
return mysql.createPool({
connectionLimit: 10,
port,
host: process.env.DB_ENDPOINT,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: 'catherine_league',
charset: 'utf8mb4',
});
}
let pool: mysql.Pool | undefined;
export function getPool(): mysql.Pool {
if (!pool) {
pool = createPool();
}
return pool;
}

View File

@@ -0,0 +1,5 @@
export interface IArchiveItem {
id: number;
title: string;
youtube_id: string;
}

View File

@@ -0,0 +1,5 @@
export interface IContactQuestion {
id: number;
question: string;
answer: string;
}

View File

@@ -0,0 +1,6 @@
export interface IGuideItem {
id: number;
title: string;
description: string;
youtube_id: string;
}

View File

@@ -0,0 +1,10 @@
export interface IPlayerInfo {
id: number;
player_key: string;
player_name: string;
description: string;
image: string;
name_id: string;
name: string;
name_jp: string;
}

View File

@@ -0,0 +1,141 @@
.wrap {
max-width: 960px;
margin: 0 auto;
padding: 24px 16px 48px;
font-family: system-ui, sans-serif;
color: #1a1a1a;
}
.card {
background: #fff;
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
}
.title {
margin: 0 0 8px;
font-size: 1.5rem;
}
.sub {
color: #666;
margin: 0 0 16px;
font-size: 0.95rem;
}
.form {
display: flex;
flex-direction: column;
gap: 12px;
max-width: 360px;
}
.label {
display: flex;
flex-direction: column;
gap: 4px;
font-size: 0.9rem;
}
.input {
padding: 8px 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 1rem;
}
.textarea {
min-height: 100px;
font-family: inherit;
}
.btn {
padding: 10px 16px;
border: none;
border-radius: 4px;
background: #2563eb;
color: #fff;
font-size: 1rem;
cursor: pointer;
&:hover {
background: #1d4ed8;
}
&:disabled {
opacity: 0.6;
cursor: not-allowed;
}
}
.btnDanger {
background: #dc2626;
&:hover {
background: #b91c1c;
}
}
.btnGhost {
background: #f3f4f6;
color: #111;
&:hover {
background: #e5e7eb;
}
}
.error {
color: #b91c1c;
font-size: 0.9rem;
}
.success {
color: #15803d;
font-size: 0.9rem;
}
.nav {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-bottom: 24px;
padding-bottom: 16px;
border-bottom: 1px solid #e5e7eb;
}
.nav a {
color: #2563eb;
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
.table {
width: 100%;
border-collapse: collapse;
font-size: 0.9rem;
}
.table th,
.table td {
border: 1px solid #e5e7eb;
padding: 8px;
text-align: left;
vertical-align: top;
}
.table th {
background: #f9fafb;
}
.rowActions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.hr {
border: none;
border-top: 1px solid #e5e7eb;
margin: 16px 0;
}

View File

@@ -0,0 +1,608 @@
.header {
background-image: url('https://static.catherine-fc.com/media/bgbg.png');
background-repeat: none;
width: 100%;
height: 460px;
}
.buynow {
position: fixed;
top: 0;
bottom: 0;
right: 0;
margin: auto;
width: 235px;
height: 99px;
background-image: url('https://static.catherine-fc.com/media/buynow.png');
z-index: 1;
&> a {
display:block;
width: 235px;
height: 99px;
}
&:hover {
animation: bounce 1s;
}
}
.background {
position: absolute;
top: 0;
left: 0;
right: 0;
margin: auto;
background-image: url('https://static.catherine-fc.com/media/bgimage.png');
background-repeat: none;
width: 1366px;
height: 401px;
animation: upAndDown 10s linear infinite;
transition: background-image 0.5s ease-in-out;
&:hover {
transition: background-image 0.5s ease-in-out;
background-image: url('https://static.catherine-fc.com/media/bgimagenight.png');
}
}
.logoHeader {
position: absolute;
top: -30px;
left: 0;
right: 0;
margin: auto;
width: 577px;
height: 401px;
background-image: url('https://static.catherine-fc.com/media/cat_fb_logo.png');
background-repeat: none;
z-index: 1;
}
.logoSwitch {
position: absolute;
top: 310px;
left: 0;
right: 0;
margin: auto;
width: 415px;
height: 64px;
background-image: url('https://static.catherine-fc.com/media/faito_crab.png');
background-repeat: none;
z-index: 1;
}
.contents {
flex-grow: 1;
padding: 30px;
}
.main {
display: flex;
flex-direction: column;
width: 100%;
background-image: url('https://static.catherine-fc.com/media/background.png');
background-repeat: none;
color: white;
min-height: 100vh;
}
.footer {
display: flex;
justify-content: center;
align-items: center;
flex-direction: row;
padding: 20px;
width: 100%;
background-color: black;
color: white;
bottom: 0;
}
.footerText {
float: left;
display: block;
justify-content: center;
align-items: center;
flex-direction: row;
& > p {
margin: 5px 0;
}
}
.twitch {
float: right;
width: 113px;
height: 70px;
background-image: url('https://static.catherine-fc.com/media/twitch.png');
background-size: 142px 70px;
margin: 0 20px;
background-repeat: none;
background-size: contain;
&> a {
display:block;
width: 113px;
height: 70px;
}
}
.twitchHome {
width: 113px;
height: 70px;
background-image: url('https://static.catherine-fc.com/media/twitch.png');
background-size: 142px 70px;
margin: auto;
background-repeat: none;
background-size: contain;
&> a {
display:block;
width: 113px;
height: 70px;
}
}
.twitter {
float: right;
width: 70px;
height: 70px;
margin: 0 20px;
background-image: url('https://static.catherine-fc.com/media/twitter.png');
background-size: contain;
&> a {
display:block;
width: 70px;
height: 70px;
}
}
.youtube {
float: right;
width: 100px;
height: 70px;
margin: 0 20px;
background-image: url('https://static.catherine-fc.com/media/youtube.png');
background-size: contain;
&> a {
display:block;
width: 100px;
height: 70px;
}
}
.waveContainer {
position: absolute;
top: 260px;
left: 0;
right: 0;
margin: auto;
z-index: 0;
}
.waves {
position: relative;
width: 100%;
height: 200px;
margin-bottom: -7px;
min-height: 100px;
max-height: 200px;
}
.firstWave {
animation: moveforever 25s cubic-bezier(.55, .5, .45, .5) infinite;
animation-delay: -2s;
animation-duration: 2s;
}
.secondWave {
animation: moveforever 25s cubic-bezier(.55, .5, .45, .5) infinite;
animation-delay: -4s;
animation-duration: 5s;
}
@keyframes moveforever {
0% {
transform: translate3d(-90px, 0, 0);
}
100% {
transform: translate3d(85px, 0, 0);
}
}
@keyframes bounce {
0%, 20%, 60%, 100% {
-webkit-transform: translateY(0);
transform: translateY(0);
}
40% {
-webkit-transform: translateY(-20px);
transform: translateY(-20px);
}
80% {
-webkit-transform: translateY(-10px);
transform: translateY(-10px);
}
}
.navigation {
position: absolute;
top: 400px;
left: 0;
right: 0;
margin: auto;
z-index: 1;
display: flex;
align-items: center;
justify-content: center;
&>ul {
list-style-type: none;
&>li {
float: left;
margin-left: 10px;
margin-right: 10px;
&>a {
background-color: black;
width: 90px;
height: 30px;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 16px;
font-family: var(--font-indie), cursive;
color: white;
&:hover {
transform: rotate(-10deg);
font-weight: bold;
color: pink;
}
}
}
}
}
.characterBlock {
position: relative;
opacity: 0;
width: 980px;
height: 314px;
margin: 20px auto;
padding: 30px;
background-image: url('https://static.catherine-fc.com/media/playerbg.png');
background-repeat: none;
font-family: var(--font-mplus), sans-serif;
&:nth-child(odd) {
animation: slideInFromLeft 1s forwards;
}
&:nth-child(even) {
animation: slideInFromRight 1s forwards;
}
}
@keyframes slideInFromLeft {
0% {
transform: translateX(-100%);
}
100% {
opacity: 1;
transform: translateX(0);
}
}
@keyframes slideInFromRight {
0% {
transform: translateX(100%);
}
100% {
opacity: 1;
transform: translateX(0);
}
}
@keyframes upAndDown {
0%,
100% {
transform: translateY(0);
}
50% {
transform: translateY(-5%);
}
}
@media (max-width: 600px) {
.buynow {
display: none;
}
}
@mixin characterImage($url) {
width: 240px;
height: 240px;
margin: 0 20px 0 0;
background-image: url($url);
background-size: contain;
float: left;
}
.character-blue_cap {
@include characterImage('https://static.catherine-fc.com/media/00_bluecap_1204.png');
}
.character-red_cap {
@include characterImage('https://static.catherine-fc.com/media/00_redcap_1204.png');
}
.character-vincent_shirt {
@include characterImage('https://static.catherine-fc.com/media/01_vincent_1204.png');
}
.character-vincent_sheep {
@include characterImage('https://static.catherine-fc.com/media/01_sheep_vincent_1204.png');
}
.character-katherine {
@include characterImage('https://static.catherine-fc.com/media/02_katherine_1204.png');
}
.character-catherine {
@include characterImage('https://static.catherine-fc.com/media/03_catherine_1204.png');
}
.character-rin {
@include characterImage('https://static.catherine-fc.com/media/04_rin_1204.png');
}
.character-orlando {
@include characterImage('https://static.catherine-fc.com/media/05_orlando_1204.png');
}
.character-johny {
@include characterImage('https://static.catherine-fc.com/media/06_jonny_1204.png');
}
.character-tobby {
@include characterImage('https://static.catherine-fc.com/media/07_tobby_1204.png');
}
.character-erica {
@include characterImage('https://static.catherine-fc.com/media/08_erika_1204.png');
}
.character-master {
@include characterImage('https://static.catherine-fc.com/media/09_master_1204.png');
}
.character-joker {
@include characterImage('https://static.catherine-fc.com/media/13_joker_1204.png');
}
.titlePlayer {
position: relative;
display: flex;
margin-bottom: 10px;
}
.titlePlayerBlock {
padding: 5px 10px;
background-color: white;
transform: rotate(-5deg);
color: black;
font-family: var(--font-mplus), sans-serif;
}
.aboutNoticeBlock {
position: relative;
width: 980px;
height: 800px;
margin: 20px auto;
padding: 50px;
background-image: url('https://static.catherine-fc.com/media/playerbg.png');
background-repeat: none;
background-size: 980px 800px;
font-family: var(--font-mplus), sans-serif;
}
.sheepAbout {
position: relative;
width: 207px;
height: 350px;
float: left;
margin-top: 70px;
bottom: 0;
left: 0;
background-image: url('https://static.catherine-fc.com/media/title_sheep.png');
background-repeat: none;
}
.guideBody {
position: relative;
margin: 20px auto;
width: 980px;
}
.centerVideo {
width: 100%;
display: flex;
justify-content: center;
}
.aboutContactBox {
position: relative;
width: 128px;
height: 128px;
margin: 20px;
background-image: url('https://static.catherine-fc.com/media/letterbox.png');
background-size: 128px 128px;
background-repeat: none;
& > a {
display: block;
width: 128px;
height: 128px;
}
}
.contactBox {
position: relative;
width: 128px;
height: 128px;
margin: 20px auto;
background-image: url('https://static.catherine-fc.com/media/letterbox.png');
background-size: 128px 128px;
background-repeat: none;
& > a {
display: block;
width: 128px;
height: 128px;
}
}
.mainBody {
position: flex;
margin: 20px auto;
width: 980px;
align-items: center;
justify-content: center;
}
.chalice {
width: 400px;
height: 340px;
margin: auto;
background-image: url('https://static.catherine-fc.com/media/chalice.png');
background-size: contain;
background-repeat: none;
}
.evojapan2023 {
width: 500px;
height: 471px;
margin: auto;
background-image: url('https://static.catherine-fc.com/media/evo_logo_shadow_drop.png');
background-size: contain;
background-repeat: none;
}
.evojapan2024 {
width: 500px;
height: 471px;
margin: auto;
background-image: url('https://static.catherine-fc.com/media/evo_2024_logo_shadow_drop.png');
background-size: contain;
background-repeat: none;
}
.evojapan2025 {
width: 500px;
height: 471px;
margin: auto;
background-image: url('https://static.catherine-fc.com/media/evo_logo_2025_shadow_drop.png');
background-size: contain;
background-repeat: none;
}
.evojapan2026 {
width: 500px;
height: 471px;
margin: auto;
background-image: url('https://static.catherine-fc.com/media/evo_logo_2026_shadow_drop.png');
background-size: contain;
background-repeat: none;
}
.evojapan2023kaisaikettei {
width: 846px;
height: 285px;
margin: auto;
background-image: url('https://static.catherine-fc.com/media/kaisaikettei3.png');
background-size: contain;
}
.evojapan2023catherinetonamel {
width: 412px;
height: 389px;
background-image: url('https://static.catherine-fc.com/media/catherine_logo_classic.png');
background-size: contain;
background-repeat: none;
&> a {
display:block;
width: 412px;
height: 389px;
}
}
.evojapan2023catherinefullbodytonamel {
width: 517px;
height: 319px;
background-image: url('https://static.catherine-fc.com/media/catherine_fullbody_logo.png');
background-size: contain;
background-repeat: none;
&> a {
display:block;
width: 517px;
height: 319px;
}
}
.group {
width: 900px;
height: 389px;
margin: auto;
display: flex;
background-size: contain;
background-repeat: none;
}
.players {
width: 900px;
height: 606px;
margin: auto;
background-image: url('https://static.catherine-fc.com/media/players.png');
background-size: contain;
background-repeat: none;
}
.scoreboardImage {
width: 567px;
height: 485px;
margin: auto;
background-image: url('https://static.catherine-fc.com/media/scoreboard.png');
background-size: contain;
background-repeat: none;
}
.titleImageStrayShip0 {
width: 808px;
height: 119px;
margin: auto;
background-image: url('https://static.catherine-fc.com/media/straysheepcup0.png');
background-size: contain;
background-repeat: none;
}
.titleImageStrayShip4 {
width: 808px;
height: 119px;
margin: auto;
background-image: url('https://static.catherine-fc.com/media/straysheepcup4.png');
background-size: contain;
background-repeat: none;
}
.rule {
width: 900px;
height: 637px;
margin: auto;
background-image: url('https://static.catherine-fc.com/media/rule.png');
background-size: contain;
background-repeat: none;
}
.tonamel {
width: 900px;
height: 637px;
margin: auto;
background-image: url('https://static.catherine-fc.com/media/tonamel.png');
background-size: contain;
background-repeat: none;
&> a {
display:block;
width: 900px;
height: 637px;
}
}
.padding {
width: 900px;
height: 100px;
margin: auto;
}
.players0801 {
width: 899px;
height: 696px;
margin: auto;
background-image: url('https://static.catherine-fc.com/media/0801.png');
background-size: contain;
background-repeat: none;
}
.players0802 {
width: 900px;
height: 710px;
margin: auto;
background-image: url('https://static.catherine-fc.com/media/0802.png');
background-size: contain;
background-repeat: none;
}
.players0808 {
width: 900px;
height: 710px;
margin: auto;
background-image: url('https://static.catherine-fc.com/media/0808.png');
background-size: contain;
background-repeat: none;
}
.players0809 {
width: 900px;
height: 696px;
margin: auto;
background-image: url('https://static.catherine-fc.com/media/0809.png');
background-size: contain;
background-repeat: none;
}
.players0815 {
width: 900px;
height: 696px;
margin: auto;
background-image: url('https://static.catherine-fc.com/media/0815.png');
background-size: contain;
background-repeat: none;
}

40
nextjs/tsconfig.json Normal file
View File

@@ -0,0 +1,40 @@
{
"compilerOptions": {
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": [
"./src/*"
]
},
"target": "ES2017"
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}

7
package.json Normal file
View File

@@ -0,0 +1,7 @@
{
"name": "catherine-league",
"private": true,
"workspaces": [
"nextjs"
]
}