feat: username/ww login, tijdzone fix, Vannacht → Eergisternacht"
Some checks failed
Build & Deploy / build (push) Failing after 1m11s

This commit is contained in:
2026-05-15 18:12:47 +02:00
parent cfd9ed4eae
commit a094e67f69
10 changed files with 316 additions and 70 deletions

View File

@@ -6,6 +6,7 @@ services:
container_name: slaapkampioen
restart: unless-stopped
environment:
TZ: Europe/Brussels
DATABASE_URL: postgresql://sleep:${POSTGRES_PASSWORD}@db:5432/sleep
NEXTAUTH_URL: ${NEXTAUTH_URL}
NEXTAUTH_SECRET: ${NEXTAUTH_SECRET}

15
package-lock.json generated
View File

@@ -10,12 +10,14 @@
"dependencies": {
"@next-auth/prisma-adapter": "^1.0.7",
"@prisma/client": "^5.16.0",
"bcryptjs": "^2.4.3",
"next": "^14.2.5",
"next-auth": "^4.24.7",
"react": "^18.3.0",
"react-dom": "^18.3.0"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.6",
"@types/node": "^20.14.0",
"@types/react": "^18.3.0",
"@types/react-dom": "^18.3.0",
@@ -378,6 +380,13 @@
"tslib": "^2.4.0"
}
},
"node_modules/@types/bcryptjs": {
"version": "2.4.6",
"resolved": "https://registry.npmjs.org/@types/bcryptjs/-/bcryptjs-2.4.6.tgz",
"integrity": "sha512-9xlo6R2qDs5uixm0bcIqCeMCE6HiQsIyel9KQySStiyqNl2tnj2mP3DX1Nf56MD6KMenNNlBBsy3LJ7gUEQPXQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/node": {
"version": "20.19.41",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.41.tgz",
@@ -494,6 +503,12 @@
"node": ">=6.0.0"
}
},
"node_modules/bcryptjs": {
"version": "2.4.3",
"resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz",
"integrity": "sha512-V/Hy/X9Vt7f3BbPJEi8BdVFMByHi+jNXrYkW3huaybV/kQ0KJg0Y6PkEMbn+zeT+i+SiKZ/HMqJGIIt4LZDqNQ==",
"license": "MIT"
},
"node_modules/binary-extensions": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",

View File

@@ -17,7 +17,8 @@
"next": "^14.2.5",
"next-auth": "^4.24.7",
"react": "^18.3.0",
"react-dom": "^18.3.0"
"react-dom": "^18.3.0",
"bcryptjs": "^2.4.3"
},
"devDependencies": {
"@types/node": "^20.14.0",
@@ -27,6 +28,7 @@
"postcss": "^8.4.38",
"prisma": "^5.16.0",
"tailwindcss": "^3.4.4",
"typescript": "^5.4.5"
"typescript": "^5.4.5",
"@types/bcryptjs": "^2.4.6"
}
}
}

View File

@@ -0,0 +1,6 @@
-- AlterTable
ALTER TABLE "User" ADD COLUMN "username" TEXT;
ALTER TABLE "User" ADD COLUMN "password" TEXT;
-- CreateIndex
CREATE UNIQUE INDEX "User_username_key" ON "User"("username");

View File

@@ -0,0 +1,34 @@
import { NextRequest, NextResponse } from "next/server";
import bcrypt from "bcryptjs";
import { prisma } from "@/lib/prisma";
export async function POST(req: NextRequest) {
const { username, password } = await req.json();
if (!username || !password) {
return NextResponse.json({ error: "Gebruikersnaam en wachtwoord zijn verplicht." }, { status: 400 });
}
if (username.length < 3) {
return NextResponse.json({ error: "Gebruikersnaam moet minstens 3 tekens zijn." }, { status: 400 });
}
if (password.length < 6) {
return NextResponse.json({ error: "Wachtwoord moet minstens 6 tekens zijn." }, { status: 400 });
}
const existing = await prisma.user.findUnique({ where: { username } });
if (existing) {
return NextResponse.json({ error: "Deze gebruikersnaam is al in gebruik." }, { status: 409 });
}
const hashed = await bcrypt.hash(password, 12);
await prisma.user.create({
data: {
username,
name: username,
password: hashed,
},
});
return NextResponse.json({ success: true });
}

View File

