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:
co-authored by
Claude Sonnet 5
parent
fc69d4a668
commit
c3a0a7b765
+77
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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>
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
Reference in New Issue
Block a user