Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 81 additions & 0 deletions src/__tests__/auth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { describe, test, expect, vi, beforeEach } from "vitest"

// Mock next/cache
vi.mock("next/cache", () => ({
revalidatePath: vi.fn(),
}))

// Mock next/navigation
const mockRedirect = vi.fn()
vi.mock("next/navigation", () => ({
redirect: (url: string) => {
mockRedirect(url)
throw new Error(`NEXT_REDIRECT:${url}`)
},
}))

// Mock Supabase server client
const mockSignInWithPassword = vi.fn()
const mockSignOut = vi.fn()

vi.mock("@/lib/supabase/server", () => ({
createClient: () =>
Promise.resolve({
auth: {
signInWithPassword: mockSignInWithPassword,
signOut: mockSignOut,
},
}),
}))

import { login, logout } from "@/app/login/actions"

describe("login action", () => {
beforeEach(() => {
vi.clearAllMocks()
})

test("returns error when email or password is missing", async () => {
const formData = new FormData()
const result = await login(formData)
expect(result).toEqual({ error: "Email and password are required" })
})

test("returns error on invalid credentials", async () => {
mockSignInWithPassword.mockResolvedValue({
error: { message: "Invalid login credentials" },
})

const formData = new FormData()
formData.set("email", "test@example.com")
formData.set("password", "wrong-password")

const result = await login(formData)
expect(result).toEqual({ error: "Invalid email or password" })
})

test("redirects to / on successful login", async () => {
mockSignInWithPassword.mockResolvedValue({ error: null })

const formData = new FormData()
formData.set("email", "test@example.com")
formData.set("password", "correct-password")

await expect(login(formData)).rejects.toThrow("NEXT_REDIRECT:/")
expect(mockRedirect).toHaveBeenCalledWith("/")
})
})

describe("logout action", () => {
beforeEach(() => {
vi.clearAllMocks()
})

test("signs out and redirects to /login", async () => {
mockSignOut.mockResolvedValue({ error: null })

await expect(logout()).rejects.toThrow("NEXT_REDIRECT:/login")
expect(mockSignOut).toHaveBeenCalled()
expect(mockRedirect).toHaveBeenCalledWith("/login")
})
})
60 changes: 60 additions & 0 deletions src/__tests__/middleware.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { describe, test, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"

// Mock Supabase SSR
const mockGetUser = vi.fn()
vi.mock("@supabase/ssr", () => ({
createServerClient: () => ({
auth: {
getUser: mockGetUser,
},
}),
}))

import { middleware } from "@/middleware"

function createRequest(pathname: string) {
return new NextRequest(new URL(pathname, "http://localhost:3000"))
}

describe("middleware", () => {
beforeEach(() => {
vi.clearAllMocks()
process.env.NEXT_PUBLIC_SUPABASE_URL = "http://localhost:54321"
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = "test-anon-key"
})

test("redirects unauthenticated users from /settings to /login", async () => {
mockGetUser.mockResolvedValue({ data: { user: null } })

const response = await middleware(createRequest("/settings"))
expect(response.status).toBe(307)
expect(new URL(response.headers.get("location")!).pathname).toBe("/login")
})

test("allows unauthenticated users to access /", async () => {
mockGetUser.mockResolvedValue({ data: { user: null } })

const response = await middleware(createRequest("/"))
expect(response.status).toBe(200)
})

test("allows authenticated users to access /settings", async () => {
mockGetUser.mockResolvedValue({
data: { user: { id: "user-1", email: "test@example.com" } },
})

const response = await middleware(createRequest("/settings"))
expect(response.status).toBe(200)
})

test("redirects authenticated users away from /login", async () => {
mockGetUser.mockResolvedValue({
data: { user: { id: "user-1", email: "test@example.com" } },
})

const response = await middleware(createRequest("/login"))
expect(response.status).toBe(307)
expect(new URL(response.headers.get("location")!).pathname).toBe("/")
})
})
16 changes: 10 additions & 6 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
import type { Metadata } from "next";
import "./globals.css";
import type { Metadata } from "next"
import "./globals.css"
import Header from "@/components/Header"

export const metadata: Metadata = {
title: "Site Status",
description: "Uptime monitoring for Roots of Progress",
};
}

