From 6e5b8c4a5df459e31690f7f1c66514e8fea6cc69 Mon Sep 17 00:00:00 2001 From: Benjamin CHARMES Date: Wed, 13 Mar 2024 17:30:06 +0000 Subject: [PATCH] Added validation in save_user --- pydatalab/pydatalab/models/people.py | 14 ++++++++------ pydatalab/pydatalab/routes/v0_1/users.py | 7 +++++++ webapp/src/components/EditAccountSettingsModal.vue | 9 +++------ 3 files changed, 18 insertions(+), 12 deletions(-) diff --git a/pydatalab/pydatalab/models/people.py b/pydatalab/pydatalab/models/people.py index 9afa82c9d..faa56e489 100644 --- a/pydatalab/pydatalab/models/people.py +++ b/pydatalab/pydatalab/models/people.py @@ -4,7 +4,8 @@ import bson import bson.errors -from pydantic import BaseModel, EmailStr, Field, validator +import re +from pydantic import BaseModel, EmailStr, Field, validator, validate_email from pydatalab.models.entries import Entry from pydatalab.models.utils import PyObjectId @@ -94,17 +95,18 @@ def set_default_type(cls, _): @validator("display_name") def validate_display_name_length(cls, v): - """Validate that the display name.""" + """Validate the display name.""" if len(v) > 150: - raise ValueError("Display name must be at most 150 characters long.") + raise ValueError( + "Display name must be at most 150 characters long.") return v @validator("contact_email") def validate_contact_email_format(cls, v): """Validate that the contact email has a valid email format.""" - email_regex = re.compile(r"[^@]+@[^@]+\.[^@]+") - if v is not None: - not email_regex.match(EmailStr(v)) + if not validate_email(v): + raise ValueError( + "Invalid email format for contact email.") return v @staticmethod diff --git a/pydatalab/pydatalab/routes/v0_1/users.py b/pydatalab/pydatalab/routes/v0_1/users.py index 00c56935f..09765d461 100644 --- a/pydatalab/pydatalab/routes/v0_1/users.py +++ b/pydatalab/pydatalab/routes/v0_1/users.py @@ -1,6 +1,8 @@ from bson import ObjectId from flask import Blueprint, jsonify, request from flask_login import current_user +from pydantic import validate_email + from pydatalab.mongo import flask_mongo @@ -12,7 +14,12 @@ def save_user(user_id): request_json = request.get_json() display_name = request_json.get("display_name") + if len(display_name) > 150: + return jsonify(status="error", detail="Name should be less than 150 characters."), 400 + contact_email = request_json.get("contact_email") + if not validate_email(contact_email): + return jsonify(status="error", detail="Invalid email format for contact email."), 400 if not current_user.is_authenticated: return jsonify(status="error"), 401 diff --git a/webapp/src/components/EditAccountSettingsModal.vue b/webapp/src/components/EditAccountSettingsModal.vue index e424fd0fa..06cd70608 100644 --- a/webapp/src/components/EditAccountSettingsModal.vue +++ b/webapp/src/components/EditAccountSettingsModal.vue @@ -1,12 +1,9 @@