diff --git a/README.md b/README.md index e4c76e81..423605e9 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,19 @@ Anyone can discover books without signing in. Registered users can also save fav - **Use the application comfortably:** Readr supports keyboard use, responsive layouts, light and dark themes, and accessible feedback. +We provide an example user that anyone can use. This is also helpful for evaluators when reviewing the project. +Just use the "Login as example user" button on the login screen. You can also take a look at the credentials below if you want to log in manually. + +
+ +Example user credentials + +Email: `user@example.com` + +Password: `msQBPuJzExgnWGwT` + +
+ ## Getting started In order to get started with the project, check the READMEs for the respective part of the project: diff --git a/backend/src/auth/index.ts b/backend/src/auth/index.ts index 4050d6f0..c7f4f209 100644 --- a/backend/src/auth/index.ts +++ b/backend/src/auth/index.ts @@ -1,8 +1,24 @@ import { betterAuth } from "better-auth"; +import { + APIError, + createAuthMiddleware, + getSessionFromCtx, +} from "better-auth/api"; import { drizzleAdapter } from "@better-auth/drizzle-adapter/relations-v2"; import { db } from "~/db"; import * as schema from "~/db/schema"; +const EXAMPLE_USER_EMAIL = "user@example.com"; +const EXAMPLE_USER_PASSWORD = "msQBPuJzExgnWGwT"; + +// Endpoints that would let one visitor change the example user for everyone else +const BLOCKED_FOR_EXAMPLE_USER = [ + "/update-user", + "/change-password", + "/change-email", + "/delete-user", +]; + const auth = betterAuth({ database: drizzleAdapter(db, { provider: "pg", @@ -30,7 +46,19 @@ const auth = betterAuth({ clientSecret: process.env.DISCORD_CLIENT_SECRET ?? "", }, }, + hooks: { + before: createAuthMiddleware(async (ctx) => { + if (!BLOCKED_FOR_EXAMPLE_USER.includes(ctx.path)) return; + + const session = await getSessionFromCtx(ctx); + if (session?.user.email === EXAMPLE_USER_EMAIL) { + throw new APIError("FORBIDDEN", { + message: "The example user cannot be changed.", + }); + } + }), + }, trustedOrigins: [process.env.FRONTEND_URL ?? "http://localhost:5173"], }); -export { auth }; +export { auth, EXAMPLE_USER_EMAIL, EXAMPLE_USER_PASSWORD }; diff --git a/backend/src/db/seed/index.ts b/backend/src/db/seed/index.ts index 533a3463..c32d041f 100644 --- a/backend/src/db/seed/index.ts +++ b/backend/src/db/seed/index.ts @@ -12,6 +12,7 @@ import { type InsertBook, } from "~/db/schema/books"; import { emptyToNull } from "~/utils/emptyToNull"; +import { auth, EXAMPLE_USER_EMAIL, EXAMPLE_USER_PASSWORD } from "~/auth"; interface BookRow { bookId: string; @@ -159,6 +160,15 @@ if (booksToInsert.length > 0) { await insertBatch(booksToInsert, genresToInsert); } +// Add example user +await auth.api.signUpEmail({ + body: { + email: EXAMPLE_USER_EMAIL, + password: EXAMPLE_USER_PASSWORD, + name: "Example User", + }, +}); + console.clear(); console.log("Seeding complete!"); process.exit(0); diff --git a/backend/tests/auth.test.ts b/backend/tests/auth.test.ts new file mode 100644 index 00000000..8a9ae413 --- /dev/null +++ b/backend/tests/auth.test.ts @@ -0,0 +1,51 @@ +import { beforeAll, describe, expect, it } from "vitest"; +import { auth, EXAMPLE_USER_EMAIL, EXAMPLE_USER_PASSWORD } from "~/auth"; + +// Signs up a user and returns headers that carry its session cookie. +async function signUp(email: string) { + const { headers } = await auth.api.signUpEmail({ + body: { email, password: EXAMPLE_USER_PASSWORD, name: "Original name" }, + returnHeaders: true, + }); + return new Headers({ cookie: headers.get("set-cookie") ?? "" }); +} + +describe("example user", () => { + let headers: Headers; + + beforeAll(async () => { + headers = await signUp(EXAMPLE_USER_EMAIL); + }); + + it("cannot change name or bio", async () => { + await expect( + auth.api.updateUser({ headers, body: { name: "Changed", bio: "Hi" } }), + ).rejects.toMatchObject({ statusCode: 403 }); + + const session = await auth.api.getSession({ headers }); + expect(session?.user.name).toBe("Original name"); + }); + + it("cannot change password", async () => { + await expect( + auth.api.changePassword({ + headers, + body: { + currentPassword: EXAMPLE_USER_PASSWORD, + newPassword: "new-password", + }, + }), + ).rejects.toMatchObject({ statusCode: 403 }); + }); +}); + +describe("other users", () => { + it("can still change name and bio", async () => { + const headers = await signUp("someone@example.com"); + + await auth.api.updateUser({ headers, body: { name: "Changed" } }); + + const session = await auth.api.getSession({ headers }); + expect(session?.user.name).toBe("Changed"); + }); +}); diff --git a/frontend/app/components/settings/PasswordForm/PasswordForm.tsx b/frontend/app/components/settings/PasswordForm/PasswordForm.tsx index bacf0804..b47a0789 100644 --- a/frontend/app/components/settings/PasswordForm/PasswordForm.tsx +++ b/frontend/app/components/settings/PasswordForm/PasswordForm.tsx @@ -26,7 +26,7 @@ const passwordFormSchema = z.object({ confirmPassword: z.string().min(1, "Confirm your new password."), }); -function PasswordForm() { +function PasswordForm({ disabled = false }: { disabled?: boolean }) { const [serverError, setServerError] = useState(null); const form = useAppForm({ @@ -76,62 +76,69 @@ function PasswordForm() {
{ e.preventDefault(); void form.handleSubmit(); }} > - - - - {(field) => ( - - )} - - - {(field) => ( - - )} - - { - if (value !== fieldApi.form.getFieldValue("newPassword")) { - return { message: "Passwords do not match." }; - } - return undefined; - }, - }} - > - {(field) => ( - - )} - - {serverError} - - - - - Change password - - + {/* Disabling the fieldset disables every input and button in it */} +
+ + + + {(field) => ( + + )} + + + {(field) => ( + + )} + + { + if ( + value !== fieldApi.form.getFieldValue("newPassword") + ) { + return { message: "Passwords do not match." }; + } + return undefined; + }, + }} + > + {(field) => ( + + )} + + {serverError} + + + + + {disabled ? "Unavailable for example user" : "Change password"} + + +
diff --git a/frontend/app/components/settings/ProfileForm/ProfileForm.tsx b/frontend/app/components/settings/ProfileForm/ProfileForm.tsx index 49db23ac..641be5ca 100644 --- a/frontend/app/components/settings/ProfileForm/ProfileForm.tsx +++ b/frontend/app/components/settings/ProfileForm/ProfileForm.tsx @@ -23,7 +23,13 @@ const profileFormSchema = z.object({ .max(MAX_BIO_LENGTH, `Bio must be at most ${MAX_BIO_LENGTH} characters.`), }); -function ProfileForm({ name, bio }: { name: string; bio: string }) { +interface ProfileFormProps { + name: string; + bio: string; + disabled?: boolean; +} + +function ProfileForm({ name, bio, disabled = false }: ProfileFormProps) { const [serverError, setServerError] = useState(null); const form = useAppForm({ @@ -70,36 +76,41 @@ function ProfileForm({ name, bio }: { name: string; bio: string }) {
{ e.preventDefault(); void form.handleSubmit(); }} > - - - - {(field) => ( - - )} - - - {(field) => ( - - )} - - {serverError} - - - - - Save profile - - + {/* Disabling the fieldset disables every input and button in it */} +
+ + + + {(field) => ( + + )} + + + {(field) => ( + + )} + + {serverError} + + + + + {disabled ? "Unavailable for example user" : "Save profile"} + + +
diff --git a/frontend/app/lib/constants.ts b/frontend/app/lib/constants.ts index 34a08620..ffe53184 100644 --- a/frontend/app/lib/constants.ts +++ b/frontend/app/lib/constants.ts @@ -1,6 +1,10 @@ // Make sure this matches the minimum password length set in backend/src/auth/index.ts const MIN_PASSWORD_LENGTH = 8; +// Make sure this matches in backend/src/auth/index.ts +const EXAMPLE_USER_EMAIL = "user@example.com"; +const EXAMPLE_USER_PASSWORD = "msQBPuJzExgnWGwT"; + // Default number of books shown on a page const BOOK_PAGE_LIMIT = 12; @@ -23,6 +27,8 @@ const MAX_REVIEW_COMMENT_LENGTH = 2000; export { MIN_PASSWORD_LENGTH, + EXAMPLE_USER_EMAIL, + EXAMPLE_USER_PASSWORD, BOOK_PAGE_LIMIT, FAVORITE_BOOKS_PAGE_LIMIT, MIN_RATINGS, diff --git a/frontend/app/routes/login.tsx b/frontend/app/routes/login.tsx index bad98647..a35d9f2f 100644 --- a/frontend/app/routes/login.tsx +++ b/frontend/app/routes/login.tsx @@ -23,6 +23,8 @@ import { Input } from "~/components/ui/Input"; import { Spinner } from "~/components/ui/Spinner"; import { toast } from "~/components/ui/Toast"; import { SocialLogins } from "~/components/SocialLogins/SocialLogins"; +import { Separator } from "~/components/ui/Separator"; +import { EXAMPLE_USER_EMAIL, EXAMPLE_USER_PASSWORD } from "~/lib/constants"; const formSchema = z.object({ email: z.email("Enter a valid email address."), @@ -168,9 +170,25 @@ export default function LoginPage() { Sign up

- + Continue without an account + + diff --git a/frontend/app/routes/settings.test.tsx b/frontend/app/routes/settings.test.tsx new file mode 100644 index 00000000..a20070eb --- /dev/null +++ b/frontend/app/routes/settings.test.tsx @@ -0,0 +1,48 @@ +import { describe, expect, it, vi } from "vitest"; +import { screen } from "@testing-library/react"; +import { authClient } from "~/api/auth"; +import SettingsPage from "~/routes/settings"; +import { EXAMPLE_USER_EMAIL } from "~/lib/constants"; +import { renderRoutes } from "~/test/renderRoutes"; +import { loggedIn } from "~/test/session"; + +vi.mock("~/api/auth", () => ({ + authClient: { useSession: vi.fn(() => loggedIn) }, +})); + +const routes = [{ path: "/settings", Component: SettingsPage }]; + +function renderSettings() { + renderRoutes(routes, { initialEntries: ["/settings"] }); +} + +describe("SettingsPage", () => { + it("lets a normal user edit the forms", () => { + renderSettings(); + + expect(screen.getByLabelText("Name")).toBeEnabled(); + expect(screen.getByLabelText("Current password")).toBeEnabled(); + expect(screen.getByRole("button", { name: "Save profile" })).toBeEnabled(); + expect( + screen.getByRole("button", { name: "Change password" }), + ).toBeEnabled(); + }); + + it("disables the forms for the example user", () => { + const exampleUser = structuredClone(loggedIn); + if (exampleUser.data) exampleUser.data.user.email = EXAMPLE_USER_EMAIL; + vi.mocked(authClient.useSession).mockReturnValue(exampleUser); + + renderSettings(); + + expect(screen.getByText(/logged in as the example user/)).toBeVisible(); + expect(screen.getByLabelText("Name")).toBeDisabled(); + expect(screen.getByLabelText("Bio")).toBeDisabled(); + expect(screen.getByLabelText("Current password")).toBeDisabled(); + const buttons = screen.getAllByRole("button", { + name: "Unavailable for example user", + }); + expect(buttons).toHaveLength(2); + for (const button of buttons) expect(button).toBeDisabled(); + }); +}); diff --git a/frontend/app/routes/settings.tsx b/frontend/app/routes/settings.tsx index f72f2964..28ea6171 100644 --- a/frontend/app/routes/settings.tsx +++ b/frontend/app/routes/settings.tsx @@ -5,6 +5,8 @@ import { Skeleton } from "~/components/ui/Skeleton"; import { ProfileForm } from "~/components/settings/ProfileForm/ProfileForm"; import { PasswordForm } from "~/components/settings/PasswordForm/PasswordForm"; import { ArrowLeftIcon } from "lucide-react"; +import { EXAMPLE_USER_EMAIL } from "~/lib/constants"; +import { cn } from "cn"; export function meta() { return [{ title: "Settings | Readr" }]; @@ -25,6 +27,9 @@ export default function SettingsPage() { return ; } + // Everyone shares the example user, so the server blocks changes to it + const isExampleUser = session.user.email === EXAMPLE_USER_EMAIL; + return (
Back to profile -

- Update your profile information and change your password. +

+ {isExampleUser + ? "You are logged in as the example user, which everyone shares, so its profile and password cannot be changed. Please create your own account to change your profile and password." + : "Update your profile information and change your password."}

- - + +
);