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
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

<details>

<summary>Example user credentials</summary>

Email: `user@example.com`

Password: `msQBPuJzExgnWGwT`

</details>

## Getting started

In order to get started with the project, check the READMEs for the respective part of the project:
Expand Down
30 changes: 29 additions & 1 deletion backend/src/auth/index.ts
Original file line number Diff line number Diff line change
@@ -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",
Expand Down Expand Up @@ -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 };
10 changes: 10 additions & 0 deletions backend/src/db/seed/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
51 changes: 51 additions & 0 deletions backend/tests/auth.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
});
109 changes: 58 additions & 51 deletions frontend/app/components/settings/PasswordForm/PasswordForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | null>(null);

const form = useAppForm({
Expand Down Expand Up @@ -76,62 +76,69 @@ function PasswordForm() {
</CardHeader>
<form.AppForm>
<form
className="space-y-6"
noValidate
onSubmit={(e) => {
e.preventDefault();
void form.handleSubmit();
}}
>
<CardContent>
<FieldGroup>
<form.AppField name="currentPassword">
{(field) => (
<field.TextField
label="Current password"
type="password"
autoComplete="current-password"
/>
)}
</form.AppField>
<form.AppField name="newPassword">
{(field) => (
<field.TextField
label="New password"
description={`At least ${MIN_PASSWORD_LENGTH} characters.`}
type="password"
autoComplete="new-password"
/>
)}
</form.AppField>
<form.AppField
name="confirmPassword"
validators={{
onChangeListenTo: ["newPassword"],
onChange: ({ value, fieldApi }) => {
if (value !== fieldApi.form.getFieldValue("newPassword")) {
return { message: "Passwords do not match." };
}
return undefined;
},
}}
>
{(field) => (
<field.TextField
label="Confirm new password"
type="password"
autoComplete="new-password"
/>
)}
</form.AppField>
<FieldError>{serverError}</FieldError>
</FieldGroup>
</CardContent>
<CardFooter>
<form.SubmitButton size="lg" className="w-full">
Change password
</form.SubmitButton>
</CardFooter>
{/* Disabling the fieldset disables every input and button in it */}
<fieldset
disabled={disabled}
className="space-y-6 disabled:cursor-not-allowed"
>
<CardContent>
<FieldGroup>
<form.AppField name="currentPassword">
{(field) => (
<field.TextField
label="Current password"
type="password"
autoComplete="current-password"
/>
)}
</form.AppField>
<form.AppField name="newPassword">
{(field) => (
<field.TextField
label="New password"
description={`At least ${MIN_PASSWORD_LENGTH} characters.`}
type="password"
autoComplete="new-password"
/>
)}
</form.AppField>
<form.AppField
name="confirmPassword"
validators={{
onChangeListenTo: ["newPassword"],
onChange: ({ value, fieldApi }) => {
if (
value !== fieldApi.form.getFieldValue("newPassword")
) {
return { message: "Passwords do not match." };
}
return undefined;
},
}}
>
{(field) => (
<field.TextField
label="Confirm new password"
type="password"
autoComplete="new-password"
/>
)}
</form.AppField>
<FieldError>{serverError}</FieldError>
</FieldGroup>
</CardContent>
<CardFooter>
<form.SubmitButton size="lg" className="w-full">
{disabled ? "Unavailable for example user" : "Change password"}
</form.SubmitButton>
</CardFooter>
</fieldset>
</form>
</form.AppForm>
</Card>
Expand Down
61 changes: 36 additions & 25 deletions frontend/app/components/settings/ProfileForm/ProfileForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | null>(null);

const form = useAppForm({
Expand Down Expand Up @@ -70,36 +76,41 @@ function ProfileForm({ name, bio }: { name: string; bio: string }) {
</CardHeader>
<form.AppForm>
<form
className="space-y-6"
noValidate
onSubmit={(e) => {
e.preventDefault();
void form.handleSubmit();
}}
>
<CardContent>
<FieldGroup>
<form.AppField name="name">
{(field) => (
<field.TextField label="Name" autoComplete="name" />
)}
</form.AppField>
<form.AppField name="bio">
{(field) => (
<field.TextareaField
label="Bio"
description={`${field.state.value.length}/${MAX_BIO_LENGTH} characters.`}
/>
)}
</form.AppField>
<FieldError>{serverError}</FieldError>
</FieldGroup>
</CardContent>
<CardFooter>
<form.SubmitButton size="lg" className="w-full">
Save profile
</form.SubmitButton>
</CardFooter>
{/* Disabling the fieldset disables every input and button in it */}
<fieldset
disabled={disabled}
className="space-y-6 disabled:cursor-not-allowed"
>
<CardContent>
<FieldGroup>
<form.AppField name="name">
{(field) => (
<field.TextField label="Name" autoComplete="name" />
)}
</form.AppField>
<form.AppField name="bio">
{(field) => (
<field.TextareaField
label="Bio"
description={`${field.state.value.length}/${MAX_BIO_LENGTH} characters.`}
/>
)}
</form.AppField>
<FieldError>{serverError}</FieldError>
</FieldGroup>
</CardContent>
<CardFooter>
<form.SubmitButton size="lg" className="w-full">
{disabled ? "Unavailable for example user" : "Save profile"}
</form.SubmitButton>
</CardFooter>
</fieldset>
</form>
</form.AppForm>
</Card>
Expand Down
6 changes: 6 additions & 0 deletions frontend/app/lib/constants.ts
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -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,
Expand Down
Loading