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
6 changes: 6 additions & 0 deletions .credentials.template
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ USERNAME=<realm user username>
EMAIL=<realm user email>
PASSWORD=<realm user password>

# Optional second realm user for multi-client testing (SSE: one user edits,
# the other sees the change live without refreshing).
USERNAME_2=<second realm user username>
EMAIL_2=<second realm user email>
PASSWORD_2=<second realm user password>

# NOTE: if the password ends in punctuation (e.g. "?"), it IS part of the
# password - type it exactly.
# NOTE: the local Keycloak master-realm admin may not be the default
Expand Down
39 changes: 25 additions & 14 deletions AGENTS.md

Large diffs are not rendered by default.

8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,16 @@ Start the backend stack first (`spring-reactive-mongo-template` dev-infra), then

Login via the user menu (top right). Real credentials live in the git-ignored `.credentials` file — copy `.credentials.template` and fill it in on a fresh clone. URLs come from the committed `.env` (all variables documented in `.env.template`; `.env.production` is generated by CI from repo secrets).

Live updates (`/users`) subscribe to `GET /update/user` with a bearer header — the client streams via `fetch` (no EventSource, no ticket, no credential in the URL). Reconnects always resolve a fresh token first (`getAccessToken()`), `token_expired` → refresh + reconnect, `logged_out` → the local session is expired, protected pages lock immediately and the stream never reconnects (see `src/hooks/useSseUsers.ts`).

## Structure

```
src/
├── components/ # shared chrome: nav, side-menu, user-dropdown, cookie-consent,
│ │ # mode-toggle, loading-screen, spinner, error-boundary
│ ├── permissions/ # header widget: permission CRUD in a Sheet via Apollo GraphQL;
│ │ # usePermissionsGraphql.ts is the app's sole permission data layer
│ └── ui/ # generated shadcn (base-nova) — do not hand-edit
├── graphql/ # schema.graphql + generated/ (codegen client preset; git-ignored)
├── lib/ # keycloak.ts, apollo.ts, utils (cn re-export)
Expand All @@ -49,8 +53,8 @@ src/
│ ├── counter/ # RTK slice demo
│ ├── home/ # landing card
│ ├── error/ # 401 / 404 pages
│ └── users/ # RTK Query + GraphQL + SSE CRUD; owns its data-table,
│ # roles combobox and SSE status bar under components/
│ └── users/ # RTK Query + SSE CRUD; owns its data-table,
│ # roles combobox (data from components/permissions) and SSE status bar
├── providers/ # keycloak.tsx (own Keycloak context), theme.tsx (light/dark/system)
└── store/ # store + persisted counter slice + RTK Query api
```
Expand Down
72 changes: 70 additions & 2 deletions src/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,24 @@ import type { ReactNode } from "react"
import { Provider } from "react-redux"
import { render, screen, waitFor } from "@testing-library/react"
import { BrowserRouter } from "react-router-dom"
import { describe, expect, it, vi } from "vite-plus/test"
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"

import App from "@/App"
import { ThemeProvider } from "@/providers/theme"
import { setupStore } from "@/store/store"

// Controllable auth state so the same App tree can be exercised as an
// authenticated and a logged-out visitor.
const kcState = vi.hoisted(() => ({ authenticated: true }))

