Skip to content

Commit 993c219

Browse files
Security for creating accounts
1 parent 2fabff0 commit 993c219

File tree

2 files changed

+40
-7
lines changed

2 files changed

+40
-7
lines changed

app/src/app/signup/actions.ts

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,18 @@
33
import { signIn } from "@/lib/auth"
44
import { prisma } from "@/lib/prisma"
55
import bcrypt from "bcryptjs"
6+
import{ z } from "zod"
7+
8+
// Only allow emails
9+
const ALLOWED_DOMAINS = ["gmail.com", "hevs.ch", "hes-so.ch", "edu.vs.ch"]
10+
11+
// Define Zod schema for validating sign-up form data
12+
const SignupSchema = z.object({
13+
email: z.string().email().refine((val: string) => {
14+
return ALLOWED_DOMAINS.some(domain => val.endsWith(`@${domain}`));
15+
}).withMessage("Email must be from an allowed domain."),
16+
password: z.string().min(8, "8 characters minimum").max(100, "100 characters maximum"),
17+
});
618

719
type ActionResponse = string | null | undefined;
820

@@ -18,31 +30,45 @@ type ActionResponse = string | null | undefined;
1830
*/
1931
export async function signUpAction(prevState: ActionResponse, formData: FormData): Promise<ActionResponse> {
2032
try {
21-
const email = formData.get("email") as string
22-
const password = formData.get("password") as string
33+
34+
// Validate form data using Zod schema
35+
const validatedFields = SignupSchema.safeParse(
36+
Object.fromEntries(formData.entries())
37+
);
38+
39+
// If validation fails, return the first error message
40+
if (!validatedFields.success) {
41+
42+
return validatedFields.error.issues[0].message;
43+
}
44+
45+
// Extract validated email and password
46+
const { email, password } = validatedFields.data;
2347

2448
const existingUser = await prisma.user.findUnique({
2549
where: { email }
26-
})
50+
});
2751

52+
// Verify if the email is already registered
2853
if (existingUser) {
29-
return "User already exists."
54+
return "User already registered.";
3055
}
3156

32-
const hashedPassword = await bcrypt.hash(password, 10)
57+
const hashedPassword = await bcrypt.hash(password, 10);
3358

3459
await prisma.user.create({
3560
data: {
3661
email,
3762
password: hashedPassword,
3863
},
39-
})
64+
});
65+
4066

4167
await signIn("credentials", {
4268
email,
4369
password,
4470
redirectTo: "/dashboard"
45-
})
71+
});
4672

4773
} catch (error) {
4874
if (error instanceof Error && error.message.includes("NEXT_REDIRECT")) {

docker-compose-dev.yml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,13 @@ services:
5252
bun x prisma db push &&
5353
bun dev
5454
"
55+
deploy:
56+
resources:
57+
limits:
58+
cpus: '1.0' # Limit to 1 CPU core
59+
memory: 1G # If request > 1Go, the container will be killed
60+
reservations:
61+
memory: 512M
5562

5663
test:
5764
image: cypress/included:13.15.0

0 commit comments

Comments
 (0)