Add member accounts, follow-based leaderboard, and dedicated Postgres

Members register via email+password (scrypt) or Google OAuth — same
signed-cookie + scrypt pattern as LokiLab (lib/auth.ts, member-password.ts,
member-auth.ts, google-oauth.ts), own AUTH_SECRET and own OAuth client,
own dedicated Postgres database (lokiloto-db on Coolify), fully isolated
from LokiLab's own DB and auth.

Leaderboard tracks who follows Loki's picks most accurately — members
star a pick from the results panel (FollowButton), resolution reuses
LokiLab's own lastDraw.won, no money or pooled play involved anywhere.
Leaderboard page renders a horizontal bar chart (recharts) plus a ranked
list.

Profile page: public nickname (required to appear on the leaderboard),
list of followed picks. Header now carries nav + a user menu (avatar
dropdown when signed in, "Connexion" button otherwise).

Dockerfile runs prisma migrate deploy at container start via
docker-entrypoint.sh, same pattern as LokiLab.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Nazim Kri
2026-10-30 09:02:26 -04:00
co-authored by Claude Sonnet 5
parent fc69d4a668
commit c3a0a7b765
36 changed files with 2419 additions and 27 deletions
+12 -1
View File
@@ -1,10 +1,13 @@
# LokiLoto — Next.js 16 standalone, for Coolify.
FROM node:22-alpine AS base
RUN apk add --no-cache libc6-compat
RUN apk add --no-cache libc6-compat openssl
WORKDIR /app
FROM base AS deps
COPY package.json package-lock.json* ./
# prisma/schema.prisma is needed before install: the "prisma" package's own
# postinstall hook runs `prisma generate`, which fails without it.
COPY prisma ./prisma
RUN npm install --no-audit --no-fund --include=dev
FROM base AS builder
@@ -22,6 +25,14 @@ RUN addgroup -g 1001 -S nodejs && adduser -S nextjs -u 1001
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
# Prisma CLI for migrate deploy at container start — see docker-entrypoint.sh.
# Kept out of ./node_modules so it never shadows the app's own traced
# runtime deps; the entrypoint points NODE_PATH at it only for this command.
COPY --from=deps --chown=nextjs:nodejs /app/node_modules ./cli-deps/node_modules
COPY --from=builder --chown=nextjs:nodejs /app/prisma ./prisma
COPY --from=builder --chown=nextjs:nodejs /app/docker-entrypoint.sh ./docker-entrypoint.sh
RUN chmod +x ./docker-entrypoint.sh
USER nextjs
EXPOSE 3000
ENTRYPOINT ["./docker-entrypoint.sh"]
CMD ["node", "server.js"]
+19
View File
@@ -0,0 +1,19 @@
"use server"
import { revalidatePath } from "next/cache"
import { getCurrentMember } from "@/lib/member-auth"
import { followPick, unfollowPick } from "@/lib/follows"
export async function toggleFollowAction(lotteryId: string, country: string, targetDrawDate: string, isFollowing: boolean) {
const member = await getCurrentMember()
if (!member) return { ok: false as const, needsAuth: true as const }
if (isFollowing) {
await unfollowPick(member.id, lotteryId, targetDrawDate)
} else {
await followPick(member.id, lotteryId, country, targetDrawDate)
}
revalidatePath("/")
revalidatePath("/profil")
return { ok: true as const, needsAuth: false as const }
}
+42
View File
@@ -0,0 +1,42 @@
import { NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import { exchangeGoogleCode } from '@/lib/google-oauth'
import { createMemberSession } from '@/lib/member-auth'
import { prisma } from '@/lib/db'
const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'https://lotoloki.top'
function safeNext(raw: string): string {
return raw.startsWith('/') && !raw.startsWith('//') ? raw : '/'
}
export async function GET(req: Request) {
const url = new URL(req.url)
const origin = SITE_URL
const code = url.searchParams.get('code')
const state = url.searchParams.get('state')
const jar = await cookies()
const savedState = jar.get('g_state')?.value
if (!code || !state || state !== savedState) {
return NextResponse.redirect(`${origin}/connexion?error=oauth_state`)
}
const next = safeNext(decodeURIComponent(state.split('.')[1] ?? '/'))
const profile = await exchangeGoogleCode(code)
if (!profile?.email) {
return NextResponse.redirect(`${origin}/connexion?error=oauth_failed`)
}
const email = profile.email.toLowerCase()
const user = await prisma.user.upsert({
where: { googleSub: profile.sub },
update: { email, name: profile.name || email.split('@')[0], avatarUrl: profile.picture ?? null },
create: { email, name: profile.name || email.split('@')[0], avatarUrl: profile.picture ?? null, googleSub: profile.sub },
})
await createMemberSession(user.id)
const res = NextResponse.redirect(`${origin}${next}`)
res.cookies.delete('g_state')
return res
}
+26
View File
@@ -0,0 +1,26 @@
import { NextResponse } from 'next/server'
import { getGoogleAuthUrl, googleEnabled } from '@/lib/google-oauth'
function safeNext(raw: string | null): string {
return raw && raw.startsWith('/') && !raw.startsWith('//') ? raw : '/'
}
const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'https://lotoloki.top'
export async function GET(req: Request) {
const url = new URL(req.url)
if (!googleEnabled) {
return NextResponse.redirect(`${SITE_URL}/connexion?error=google_not_configured`)
}
const next = safeNext(url.searchParams.get('next'))
const state = `${crypto.randomUUID()}.${encodeURIComponent(next)}`
const res = NextResponse.redirect(getGoogleAuthUrl(state))
res.cookies.set('g_state', state, {
httpOnly: true,
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
maxAge: 600,
path: '/',
})
return res
}
+9
View File
@@ -0,0 +1,9 @@
import { NextResponse } from 'next/server'
import { destroyMemberSession } from '@/lib/member-auth'
const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'https://lotoloki.top'
export async function POST() {
await destroyMemberSession()
return NextResponse.redirect(`${SITE_URL}/`, { status: 303 })
}
+59
View File
@@ -0,0 +1,59 @@
import type { Metadata } from "next"
import { leaderboard } from "@/lib/follows"
import { AppHeader } from "@/components/app-header"
import { LeaderboardChart } from "@/components/leaderboard-chart"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Trophy } from "lucide-react"
export const metadata: Metadata = { title: "Classement — LokiLoto" }
export const instant = false
export default async function LeaderboardPage() {
const standings = await leaderboard(20)
return (
<main className="flex flex-1 flex-col">
<AppHeader />
<div className="mx-auto w-full max-w-3xl flex-1 px-4 py-6 sm:px-6">
<h1 className="text-2xl font-bold tracking-tight">Classement</h1>
<p className="mt-1 text-sm text-muted-foreground">
Les membres qui suivent le plus fidèlement les choix de Loki — aucun argent réel en jeu,
seulement le taux de réussite des pronostics suivis.
</p>
{standings.length === 0 ? (
<p className="mt-8 text-sm text-muted-foreground">
Personne n&apos;a encore suivi de pronostic. Le classement apparaîtra dès les premiers
tirages résolus.
</p>
) : (
<>
<div className="mt-6 rounded-md border border-border/60 bg-panel p-4">
<LeaderboardChart standings={standings} />
</div>
<div className="mt-4 divide-y divide-border rounded-md border border-border/60 bg-panel">
{standings.map((s, i) => (
<div key={s.userId} className="flex items-center gap-3 px-4 py-2.5 text-sm">
<span className="w-5 shrink-0 text-center text-xs text-muted-foreground tabular-nums">
{i + 1}
</span>
<Avatar className="h-7 w-7 shrink-0">
<AvatarImage src={s.avatarUrl ?? undefined} alt="" />
<AvatarFallback>{s.displayName.charAt(0).toUpperCase()}</AvatarFallback>
</Avatar>
<span className="flex-1 font-medium">{s.displayName}</span>
{i === 0 && <Trophy className="h-4 w-4 text-accent" />}
<span className="text-xs text-muted-foreground">{s.followed} suivis</span>
<span className="w-12 text-right font-semibold tabular-nums">
{(s.winRate * 100).toFixed(0)}%
</span>
</div>
))}
</div>
</>
)}
</div>
</main>
)
}
+89
View File
@@ -0,0 +1,89 @@
'use server'
import { headers } from 'next/headers'
import { redirect } from 'next/navigation'
import { z } from 'zod'
import { prisma } from '@/lib/db'
import { createMemberSession } from '@/lib/member-auth'
import { hashPassword, verifyPassword, loginAllowed, recordLoginFailure, clearLoginFailures } from '@/lib/member-password'
export interface MemberAuthState {
ok: boolean
message: string
}
const signupSchema = z.object({
name: z.string().trim().min(1).max(80),
email: z.string().trim().toLowerCase().email(),
password: z.string().min(8).max(200),
next: z.string().startsWith('/').refine((s) => !s.startsWith('//'), { message: 'invalid next' }),
})
const loginSchema = z.object({
email: z.string().trim().toLowerCase().email(),
password: z.string().min(1).max(200),
next: z.string().startsWith('/').refine((s) => !s.startsWith('//'), { message: 'invalid next' }),
})
async function clientIp(): Promise<string> {
const h = await headers()
return (h.get('x-forwarded-for')?.split(',')[0] ?? h.get('x-real-ip') ?? 'unknown').trim()
}
export async function signupWithPassword(_prev: MemberAuthState, formData: FormData): Promise<MemberAuthState> {
const ip = await clientIp()
if (!loginAllowed(ip)) return { ok: false, message: 'Trop de tentatives. Réessayez dans 15 minutes.' }
const parsed = signupSchema.safeParse({
name: formData.get('name'),
email: formData.get('email'),
password: formData.get('password'),
next: formData.get('next') || '/profil',
})
if (!parsed.success) {
recordLoginFailure(ip)
return { ok: false, message: 'Nom, courriel valide et mot de passe (8 caractères min.) requis.' }
}
const existing = await prisma.user.findUnique({ where: { email: parsed.data.email } })
if (existing) {
return { ok: false, message: 'Un compte existe déjà avec ce courriel. Connectez-vous plutôt.' }
}
const user = await prisma.user.create({
data: {
email: parsed.data.email,
name: parsed.data.name,
passwordHash: hashPassword(parsed.data.password),
},
})
clearLoginFailures(ip)
await createMemberSession(user.id)
redirect(parsed.data.next)
}
export async function loginWithPassword(_prev: MemberAuthState, formData: FormData): Promise<MemberAuthState> {
const ip = await clientIp()
if (!loginAllowed(ip)) return { ok: false, message: 'Trop de tentatives. Réessayez dans 15 minutes.' }
const parsed = loginSchema.safeParse({
email: formData.get('email'),
password: formData.get('password'),
next: formData.get('next') || '/profil',
})
if (!parsed.success) {
recordLoginFailure(ip)
return { ok: false, message: 'Courriel ou mot de passe incorrect.' }
}
const user = await prisma.user.findUnique({ where: { email: parsed.data.email } })
if (!user?.passwordHash || !verifyPassword(parsed.data.password, user.passwordHash)) {
recordLoginFailure(ip)
return { ok: false, message: 'Courriel ou mot de passe incorrect.' }
}
clearLoginFailures(ip)
await createMemberSession(user.id)
redirect(parsed.data.next)
}
+90
View File
@@ -0,0 +1,90 @@
import type { Metadata } from "next"
import Link from "next/link"
import { redirect } from "next/navigation"
import { getCurrentMember } from "@/lib/member-auth"
import { MemberAuthForm } from "@/components/member-auth-form"
import { LokiMark } from "@/components/loki-mark"
export const metadata: Metadata = { title: "Connexion — LokiLoto" }
export const instant = false
const ERROR_FR: Record<string, string> = {
oauth_state: "La connexion a expiré ou a été interrompue. Réessayez.",
oauth_failed: "La connexion avec Google a échoué. Réessayez.",
google_not_configured: "La connexion Google n'est pas encore activée sur ce site.",
}
export default async function LoginPage({
searchParams,
}: {
searchParams: Promise<Record<string, string | string[] | undefined>>
}) {
const member = await getCurrentMember()
if (member) redirect("/profil")
const sp = await searchParams
const errorKey = typeof sp.error === "string" ? sp.error : null
const error = errorKey ? (ERROR_FR[errorKey] ?? "Une erreur est survenue. Réessayez.") : null
const next = typeof sp.next === "string" && sp.next.startsWith("/") ? sp.next : "/profil"
return (
<main className="flex flex-1 items-center justify-center px-4 py-12">
<div className="w-full max-w-sm">
<Link href="/" className="mb-8 inline-flex items-center gap-2">
<LokiMark className="h-8 w-8 text-accent" />
<span className="text-lg font-bold tracking-tight">LokiLoto</span>
</Link>
<h1 className="text-xl font-bold tracking-tight">Connexion</h1>
<p className="mt-1 text-sm text-muted-foreground">
Suivez les choix de Loki, apparaissez au classement, gardez votre pays favori.
</p>
{error && <p className="mt-4 text-xs text-destructive">{error}</p>}
<div className="mt-6">
<MemberAuthForm next={next} />
</div>
<div className="my-5 flex items-center gap-3 text-[11px] text-muted-foreground">
<span className="h-px flex-1 bg-border" />
ou
<span className="h-px flex-1 bg-border" />
</div>
<a
href={`/api/auth/google?next=${encodeURIComponent(next)}`}
className="flex h-9 w-full items-center justify-center gap-3 rounded-md border border-border bg-panel text-sm font-medium transition-colors hover:bg-panel-hover"
>
<svg viewBox="0 0 24 24" className="h-4 w-4 shrink-0" aria-hidden="true">
<path
fill="#4285F4"
d="M23.52 12.27c0-.85-.07-1.47-.23-2.12H12v3.85h6.6c-.13 1.1-.86 2.76-2.47 3.87l-.02.15 3.59 2.78.25.02c2.28-2.1 3.57-5.2 3.57-8.55"
/>
<path
fill="#34A853"
d="M12 24c3.24 0 5.95-1.07 7.93-2.91l-3.78-2.93c-1.02.7-2.4 1.19-4.15 1.19-3.18 0-5.88-2.1-6.84-5l-.14.01-3.73 2.89-.05.13C3.21 21.3 7.26 24 12 24"
/>
<path
fill="#FBBC05"
d="M5.16 14.35A7.3 7.3 0 0 1 4.75 12c0-.81.14-1.6.4-2.35l-.01-.16-3.78-2.94-.12.06A11.97 11.97 0 0 0 0 12c0 1.93.46 3.76 1.24 5.39l3.92-3.04"
/>
<path
fill="#EA4335"
d="M12 4.75c2.25 0 3.77.97 4.64 1.78l3.39-3.31C17.94 1.19 15.24 0 12 0 7.26 0 3.21 2.7 1.24 6.61l3.91 3.04c.97-2.9 3.67-5 6.85-5"
/>
</svg>
Continuer avec Google
</a>
<p className="mt-6 text-[11px] leading-relaxed text-muted-foreground">
Un compte LokiLoto sert à suivre vos pronostics et apparaître au classement. Aucun billet
n&apos;est vendu, aucun argent ne transite par ce site.
</p>
<Link href="/" className="mt-6 inline-block text-xs text-muted-foreground hover:text-foreground">
← Retour au site
</Link>
</div>
</main>
)
}
+13 -14
View File
@@ -1,9 +1,11 @@
import { Suspense } from "react"
import { COUNTRIES, countryTheme } from "@/lib/countries"
import { getArmyFeed } from "@/lib/lokilab-feed"
import { getCurrentMember } from "@/lib/member-auth"
import { listFollowedPicks } from "@/lib/follows"
import { CountryNav, CountryNavMobile } from "@/components/country-nav"
import { LotteryResultsPanel } from "@/components/lottery-results-panel"
import { LokiMark } from "@/components/loki-mark"
import { AppHeader } from "@/components/app-header"
import { Skeleton } from "@/components/ui/skeleton"
export const instant = false
@@ -26,25 +28,17 @@ export default async function Home({
)
}
function AppHeader() {
return (
<div className="h-14 border-b border-border/60 bg-card">
<div className="mx-auto flex h-full max-w-6xl items-center gap-2 px-4 sm:px-6">
<LokiMark className="h-8 w-8 shrink-0 text-accent" />
<span className="text-base font-bold tracking-tight">LokiLoto</span>
</div>
</div>
)
}
async function HomeContent({ activeCode }: { activeCode: string }) {
const feed = await getArmyFeed()
const [feed, member] = await Promise.all([getArmyFeed(), getCurrentMember()])
const theme = countryTheme(activeCode)
const lotteries = feed.lotteries.filter((l) => l.country === activeCode)
const totalWins = lotteries.reduce((sum, l) => sum + l.lifetime.wins, 0)
const totalTracked = lotteries.reduce((sum, l) => sum + l.lifetime.picksTracked, 0)
const countryMembers = feed.army.byCountry[activeCode] ?? 0
const follows = member ? await listFollowedPicks(member.id) : []
const followedKeys = new Set(follows.map((f) => `${f.lotteryId}:${f.targetDrawDate}`))
return (
<div
style={{ "--accent": theme.accent, "--accent-soft": theme.accentSoft } as React.CSSProperties}
@@ -78,7 +72,12 @@ async function HomeContent({ activeCode }: { activeCode: string }) {
</div>
{lotteries.length > 0 ? (
<LotteryResultsPanel lotteries={lotteries} />
<LotteryResultsPanel
lotteries={lotteries}
country={activeCode}
followedKeys={followedKeys}
isAuthenticated={!!member}
/>
) : (
<div className="rounded-md border border-dashed border-border py-16 text-center text-sm text-muted-foreground">
Aucune loterie suivie pour {theme.name} pour le moment.
+25
View File
@@ -0,0 +1,25 @@
"use server"
import { z } from "zod"
import { revalidatePath } from "next/cache"
import { prisma } from "@/lib/db"
import { getCurrentMember } from "@/lib/member-auth"
const nicknameSchema = z.string().trim().min(2).max(24)
export interface NicknameState {
ok: boolean
message: string
}
export async function setNicknameAction(_prev: NicknameState, formData: FormData): Promise<NicknameState> {
const member = await getCurrentMember()
if (!member) return { ok: false, message: "Non connecté." }
const parsed = nicknameSchema.safeParse(formData.get("nickname"))
if (!parsed.success) return { ok: false, message: "Pseudo invalide (2 à 24 caractères)." }
await prisma.user.update({ where: { id: member.id }, data: { publicNickname: parsed.data } })
revalidatePath("/profil")
return { ok: true, message: "Pseudo mis à jour." }
}
+63
View File
@@ -0,0 +1,63 @@
import type { Metadata } from "next"
import { redirect } from "next/navigation"
import { getCurrentMember } from "@/lib/member-auth"
import { listFollowedPicks } from "@/lib/follows"
import { countryTheme } from "@/lib/countries"
import { AppHeader } from "@/components/app-header"
import { NicknameForm } from "@/components/nickname-form"
import { Badge } from "@/components/ui/badge"
export const metadata: Metadata = { title: "Mon profil — LokiLoto" }
export const instant = false
export default async function ProfilePage() {
const member = await getCurrentMember()
if (!member) redirect("/connexion?next=/profil")
const follows = await listFollowedPicks(member.id)
return (
<main className="flex flex-1 flex-col">
<AppHeader />
<div className="mx-auto w-full max-w-3xl flex-1 px-4 py-6 sm:px-6">
<h1 className="text-2xl font-bold tracking-tight">Mon profil</h1>
<p className="mt-1 text-sm text-muted-foreground">{member.email}</p>
<div className="mt-6 rounded-md border border-border/60 bg-panel p-4">
<h2 className="mb-2 text-sm font-semibold">Pseudo public</h2>
<p className="mb-3 text-xs text-muted-foreground">
Affiché au classement à la place de votre nom. Requis pour apparaître publiquement.
</p>
<NicknameForm currentNickname={member.publicNickname} />
</div>
<div className="mt-6">
<h2 className="mb-2 text-sm font-semibold">
Pronostics suivis <Badge variant="secondary">{follows.length}</Badge>
</h2>
{follows.length === 0 ? (
<p className="text-sm text-muted-foreground">
Vous ne suivez aucun pronostic de Loki pour l&apos;instant. Suivez-en un depuis la page
des résultats pour apparaître au classement.
</p>
) : (
<div className="divide-y divide-border rounded-md border border-border/60 bg-panel">
{follows.map((f) => {
const theme = countryTheme(f.country)
return (
<div key={f.id} className="flex items-center justify-between px-4 py-2.5 text-sm">
<span className="flex items-center gap-2">
<span aria-hidden>{theme.flagEmoji}</span>
{f.lotteryId}
</span>
<span className="text-xs text-muted-foreground">{f.targetDrawDate}</span>
</div>
)
})}
</div>
)}
</div>
</div>
</main>
)
}
+33
View File
@@ -0,0 +1,33 @@
import Link from "next/link"
import { Suspense } from "react"
import { LokiMark } from "@/components/loki-mark"
import { UserMenu } from "@/components/user-menu"
import { Skeleton } from "@/components/ui/skeleton"
export function AppHeader() {
return (
<div className="h-14 border-b border-border/60 bg-card">
<div className="mx-auto flex h-full max-w-6xl items-center gap-5 px-4 sm:px-6">
<Link href="/" className="flex shrink-0 items-center gap-2">
<LokiMark className="h-8 w-8 text-accent" />
<span className="text-base font-bold tracking-tight">LokiLoto</span>
</Link>
<nav className="hidden items-center gap-4 text-sm text-muted-foreground sm:flex">
<Link href="/" className="hover:text-foreground">
Résultats
</Link>
<Link href="/classement" className="hover:text-foreground">
Classement
</Link>
</nav>
<div className="ml-auto">
<Suspense fallback={<Skeleton className="h-8 w-8 rounded-full" />}>
<UserMenu />
</Suspense>
</div>
</div>
</div>
)
}
+53
View File
@@ -0,0 +1,53 @@
"use client"
import { useState, useTransition } from "react"
import { useRouter } from "next/navigation"
import { Star } from "lucide-react"
import { toggleFollowAction } from "@/app/actions"
import { cn } from "@/lib/utils"
export function FollowButton({
lotteryId,
country,
targetDrawDate,
initialFollowing,
isAuthenticated,
}: {
lotteryId: string
country: string
targetDrawDate: string
initialFollowing: boolean
isAuthenticated: boolean
}) {
const [following, setFollowing] = useState(initialFollowing)
const [pending, startTransition] = useTransition()
const router = useRouter()
function handleClick() {
if (!isAuthenticated) {
router.push(`/connexion?next=${encodeURIComponent(window.location.pathname + window.location.search)}`)
return
}
const next = !following
setFollowing(next)
startTransition(async () => {
const res = await toggleFollowAction(lotteryId, country, targetDrawDate, following)
if (!res.ok) setFollowing(!next)
})
}
return (
<button
type="button"
onClick={handleClick}
disabled={pending}
title={following ? "Ne plus suivre" : "Suivre ce pronostic"}
className={cn(
"flex h-6 w-6 shrink-0 items-center justify-center rounded transition-colors",
following ? "text-accent" : "text-muted-foreground hover:text-foreground"
)}
>
<Star className="h-4 w-4" fill={following ? "currentColor" : "none"} />
</button>
)
}
+36
View File
@@ -0,0 +1,36 @@
"use client"
import { Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts"
import type { MemberStanding } from "@/lib/follows"
export function LeaderboardChart({ standings }: { standings: MemberStanding[] }) {
const data = standings.slice(0, 10).map((s) => ({
name: s.displayName,
"Taux de réussite": Math.round(s.winRate * 100),
}))
return (
<ResponsiveContainer width="100%" height={Math.max(220, data.length * 36)}>
<BarChart data={data} layout="vertical" margin={{ left: 8, right: 24, top: 8, bottom: 8 }}>
<CartesianGrid strokeDasharray="3 3" stroke="var(--border)" horizontal={false} />
<XAxis type="number" domain={[0, 100]} tick={{ fill: "var(--muted-foreground)", fontSize: 12 }} unit="%" />
<YAxis
type="category"
dataKey="name"
width={110}
tick={{ fill: "var(--foreground)", fontSize: 12 }}
/>
<Tooltip
contentStyle={{
background: "var(--panel)",
border: "1px solid var(--border)",
borderRadius: 6,
fontSize: 12,
}}
cursor={{ fill: "var(--panel-hover)" }}
/>
<Bar dataKey="Taux de réussite" fill="var(--accent)" radius={[0, 4, 4, 0]} />
</BarChart>
</ResponsiveContainer>
)
}
+24 -2
View File
@@ -1,14 +1,36 @@
import { NumberSequence } from "@/components/number-sequence"
import { FollowButton } from "@/components/follow-button"
import type { LotteryFeedEntry } from "@/lib/lokilab-feed"
export function LotteryMobileCard({ entry }: { entry: LotteryFeedEntry }) {
export function LotteryMobileCard({
entry,
country,
isFollowing,
isAuthenticated,
}: {
entry: LotteryFeedEntry
country: string
isFollowing: boolean
isAuthenticated: boolean
}) {
const { lifetime, lastDraw } = entry
const resultSet = new Set(lastDraw?.result ?? [])
return (
<div className="space-y-2.5 border-b border-border/60 p-3 last:border-b-0">
<div className="flex items-center justify-between">
<p className="font-semibold">{entry.name}</p>
<p className="flex items-center gap-1.5 font-semibold">
{lastDraw && (
<FollowButton
lotteryId={entry.id}
country={country}
targetDrawDate={lastDraw.date}
initialFollowing={isFollowing}
isAuthenticated={isAuthenticated}
/>
)}
{entry.name}
</p>
{lifetime.picksTracked > 0 ? (
<p className="text-xs text-muted-foreground">
<span className="font-semibold text-foreground tabular-nums">
+27 -4
View File
@@ -2,10 +2,21 @@ import { LotteryRow } from "@/components/lottery-row"
import { LotteryMobileCard } from "@/components/lottery-mobile-card"
import type { LotteryFeedEntry } from "@/lib/lokilab-feed"
export function LotteryResultsPanel({ lotteries }: { lotteries: LotteryFeedEntry[] }) {
export function LotteryResultsPanel({
lotteries,
country,
followedKeys,
isAuthenticated,
}: {
lotteries: LotteryFeedEntry[]
country: string
followedKeys: Set<string>
isAuthenticated: boolean
}) {
return (
<div className="overflow-hidden rounded-md border border-border/60 bg-panel">
<div className="hidden sm:grid grid-cols-[160px_1fr_1fr_72px_120px] gap-3 border-b border-border/60 px-3 py-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">
<div className="hidden sm:grid grid-cols-[28px_160px_1fr_1fr_72px_120px] gap-3 border-b border-border/60 px-3 py-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">
<span />
<span>Loterie</span>
<span>Résultat officiel</span>
<span>Choix de Loki</span>
@@ -15,13 +26,25 @@ export function LotteryResultsPanel({ lotteries }: { lotteries: LotteryFeedEntry
<div className="hidden sm:block">
{lotteries.map((entry) => (
<LotteryRow key={entry.id} entry={entry} />
<LotteryRow
key={entry.id}
entry={entry}
country={country}
isFollowing={entry.lastDraw ? followedKeys.has(`${entry.id}:${entry.lastDraw.date}`) : false}
isAuthenticated={isAuthenticated}
/>
))}
</div>
<div className="sm:hidden">
{lotteries.map((entry) => (
<LotteryMobileCard key={entry.id} entry={entry} />
<LotteryMobileCard
key={entry.id}
entry={entry}
country={country}
isFollowing={entry.lastDraw ? followedKeys.has(`${entry.id}:${entry.lastDraw.date}`) : false}
isAuthenticated={isAuthenticated}
/>
))}
</div>
</div>
+25 -2
View File
@@ -1,12 +1,35 @@
import { NumberSequence } from "@/components/number-sequence"
import { FollowButton } from "@/components/follow-button"
import type { LotteryFeedEntry } from "@/lib/lokilab-feed"
export function LotteryRow({ entry }: { entry: LotteryFeedEntry }) {
export function LotteryRow({
entry,
country,
isFollowing,
isAuthenticated,
}: {
entry: LotteryFeedEntry
country: string
isFollowing: boolean
isAuthenticated: boolean
}) {
const { lifetime, lastDraw } = entry
const resultSet = new Set(lastDraw?.result ?? [])
return (
<div className="grid grid-cols-[160px_1fr_1fr_72px_120px] items-center gap-3 border-b border-border/60 px-3 py-3 text-sm last:border-b-0 hover:bg-panel-hover/40">
<div className="grid grid-cols-[28px_160px_1fr_1fr_72px_120px] items-center gap-3 border-b border-border/60 px-3 py-3 text-sm last:border-b-0 hover:bg-panel-hover/40">
<div>
{lastDraw && (
<FollowButton
lotteryId={entry.id}
country={country}
targetDrawDate={lastDraw.date}
initialFollowing={isFollowing}
isAuthenticated={isAuthenticated}
/>
)}
</div>
<div className="min-w-0">
<p className="truncate font-semibold leading-tight" title={entry.name}>
{entry.name}
+81
View File
@@ -0,0 +1,81 @@
"use client"
import { useActionState, useState } from "react"
import { loginWithPassword, signupWithPassword, type MemberAuthState } from "@/app/connexion/actions"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { cn } from "@/lib/utils"
const INITIAL: MemberAuthState = { ok: false, message: "" }
export function MemberAuthForm({ next }: { next: string }) {
const [mode, setMode] = useState<"login" | "signup">("login")
const [loginState, loginAction, loginPending] = useActionState(loginWithPassword, INITIAL)
const [signupState, signupActionFn, signupPending] = useActionState(signupWithPassword, INITIAL)
const action = mode === "login" ? loginAction : signupActionFn
const state = mode === "login" ? loginState : signupState
const pending = mode === "login" ? loginPending : signupPending
return (
<div>
<div className="mb-4 flex rounded-md border border-border/60 bg-panel p-1 text-sm">
<button
type="button"
onClick={() => setMode("login")}
className={cn(
"flex-1 rounded py-1.5 font-medium transition-colors",
mode === "login" ? "bg-panel-hover text-foreground" : "text-muted-foreground"
)}
>
Connexion
</button>
<button
type="button"
onClick={() => setMode("signup")}
className={cn(
"flex-1 rounded py-1.5 font-medium transition-colors",
mode === "signup" ? "bg-panel-hover text-foreground" : "text-muted-foreground"
)}
>
Créer un compte
</button>
</div>
<form action={action} className="space-y-3">
<input type="hidden" name="next" value={next} />
{mode === "signup" && (
<div className="space-y-1.5">
<Label htmlFor="name">Nom</Label>
<Input id="name" name="name" type="text" required autoComplete="name" />
</div>
)}
<div className="space-y-1.5">
<Label htmlFor="email">Courriel</Label>
<Input id="email" name="email" type="email" required autoComplete="email" />
</div>
<div className="space-y-1.5">
<Label htmlFor="password">Mot de passe</Label>
<Input
id="password"
name="password"
type="password"
required
minLength={mode === "signup" ? 8 : undefined}
autoComplete={mode === "login" ? "current-password" : "new-password"}
/>
{mode === "signup" && (
<p className="text-[11px] text-muted-foreground">8 caractères minimum.</p>
)}
</div>
{!state.ok && state.message && <p className="text-xs text-destructive">{state.message}</p>}
<Button type="submit" disabled={pending} className="w-full">
{pending ? "…" : mode === "login" ? "Se connecter" : "Créer mon compte"}
</Button>
</form>
</div>
)
}
+24
View File
@@ -0,0 +1,24 @@
"use client"
import { useActionState } from "react"
import { setNicknameAction, type NicknameState } from "@/app/profil/actions"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
const INITIAL: NicknameState = { ok: false, message: "" }
export function NicknameForm({ currentNickname }: { currentNickname: string | null }) {
const [state, action, pending] = useActionState(setNicknameAction, INITIAL)
return (
<form action={action} className="flex items-center gap-2">
<Input name="nickname" defaultValue={currentNickname ?? ""} placeholder="Votre pseudo" maxLength={24} />
<Button type="submit" disabled={pending} size="sm">
{pending ? "…" : "Enregistrer"}
</Button>
{state.message && (
<span className={state.ok ? "text-xs text-success" : "text-xs text-destructive"}>{state.message}</span>
)}
</form>
)
}
+111
View File
@@ -0,0 +1,111 @@
"use client"
import * as React from "react"
import { cn } from "cn"
import { Avatar as AvatarPrimitive } from "radix-ui"
function Avatar({
className,
size = "default",
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root> & {
size?: "default" | "sm" | "lg"
}) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
data-size={size}
className={cn(
"group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten",
className
)}
{...props}
/>
)
}
function AvatarImage({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn(
"aspect-square size-full rounded-full object-cover",
className
)}
{...props}
/>
)
}
function AvatarFallback({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
"flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs",
className
)}
{...props}
/>
)
}
function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="avatar-badge"
className={cn(
"absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground bg-blend-color ring-2 ring-background select-none",
"group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
"group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
"group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
className
)}
{...props}
/>
)
}
function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="avatar-group"
className={cn(
"group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background",
className
)}
{...props}
/>
)
}
function AvatarGroupCount({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="avatar-group-count"
className={cn(
"relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
className
)}
{...props}
/>
)
}
export {
Avatar,
AvatarImage,
AvatarFallback,
AvatarGroup,
AvatarGroupCount,
AvatarBadge,
}
+268
View File
@@ -0,0 +1,268 @@
"use client"
import * as React from "react"
import { cn } from "cn"
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui"
import { CheckIcon, ChevronRightIcon } from "lucide-react"
function DropdownMenu({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
)
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return (
<DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger"
{...props}
/>
)
}
function DropdownMenuContent({
className,
align = "start",
sideOffset = 4,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
align={align}
className={cn("z-50 max-h-(--radix-dropdown-menu-content-available-height) w-(--radix-dropdown-menu-trigger-width) min-w-32 origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:overflow-hidden data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
{...props}
/>
</DropdownMenuPrimitive.Portal>
)
}
function DropdownMenuGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
)
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",
className
)}
{...props}
/>
)
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span
className="pointer-events-none absolute right-2 flex items-center justify-center"
data-slot="dropdown-menu-checkbox-item-indicator"
>
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon
/>
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
)
}
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return (
<DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
)
}
function DropdownMenuRadioItem({
className,
children,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span
className="pointer-events-none absolute right-2 flex items-center justify-center"
data-slot="dropdown-menu-radio-item-indicator"
>
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon
/>
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
)
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7",
className
)}
{...props}
/>
)
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground",
className
)}
{...props}
/>
)
}
function DropdownMenuSub({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto" />
</DropdownMenuPrimitive.SubTrigger>
)
}
function DropdownMenuSubContent({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn("z-50 min-w-[96px] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
{...props}
/>
)
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}
+18
View File
@@ -0,0 +1,18 @@
import * as React from "react"
import { cn } from "cn"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
className
)}
{...props}
/>
)
}
export { Input }
+23
View File
@@ -0,0 +1,23 @@
"use client"
import * as React from "react"
import { cn } from "cn"
import { Label as LabelPrimitive } from "radix-ui"
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }
+55
View File
@@ -0,0 +1,55 @@
import Link from "next/link"
import { getCurrentMember } from "@/lib/member-auth"
import { Button } from "@/components/ui/button"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
export async function UserMenu() {
const member = await getCurrentMember()
if (!member) {
return (
<Button asChild size="sm">
<Link href="/connexion">Connexion</Link>
</Button>
)
}
const displayName = member.publicNickname || member.name
const initial = displayName.charAt(0).toUpperCase()
return (
<DropdownMenu>
<DropdownMenuTrigger className="flex items-center gap-2 rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring">
<Avatar className="h-8 w-8">
<AvatarImage src={member.avatarUrl ?? undefined} alt="" />
<AvatarFallback>{initial}</AvatarFallback>
</Avatar>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-52">
<div className="px-2 py-1.5 text-sm font-medium">{displayName}</div>
<DropdownMenuSeparator />
<DropdownMenuItem asChild>
<Link href="/profil">Mon profil</Link>
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link href="/classement">Classement</Link>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem asChild>
<form action="/api/auth/logout" method="post" className="w-full">
<button type="submit" className="w-full text-left">
Déconnexion
</button>
</form>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
set -e
if [ -n "$DATABASE_URL" ]; then
echo "[entrypoint] DATABASE_URL set, running prisma migrate deploy"
NODE_PATH=/app/cli-deps/node_modules node /app/cli-deps/node_modules/prisma/build/index.js migrate deploy \
|| echo "[entrypoint] migrate deploy failed, continuing to start the app anyway"
else
echo "[entrypoint] DATABASE_URL not set, skipping migrations"
fi
exec "$@"
+77
View File
@@ -0,0 +1,77 @@
/**
* Signed session cookie (HMAC-SHA256 over a base64url payload). Runtime-agnostic:
* only Web Crypto, so it works in route handlers and server actions alike.
* Same scheme as LokiLab (lib/auth.ts), own AUTH_SECRET, own cookie name.
*/
export const MEMBER_SESSION_COOKIE = 'lokiloto_session'
export const SESSION_MAX_AGE = 7 * 24 * 3600
export interface Session {
sub: string
exp: number
}
function secret(): string {
const s = process.env.AUTH_SECRET
if (!s || s.length < 16) throw new Error('AUTH_SECRET is not configured')
return s
}
function toBase64Url(bytes: Uint8Array): string {
let bin = ''
for (const b of bytes) bin += String.fromCharCode(b)
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}
function fromBase64Url(s: string): Uint8Array {
const b64 = s.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (s.length % 4)) % 4)
const bin = atob(b64)
const out = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
return out
}
async function sign(data: string): Promise<string> {
const enc = new TextEncoder()
const key = await crypto.subtle.importKey('raw', enc.encode(secret()), { name: 'HMAC', hash: 'SHA-256' }, false, [
'sign',
])
const sig = await crypto.subtle.sign('HMAC', key, enc.encode(data))
return toBase64Url(new Uint8Array(sig))
}
function safeEqual(a: string, b: string): boolean {
if (a.length !== b.length) return false
let diff = 0
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)
return diff === 0
}
export async function createSessionToken(sub: string): Promise<string> {
const body: Session = { sub, exp: Math.floor(Date.now() / 1000) + SESSION_MAX_AGE }
const payload = toBase64Url(new TextEncoder().encode(JSON.stringify(body)))
return `${payload}.${await sign(payload)}`
}
export async function verifySessionToken(token: string | undefined | null): Promise<Session | null> {
if (!token) return null
const dot = token.indexOf('.')
if (dot <= 0) return null
const payload = token.slice(0, dot)
const sig = token.slice(dot + 1)
let expected: string
try {
expected = await sign(payload)
} catch {
return null
}
if (!safeEqual(sig, expected)) return null
try {
const data = JSON.parse(new TextDecoder().decode(fromBase64Url(payload))) as Partial<Session>
if (typeof data.sub !== 'string' || typeof data.exp !== 'number') return null
if (data.exp <= Math.floor(Date.now() / 1000)) return null
return { sub: data.sub, exp: data.exp }
} catch {
return null
}
}
+9
View File
@@ -0,0 +1,9 @@
import 'server-only'
import { PrismaClient } from '@prisma/client'
/** Singleton across dev hot-reloads (Next.js would otherwise open a new pool per edit). */
const g = globalThis as unknown as { __lokilotoPrisma?: PrismaClient }
export const prisma = g.__lokilotoPrisma ?? new PrismaClient()
if (process.env.NODE_ENV !== 'production') g.__lokilotoPrisma = prisma
+70
View File
@@ -0,0 +1,70 @@
import 'server-only'
import { prisma } from './db'
import { getArmyFeed } from './lokilab-feed'
export async function followPick(userId: string, lotteryId: string, country: string, targetDrawDate: string) {
await prisma.followedPick.upsert({
where: { userId_lotteryId_targetDrawDate: { userId, lotteryId, targetDrawDate } },
update: {},
create: { userId, lotteryId, country, targetDrawDate },
})
}
export async function unfollowPick(userId: string, lotteryId: string, targetDrawDate: string) {
await prisma.followedPick.deleteMany({ where: { userId, lotteryId, targetDrawDate } })
}
export async function listFollowedPicks(userId: string) {
return prisma.followedPick.findMany({ where: { userId }, orderBy: { createdAt: 'desc' } })
}
export interface MemberStanding {
userId: string
displayName: string
avatarUrl: string | null
followed: number
wins: number
winRate: number
}
/**
* Leaderboard = who follows Loki's picks most accurately, not who won money.
* Resolution reuses LokiLab's own lastDraw.won per lottery/date rather than
* re-deriving win logic here — a follow only counts once the matching
* lottery/date pair shows up as LokiLab's most recent resolved draw.
*/
export async function leaderboard(limit = 20): Promise<MemberStanding[]> {
const feed = await getArmyFeed()
const resolvedByKey = new Map<string, boolean>()
for (const l of feed.lotteries) {
if (l.lastDraw?.pick) resolvedByKey.set(`${l.id}:${l.lastDraw.date}`, l.lastDraw.won ?? false)
}
const follows = await prisma.followedPick.findMany({
include: { user: { select: { id: true, name: true, publicNickname: true, avatarUrl: true } } },
})
const byUser = new Map<string, MemberStanding>()
for (const f of follows) {
const key = `${f.lotteryId}:${f.targetDrawDate}`
if (!resolvedByKey.has(key)) continue
const won = resolvedByKey.get(key)!
const entry =
byUser.get(f.userId) ??
({
userId: f.userId,
displayName: f.user.publicNickname || f.user.name,
avatarUrl: f.user.avatarUrl,
followed: 0,
wins: 0,
winRate: 0,
} satisfies MemberStanding)
entry.followed++
if (won) entry.wins++
byUser.set(f.userId, entry)
}
const standings = [...byUser.values()].map((s) => ({ ...s, winRate: s.followed > 0 ? s.wins / s.followed : 0 }))
standings.sort((a, b) => b.winRate - a.winRate || b.followed - a.followed)
return standings.slice(0, limit)
}
+63
View File
@@ -0,0 +1,63 @@
import 'server-only'
/**
* Google OAuth (Authorization Code flow), fetch-only — same pattern as
* LokiLab. Uses a LokiLoto-dedicated OAuth client (project-specific env var
* names, not shared with any other devyouz-lab project's Google client).
*/
const CLIENT_ID = process.env.LOKILOTO_GOOGLE_OAUTH_CLIENT_ID || ''
const CLIENT_SECRET = process.env.LOKILOTO_GOOGLE_OAUTH_CLIENT_SECRET || ''
function appUrl(): string {
return process.env.NEXT_PUBLIC_SITE_URL || 'https://lotoloki.top'
}
export const googleEnabled = !!(CLIENT_ID && CLIENT_SECRET)
export function googleRedirectUri(): string {
return `${appUrl()}/api/auth/google/callback`
}
export function getGoogleAuthUrl(state: string): string {
const params = new URLSearchParams({
client_id: CLIENT_ID,
redirect_uri: googleRedirectUri(),
response_type: 'code',
scope: 'openid email profile',
access_type: 'online',
prompt: 'select_account',
state,
})
return `https://accounts.google.com/o/oauth2/v2/auth?${params}`
}
export interface GoogleProfile {
sub: string
email: string
name: string
picture?: string
email_verified?: boolean
}
export async function exchangeGoogleCode(code: string): Promise<GoogleProfile | null> {
const tokenRes = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
code,
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
redirect_uri: googleRedirectUri(),
grant_type: 'authorization_code',
}),
})
if (!tokenRes.ok) return null
const tokenData = (await tokenRes.json()) as { access_token?: string }
if (!tokenData.access_token) return null
const profileRes = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', {
headers: { Authorization: `Bearer ${tokenData.access_token}` },
})
if (!profileRes.ok) return null
return profileRes.json() as Promise<GoogleProfile>
}
+41
View File
@@ -0,0 +1,41 @@
import 'server-only'
import { cookies } from 'next/headers'
import { createSessionToken, verifySessionToken, MEMBER_SESSION_COOKIE, SESSION_MAX_AGE } from './auth'
import { prisma } from './db'
export async function createMemberSession(userId: string): Promise<void> {
const token = await createSessionToken(userId)
const jar = await cookies()
jar.set(MEMBER_SESSION_COOKIE, token, {
httpOnly: true,
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
maxAge: SESSION_MAX_AGE,
path: '/',
})
}
export async function destroyMemberSession(): Promise<void> {
const jar = await cookies()
jar.delete(MEMBER_SESSION_COOKIE)
}
export interface CurrentMember {
id: string
email: string
name: string
avatarUrl: string | null
publicNickname: string | null
favoriteCountry: string
}
export async function getCurrentMember(): Promise<CurrentMember | null> {
const jar = await cookies()
const session = await verifySessionToken(jar.get(MEMBER_SESSION_COOKIE)?.value)
if (!session) return null
const user = await prisma.user.findUnique({
where: { id: session.sub },
select: { id: true, email: true, name: true, avatarUrl: true, publicNickname: true, favoriteCountry: true },
})
return user
}
+40
View File
@@ -0,0 +1,40 @@
import 'server-only'
import { randomBytes, scryptSync, timingSafeEqual } from 'node:crypto'
/** scrypt password hashing, same scheme as LokiLab. */
export function hashPassword(password: string): string {
const salt = randomBytes(16).toString('hex')
const hash = scryptSync(password, salt, 64).toString('hex')
return `scrypt$${salt}$${hash}`
}
export function verifyPassword(password: string, stored: string): boolean {
const [algo, salt, hex] = stored.split('$')
if (algo !== 'scrypt' || !salt || !hex) return false
const expected = Buffer.from(hex, 'hex')
const actual = scryptSync(password, salt, expected.length)
return actual.length === expected.length && timingSafeEqual(actual, expected)
}
const MAX_FAILURES = 8
const LOCK_MS = 15 * 60 * 1000
const failures = new Map<string, { count: number; until: number }>()
export function loginAllowed(ip: string): boolean {
const f = failures.get(ip)
if (!f) return true
if (f.until && f.until > Date.now()) return false
if (f.until && f.until <= Date.now()) failures.delete(ip)
return true
}
export function recordLoginFailure(ip: string): void {
const f = failures.get(ip) ?? { count: 0, until: 0 }
f.count += 1
if (f.count >= MAX_FAILURES) f.until = Date.now() + LOCK_MS
failures.set(ip, f)
}
export function clearLoginFailures(ip: string): void {
failures.delete(ip)
}
+776 -3
View File
File diff suppressed because it is too large Load Diff
+6 -1
View File
@@ -8,15 +8,20 @@
"start": "next start"
},
"dependencies": {
"@prisma/client": "6.19.3",
"class-variance-authority": "^0.7.1",
"cn": "^0.5.0",
"lucide-react": "^1.64.0",
"next": "16.4.3",
"prisma": "6.19.3",
"radix-ui": "^1.8.1",
"react": "19.3.0",
"react-dom": "19.3.0",
"recharts": "^3.10.1",
"server-only": "^0.0.1",
"shadcn": "^4.23.0",
"tw-animate-css": "^1.4.0"
"tw-animate-css": "^1.4.0",
"zod": "^4.6.7"
},
"devDependencies": {
"@tailwindcss/turbopack": "^4",
@@ -0,0 +1,45 @@
-- CreateTable
CREATE TABLE "User" (
"id" TEXT NOT NULL,
"email" TEXT NOT NULL,
"name" TEXT NOT NULL,
"avatarUrl" TEXT,
"googleSub" TEXT,
"passwordHash" TEXT,
"publicNickname" TEXT,
"favoriteCountry" TEXT NOT NULL DEFAULT 'CA-QC',
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "FollowedPick" (
"id" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"lotteryId" TEXT NOT NULL,
"country" TEXT NOT NULL,
"targetDrawDate" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "FollowedPick_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
-- CreateIndex
CREATE UNIQUE INDEX "User_googleSub_key" ON "User"("googleSub");
-- CreateIndex
CREATE INDEX "FollowedPick_userId_idx" ON "FollowedPick"("userId");
-- CreateIndex
CREATE INDEX "FollowedPick_lotteryId_targetDrawDate_idx" ON "FollowedPick"("lotteryId", "targetDrawDate");
-- CreateIndex
CREATE UNIQUE INDEX "FollowedPick_userId_lotteryId_targetDrawDate_key" ON "FollowedPick"("userId", "lotteryId", "targetDrawDate");
-- AddForeignKey
ALTER TABLE "FollowedPick" ADD CONSTRAINT "FollowedPick_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+3
View File
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
+52
View File
@@ -0,0 +1,52 @@
generator client {
provider = "prisma-client-js"
binaryTargets = ["native", "linux-musl-openssl-3.0.x"]
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
/// A member account, created on email+password signup or Google sign-in —
/// same dual-path pattern as LokiLab (lib/member-password.ts / google-oauth.ts).
model User {
id String @id @default(cuid())
email String @unique
name String
avatarUrl String?
googleSub String? @unique
/// scrypt hash, format `scrypt$<salt>$<hex>`. Null when the account was
/// created via Google only.
passwordHash String?
/// Shown instead of name/email anywhere this member's activity is public
/// (leaderboard, follow counts). Must be set before a member appears
/// publicly.
publicNickname String?
/// Last country tab the member viewed, restored on next visit.
favoriteCountry String @default("CA-QC")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
follows FollowedPick[]
}
/// A member "following" one of Loki's picks for a specific upcoming draw —
/// the leaderboard is built from how many of these resolve as wins. No
/// money, no pooled play: this only records that a member said "I'm
/// tracking this one," same spirit as LokiLab's "je joue aussi" copy but
/// without a numbers payload (the pick itself lives in LokiLab's feed).
model FollowedPick {
id String @id @default(cuid())
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
/// Matches LokiLab's lottery id (e.g. "lotto-max", "q4").
lotteryId String
country String
targetDrawDate String
createdAt DateTime @default(now())
@@unique([userId, lotteryId, targetDrawDate])
@@index([userId])
@@index([lotteryId, targetDrawDate])
}