vi.mock("@/providers/keycloak", () => ({
useKeycloak: () => ({
initialized: true,
authenticated: true,
authenticated: kcState.authenticated,
login: vi.fn(),
logout: vi.fn(),
updateToken: vi.fn().mockResolvedValue(true),
expireSession: vi.fn(),
}),
KeycloakProvider: ({ children }: { children: ReactNode }) => children,
keycloak: { token: "test-token" },
Expand All @@ -33,6 +38,15 @@ function renderApp() {
)
}

beforeEach(() => {
kcState.authenticated = true
window.history.pushState({}, "", "/")
})

afterEach(() => {
window.history.pushState({}, "", "/")
})

describe("App tests", () => {
it("home renders with keycloak authorized", async () => {
renderApp()
Expand All @@ -52,3 +66,57 @@ describe("App tests", () => {
})
})
})

describe("ProtectedRoute access control", () => {
it("denies a logged-out visitor the users page", async () => {
kcState.authenticated = false
window.history.pushState({}, "", "/users")

renderApp()

await waitFor(() => {
expect(
screen.getByRole("heading", { name: "Unauthorized" })
).toBeInTheDocument()
})
expect(window.location.pathname).toBe("/unauthorized")
// No trace of the page: neither the table chrome nor its actions
expect(
screen.queryByRole("button", { name: /add user/i })
).not.toBeInTheDocument()
expect(screen.queryByText("Users Table")).not.toBeInTheDocument()
})

it("denies a logged-out visitor the counter page", async () => {
kcState.authenticated = false
window.history.pushState({}, "", "/counter")

renderApp()

await waitFor(() => {
expect(
screen.getByRole("heading", { name: "Unauthorized" })
).toBeInTheDocument()
})
expect(window.location.pathname).toBe("/unauthorized")
})

it("keeps restricted menu items hidden while logged out", async () => {
kcState.authenticated = false

renderApp()

await waitFor(() => {
expect(screen.getByRole("link", { name: "Home" })).toBeInTheDocument()
})
expect(
screen.queryByRole("link", { name: "Users" })
).not.toBeInTheDocument()
expect(
screen.queryByRole("link", { name: "Counter" })
).not.toBeInTheDocument()
})

// Authenticated /users rendering is covered hermetically in Users.test.tsx;
// mounting it here would reach the real backend.
})
2 changes: 2 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { LoadingScreenMemo } from "@/components/loading-screen"
import { ErrorBoundary } from "@/components/error-boundary"
import { CookieConsent } from "@/components/cookie-consent"
import { ModeToggle } from "@/components/mode-toggle"
import { PermissionsWidget } from "@/components/permissions/permissions-widget"
import { useKeycloak } from "@/providers/keycloak"
import { useTheme } from "@/providers/theme"
import {
Expand Down Expand Up @@ -106,6 +107,7 @@ function App() {
</InputGroup>
</form>
<ModeToggle />
{authenticated ? <PermissionsWidget /> : null}
<UserDropdownMenu />
</header>
<main className="flex flex-1 flex-col gap-6 bg-muted/40 p-4 md:gap-10 md:p-10">
Expand Down
2 changes: 1 addition & 1 deletion src/components/nav-item.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export function NavMenuItem({ item }: NavMenuItemProps) {
const location = useLocation()

return (
<NavigationMenuItem>
<NavigationMenuItem className="mx-1">
<NavigationMenuLink
active={location.pathname === item.route}
render={<Link to={item.route} />}
Expand Down
94 changes: 94 additions & 0 deletions src/components/permissions/permission-form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { useMemo } from "react"
import { type SubmitHandler, useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { useTranslation } from "react-i18next"
import { z } from "zod"

import { Button } from "@/components/ui/button"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"

export interface PermissionFormValues {
name: string
description: string
}

export interface PermissionFormProps {
initialName?: string
initialDescription?: string
onSubmit: (values: PermissionFormValues) => void
onCancel: () => void
}

// Shared by the widget's create and inline-edit modes; mounted fresh per
// mode, so defaultValues are enough — no reset effect needed.
export function PermissionForm({
initialName = "",
initialDescription = "",
onSubmit,
onCancel,
}: PermissionFormProps) {
const { t } = useTranslation("main")

const schema = useMemo(
() =>
z.object({
name: z.string().min(2, t("permissions.name_validation")),
description: z.string(),
}),
[t]
)

const form = useForm<PermissionFormValues>({
resolver: zodResolver(schema),
defaultValues: { name: initialName, description: initialDescription },
})

const handleSubmit: SubmitHandler<PermissionFormValues> = (values) => {
onSubmit(values)
}

return (
<form
className="flex flex-col gap-4"
onSubmit={form.handleSubmit(handleSubmit)}
>
<FieldGroup>
<Field data-invalid={form.formState.errors.name !== undefined}>
<FieldLabel htmlFor="permission-name">
{t("permissions.name")}
</FieldLabel>
<Input
id="permission-name"
placeholder={t("permissions.name_placeholder")}
{...form.register("name")}
/>
<FieldError errors={[form.formState.errors.name]} />
</Field>
<Field data-invalid={form.formState.errors.description !== undefined}>
<FieldLabel htmlFor="permission-description">
{t("permissions.description")}
</FieldLabel>
<Textarea
id="permission-description"
placeholder={t("permissions.description_placeholder")}
{...form.register("description")}
/>
<FieldError errors={[form.formState.errors.description]} />
</Field>
</FieldGroup>
<div className="flex justify-end gap-2">
<Button type="button" variant="ghost" onClick={onCancel}>
{t("permissions.cancel")}
</Button>
<Button type="submit">{t("permissions.submit")}</Button>
</div>
</form>
)
}
Loading
Loading