export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
children: React.ReactNode
}>) {
return (
<html lang="en">
<body>{children}</body>
<body style={{ backgroundColor: "#FAF8F5" }}>
<Header />
{children}
</body>
</html>
);
)
}
35 changes: 35 additions & 0 deletions src/app/login/actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"use server"

import { revalidatePath } from "next/cache"
import { redirect } from "next/navigation"
import { createClient } from "@/lib/supabase/server"

export async function login(formData: FormData) {
const supabase = await createClient()

const email = formData.get("email") as string
const password = formData.get("password") as string

if (!email || !password) {
return { error: "Email and password are required" }
}

const { error } = await supabase.auth.signInWithPassword({
email,
password,
})

if (error) {
return { error: "Invalid email or password" }
}

revalidatePath("/", "layout")
redirect("/")
}

export async function logout() {
const supabase = await createClient()
await supabase.auth.signOut()
revalidatePath("/", "layout")
redirect("/login")
}
138 changes: 138 additions & 0 deletions src/app/login/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
"use client"

import { useState } from "react"
import { login } from "./actions"
import Link from "next/link"

export default function LoginPage() {
const [error, setError] = useState<string | null>(null)
const [pending, setPending] = useState(false)

async function handleSubmit(formData: FormData) {
setPending(true)
setError(null)
const result = await login(formData)
if (result?.error) {
setError(result.error)
setPending(false)
}
}

return (
<div
className="min-h-screen flex items-center justify-center p-6"
style={{ backgroundColor: "#FAF8F5" }}
>
<div className="w-full max-w-[400px]">
<div className="text-center mb-8">
<div
className="text-2xl font-bold tracking-tight"
style={{ color: "#1A1A1A" }}
>
Roots of Progress
</div>
<div
className="text-sm mt-1"
style={{ color: "#5C5C5C", letterSpacing: "0.02em" }}
>
Site Status
</div>
</div>

<div
className="rounded p-8"
style={{
backgroundColor: "#FFFFFF",
border: "1px solid #E8E4DF",
}}
>
<h1
className="text-xl font-bold mb-6"
style={{ color: "#1A1A1A" }}
>
Log in
</h1>

{error && (
<div
className="text-sm mb-4 p-3 rounded"
style={{
color: "#C4453C",
backgroundColor: "rgba(196, 69, 60, 0.06)",
border: "1px solid rgba(196, 69, 60, 0.15)",
}}
>
{error}
</div>
)}

<form action={handleSubmit}>
<div className="mb-5">
<label
htmlFor="email"
className="block text-sm font-medium mb-1.5"
style={{ color: "#1A1A1A" }}
>
Email
</label>
<input
type="email"
id="email"
name="email"
placeholder="you@example.com"
autoComplete="email"
required
className="w-full px-3 py-2.5 text-[15px] rounded outline-none transition-all"
style={{
color: "#1A1A1A",
backgroundColor: "#FFFFFF",
border: "1px solid #E8E4DF",
}}
/>
</div>

<div className="mb-7">
<label
htmlFor="password"
className="block text-sm font-medium mb-1.5"
style={{ color: "#1A1A1A" }}
>
Password
</label>
<input
type="password"
id="password"
name="password"
autoComplete="current-password"
required
className="w-full px-3 py-2.5 text-[15px] rounded outline-none transition-all"
style={{
color: "#1A1A1A",
backgroundColor: "#FFFFFF",
border: "1px solid #E8E4DF",
}}
/>
</div>

<button
type="submit"
disabled={pending}
className="w-full py-2.5 px-4 text-[15px] font-semibold text-white rounded cursor-pointer transition-colors disabled:opacity-60"
style={{ backgroundColor: pending ? "#5C5C5C" : "#2C2C2C" }}
>
{pending ? "Logging in..." : "Log in"}
</button>
</form>
</div>

<Link
href="/"
className="block text-center mt-6 text-sm no-underline transition-colors"
style={{ color: "#C4453C" }}
>
&larr; Back to status page
</Link>
</div>
</div>
)
}
Loading