Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
29 changes: 28 additions & 1 deletion backend/src/auth/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,23 @@
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";

// 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 +45,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 };
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 } 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: "password",
name: "Example User",
},
});

console.clear();
console.log("Seeding complete!");
process.exit(0);
50 changes: 50 additions & 0 deletions backend/tests/auth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { beforeAll, describe, expect, it } from "vitest";
import { auth, EXAMPLE_USER_EMAIL } from "~/auth";

const PASSWORD = "password";

// 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: 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: 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 EXAMPLE_USER_EMAIL in backend/src/auth/index.ts
const EXAMPLE_USER_EMAIL = "user@example.com";
const EXAMPLE_USER_PASSWORD = "password";

// 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
22 changes: 19 additions & 3 deletions frontend/app/routes/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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."),
Expand Down Expand Up @@ -168,9 +170,23 @@ export default function LoginPage() {
Sign up
</Link>
</p>
<Link to="/" className="text-primary underline dark:text-blue-300">
Continue without an account
</Link>
<Separator />
<Button
variant="secondary"
type="submit"
onClick={(e) => {
e.preventDefault();
form.setFieldValue("email", EXAMPLE_USER_EMAIL);
form.setFieldValue("password", EXAMPLE_USER_PASSWORD);
void form.handleSubmit();
}}
>
Login as example user
</Button>
<p className="text-center text-sm text-muted-foreground">
This will log you in as an example user with email
"user@example.com" and password "password".
</p>
</CardFooter>
</Card>
</main>
Expand Down
Loading