Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add user data validation in UserController #7

Merged
merged 1 commit into from
May 26, 2024
Merged
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
43 changes: 43 additions & 0 deletions src/controllers/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,35 @@ const env: any = {
ROOMS_COLLECTION: process.env.ROOMS_COLLECTION as string,
};

const validateUserData = (data: any) => {
const allowedGenders = ["male", "female", "other"];
const birthdate = new Date(data.birthdate);

// Check age is at least 13
const age = getAge(birthdate);
if (age < 13) {
throw new Error("You must be at least 13 years old to use this app");
}

// Check gender is valid
if (!allowedGenders.includes(data.gender)) {
throw new Error("Please select a valid gender");
}
};

const getAge = (birthdate: Date) => {
const today = new Date();
const age = today.getFullYear() - birthdate.getFullYear();
const monthDifference = today.getMonth() - birthdate.getMonth();
if (
monthDifference < 0 ||
(monthDifference === 0 && today.getDate() < birthdate.getDate())
) {
return age - 1;
}
return age;
};

export default class UserController {
async create(req: Request, res: Response) {
try {
Expand Down Expand Up @@ -55,6 +84,20 @@ export default class UserController {
}
}

// Validate user data
try {
validateUserData(data);
} catch (error) {
if (error instanceof Error) {
return res.status(400).json({ ok: false, error: error.message });
} else {
return res.status(400).json({
ok: false,
error: "Unknown error occurred during validation",
});
}
}

// Add default badges
data.badges = ["early-adopter"];

Expand Down
Loading