@@ -1,27 +1,112 @@
"use client";
import { signIn } from "next-auth/react";
import { signIn, useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { useState, useEffect } from "react";
import Link from "next/link";
export default function LoginPage() {
const { data: session, status } = useSession();
const router = useRouter();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
// Al ingelogd → meteen door naar klassement
useEffect(() => {
if (status === "authenticated") router.replace("/");
}, [status, router]);
if (status === "loading" || status === "authenticated") {
return (
<div className="flex items-center justify-center min-h-[70vh]">
<div className="text-slate-500">Laden</div>
</div>
);
}
async function handleCredentials() {
setError("");
setLoading(true);
const res = await signIn("credentials", {
username,
password,
redirect: false,
});
setLoading(false);
if (res?.error) {
setError("Gebruikersnaam of wachtwoord klopt niet.");
} else {
router.replace("/");
}
}
return (
<div className="flex flex-col items-center justify-center min-h-[70vh] text-center px-4">
<div className="text-7xl mb-6">💤</div>
<h1 className="text-3xl font-bold text-slate-100 mb-2">SlaapKampioen</h1>
<p className="text-slate-400 mb-8 max-w-sm">
Log elke nacht je slaap en zie wie het meeste slaapt in jouw vriendengroep.
</p>
<button
onClick={() => signIn("discord")}
className="flex items-center gap-3 px-6 py-3 bg-indigo-600 hover:bg-indigo-500 rounded-xl font-semibold text-white transition-colors text-lg"
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="currentColor">
<path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057c.002.022.015.043.033.057a19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028 14.09 14.09 0 0 0 1.226-1.994.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03z" />
</svg>
Inloggen met Discord
</button>
<p className="text-slate-600 text-sm mt-6">
Alleen toegankelijk voor uitgenodigde vrienden.
</p>
<div className="flex flex-col items-center justify-center min-h-[70vh] px-4">
<div className="w-full max-w-sm space-y-6">
{/* Logo */}
<div className="text-center">
<div className="text-6xl mb-3">💤</div>
<h1 className="text-2xl font-bold text-slate-100">SlaapKampioen</h1>
<p className="text-slate-500 text-sm mt-1">Log je slaap, win het klassement.</p>
</div>
{/* Discord */}
<button
onClick={() => signIn("discord", { callbackUrl: "/" })}
className="w-full flex items-center justify-center gap-3 px-4 py-3 bg-indigo-600 hover:bg-indigo-500 rounded-xl font-semibold text-white transition-colors"
>
<svg className="w-5 h-5" viewBox="0 0 24 24" fill="currentColor">
<path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057c.002.022.015.043.033.057a19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028 14.09 14.09 0 0 0 1.226-1.994.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03z" />
</svg>
Inloggen met Discord
</button>
{/* Divider */}
<div className="flex items-center gap-3">
<div className="flex-1 border-t border-slate-700" />
<span className="text-xs text-slate-600">of</span>
<div className="flex-1 border-t border-slate-700" />
</div>
{/* Credentials */}
<div className="space-y-3">
<input
type="text"
placeholder="Gebruikersnaam"
value={username}
onChange={(e) => setUsername(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleCredentials()}
className="w-full bg-slate-800 border border-slate-700 rounded-xl px-4 py-3 text-slate-100 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500"
/>
<input
type="password"
placeholder="Wachtwoord"
value={password}
onChange={(e) => setPassword(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleCredentials()}
className="w-full bg-slate-800 border border-slate-700 rounded-xl px-4 py-3 text-slate-100 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500"
/>
{error && <p className="text-red-400 text-sm text-center"> {error}</p>}
<button
onClick={handleCredentials}
disabled={loading || !username || !password}
className="w-full py-3 bg-slate-700 hover:bg-slate-600 disabled:opacity-40 disabled:cursor-not-allowed rounded-xl font-semibold text-slate-100 transition-colors"
>
{loading ? "Inloggen…" : "Inloggen"}
</button>
</div>
<p className="text-center text-sm text-slate-600">
Nog geen account?{" "}
<Link href="/register" className="text-indigo-400 hover:text-indigo-300 underline underline-offset-2">
Registreer hier
</Link>
</p>
</div>
</div>
);
}
}

91
src/app/register/page.tsx Normal file
View File

@@ -0,0 +1,91 @@
"use client";
import { useState } from "react";
import { signIn } from "next-auth/react";
import { useRouter } from "next/navigation";
import Link from "next/link";
export default function RegisterPage() {
const router = useRouter();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [password2, setPassword2] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
async function handleRegister() {
setError("");
if (password !== password2) {
setError("Wachtwoorden komen niet overeen.");
return;
}
setLoading(true);
const res = await fetch("/api/auth/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
const data = await res.json();
if (!res.ok) {
setError(data.error ?? "Registratie mislukt.");
setLoading(false);
return;
}
// Direct inloggen na registratie
await signIn("credentials", { username, password, redirect: false });
router.replace("/");
}
return (
<div className="flex flex-col items-center justify-center min-h-[70vh] px-4">
<div className="w-full max-w-sm space-y-5">
<div className="text-center">
<div className="text-5xl mb-3">🛌</div>
<h1 className="text-2xl font-bold text-slate-100">Account aanmaken</h1>
<p className="text-slate-500 text-sm mt-1">Kies een gebruikersnaam en wachtwoord.</p>
</div>
<div className="space-y-3">
<input
type="text"
placeholder="Gebruikersnaam (min. 3 tekens)"
value={username}
onChange={(e) => setUsername(e.target.value)}
className="w-full bg-slate-800 border border-slate-700 rounded-xl px-4 py-3 text-slate-100 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500"
/>
<input
type="password"
placeholder="Wachtwoord (min. 6 tekens)"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full bg-slate-800 border border-slate-700 rounded-xl px-4 py-3 text-slate-100 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500"
/>
<input
type="password"
placeholder="Herhaal wachtwoord"
value={password2}
onChange={(e) => setPassword2(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleRegister()}
className="w-full bg-slate-800 border border-slate-700 rounded-xl px-4 py-3 text-slate-100 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500"
/>
{error && <p className="text-red-400 text-sm text-center"> {error}</p>}
<button
onClick={handleRegister}
disabled={loading || !username || !password || !password2}
className="w-full py-3 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-40 disabled:cursor-not-allowed rounded-xl font-semibold text-white transition-colors"
>
{loading ? "Account aanmaken…" : "Account aanmaken"}
</button>
</div>
<p className="text-center text-sm text-slate-600">
Al een account?{" "}
<Link href="/login" className="text-indigo-400 hover:text-indigo-300 underline underline-offset-2">
Inloggen
</Link>
</p>
</div>
</div>
);
}

View File

@@ -4,8 +4,8 @@ import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { calculateTotalFromTimes, formatDuration } from "@/lib/utils";
const YESTERDAY = new Date(Date.now() - 86400000).toISOString().slice(0, 10);
const TODAY = new Date().toISOString().slice(0, 10);
const YESTERDAY = new Date(Date.now() - 86400000).toISOString().slice(0, 10);
const DAY_BEFORE = new Date(Date.now() - 172800000).toISOString().slice(0, 10);
function fromMinutes(total: number) {
return { h: String(Math.floor(total / 60)), m: String(total % 60) };
@@ -149,6 +149,16 @@ export function SleepForm() {
<div className="bg-slate-800/60 rounded-xl p-4 space-y-3">
<p className="text-sm font-semibold text-slate-200">📅 Datum van de nacht</p>
<div className="flex gap-2">
<button
onClick={() => setDate(DAY_BEFORE)}
className={`flex-1 py-2 rounded-lg text-sm font-medium transition-colors ${
date === DAY_BEFORE
? "bg-indigo-600 text-white"
: "bg-slate-700 text-slate-400 hover:text-slate-100"
}`}
>
Eergisternacht
</button>
<button
onClick={() => setDate(YESTERDAY)}
className={`flex-1 py-2 rounded-lg text-sm font-medium transition-colors ${
@@ -159,16 +169,6 @@ export function SleepForm() {
>
Gisternacht
</button>
<button
onClick={() => setDate(TODAY)}
className={`flex-1 py-2 rounded-lg text-sm font-medium transition-colors ${
date === TODAY
? "bg-indigo-600 text-white"
: "bg-slate-700 text-slate-400 hover:text-slate-100"
}`}
>
Vannacht
</button>
</div>
<input
type="date"
@@ -325,4 +325,4 @@ export function SleepForm() {
</button>
</div>
);
}
}

View File

@@ -1,33 +1,47 @@
import { NextAuthOptions } from "next-auth";
import DiscordProvider from "next-auth/providers/discord";
import CredentialsProvider from "next-auth/providers/credentials";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import bcrypt from "bcryptjs";
import { prisma } from "./prisma";
export const authOptions: NextAuthOptions = {
adapter: PrismaAdapter(prisma),
// JWT strategy zodat de middleware de sessie kan verifieren
// zonder een database call te doen bij elk request
session: {
strategy: "jwt",
},
session: { strategy: "jwt" },
providers: [
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID!,
clientSecret: process.env.DISCORD_CLIENT_SECRET!,
}),
CredentialsProvider({
name: "credentials",
credentials: {
username: { label: "Gebruikersnaam", type: "text" },
password: { label: "Wachtwoord", type: "password" },
},
async authorize(credentials) {
if (!credentials?.username || !credentials?.password) return null;
const user = await prisma.user.findUnique({
where: { username: credentials.username },
});
if (!user?.password) return null;
const valid = await bcrypt.compare(credentials.password, user.password);
if (!valid) return null;
return { id: user.id, name: user.name, email: user.email, image: user.image };
},
}),
],
callbacks: {
jwt({ token, user }) {
// user is alleen aanwezig bij eerste login
if (user) {
token.id = user.id;
}
if (user) token.id = user.id;
return token;
},
session({ session, token }) {
if (session.user) {
session.user.id = token.id as string;
}
if (session.user) session.user.id = token.id as string;
return session;
},
},

View File

@@ -4,19 +4,15 @@ export function formatDuration(minutes: number): string {
return `${h}u ${m.toString().padStart(2, "0")}min`;
}
export function minutesToHoursDecimal(minutes: number): number {
return Math.round((minutes / 60) * 10) / 10;
}
export function getSleepQuality(minutes: number): {
label: string;
color: string;
bg: string;
} {
if (minutes < 300) return { label: "Heel kort", color: "text-red-400", bg: "bg-red-500/20 text-red-400" };
if (minutes < 360) return { label: "Kort", color: "text-orange-400", bg: "bg-orange-500/20 text-orange-400" };
if (minutes < 420) return { label: "Matig", color: "text-yellow-400", bg: "bg-yellow-500/20 text-yellow-400" };
if (minutes <= 540) return { label: "Goed", color: "text-green-400", bg: "bg-green-500/20 text-green-400" };
if (minutes < 300) return { label: "Heel kort", color: "text-red-400", bg: "bg-red-500/20 text-red-400" };
if (minutes < 360) return { label: "Kort", color: "text-orange-400", bg: "bg-orange-500/20 text-orange-400" };
if (minutes < 420) return { label: "Matig", color: "text-yellow-400", bg: "bg-yellow-500/20 text-yellow-400" };
if (minutes <= 540) return { label: "Goed", color: "text-green-400", bg: "bg-green-500/20 text-green-400" };
return { label: "Lang", color: "text-blue-400", bg: "bg-blue-500/20 text-blue-400" };
}
@@ -26,30 +22,32 @@ export function getPhaseQuality(
type: "deep" | "light" | "rem" | "awake"
): { label: string; className: string } {
const pct = (phaseMinutes / totalMinutes) * 100;
if (type === "deep") {
if (pct >= 13 && pct <= 25) return { label: "Normaal", className: "bg-green-500/20 text-green-400" };
if (pct > 25) return { label: "Lang", className: "bg-orange-500/20 text-orange-400" };
return { label: "Kort", className: "bg-red-500/20 text-red-400" };
if (pct > 25) return { label: "Lang", className: "bg-orange-500/20 text-orange-400" };
return { label: "Kort", className: "bg-red-500/20 text-red-400" };
}
if (type === "light") {
if (pct >= 45 && pct <= 65) return { label: "Normaal", className: "bg-green-500/20 text-green-400" };
if (pct > 65) return { label: "Lang", className: "bg-orange-500/20 text-orange-400" };
return { label: "Kort", className: "bg-red-500/20 text-red-400" };
if (pct > 65) return { label: "Lang", className: "bg-orange-500/20 text-orange-400" };
return { label: "Kort", className: "bg-red-500/20 text-red-400" };
}
if (type === "rem") {
if (pct >= 15 && pct <= 25) return { label: "Normaal", className: "bg-green-500/20 text-green-400" };
if (pct > 25) return { label: "Lang", className: "bg-orange-500/20 text-orange-400" };
return { label: "Kort", className: "bg-red-500/20 text-red-400" };
if (pct > 25) return { label: "Lang", className: "bg-orange-500/20 text-orange-400" };
return { label: "Kort", className: "bg-red-500/20 text-red-400" };
}
// awake
if (pct <= 5) return { label: "Normaal", className: "bg-green-500/20 text-green-400" };
if (pct <= 10) return { label: "Matig", className: "bg-yellow-500/20 text-yellow-400" };
return { label: "Veel", className: "bg-red-500/20 text-red-400" };
if (pct <= 5) return { label: "Normaal", className: "bg-green-500/20 text-green-400" };
if (pct <= 10) return { label: "Matig", className: "bg-yellow-500/20 text-yellow-400" };
return { label: "Veel", className: "bg-red-500/20 text-red-400" };
}
// Prisma @db.Date geeft UTC middernacht terug → trek datum uit ISO string
// om tijdzone-offset te vermijden
export function formatDate(date: string | Date): string {
return new Date(date).toLocaleDateString("nl-BE", {
const iso = typeof date === "string" ? date : date.toISOString();
const [year, month, day] = iso.slice(0, 10).split("-").map(Number);
return new Date(year, month - 1, day).toLocaleDateString("nl-BE", {
weekday: "short",
day: "numeric",
month: "short",
@@ -62,6 +60,6 @@ export function calculateTotalFromTimes(bedtime: string, wakeTime: string): numb
const [bh, bm] = bedtime.split(":").map(Number);
const [wh, wm] = wakeTime.split(":").map(Number);
let total = wh * 60 + wm - (bh * 60 + bm);
if (total <= 0) total += 24 * 60; // crosses midnight
if (total <= 0) total += 24 * 60; // kruist middernacht
return total;
}
}