mirror of
https://github.com/infiniflow/ragflow.git
synced 2026-06-29 15:31:05 +08:00
fix(profile): enforce profile name validation and input constraints (#15694)
### What problem does this PR solve? The Profile **Name** field currently lacks application-level validation and allows users to save excessively long names and unsupported special characters. While the database enforces a maximum length of 100 characters, neither the frontend nor backend validates nickname format before persistence. This can result in inconsistent user data, poor user experience, and UI layout issues when long names wrap across multiple lines. This PR introduces consistent frontend and backend validation for profile names, enforces length and character constraints, provides clear validation feedback, and prevents invalid values from being saved. Fixes #15693 ### Type of change * [x] Bug Fix (non-breaking change which fixes an issue)
This commit is contained in:
@@ -40,6 +40,7 @@ from api.utils.api_utils import (
|
||||
server_error_response,
|
||||
validate_request,
|
||||
)
|
||||
from api.utils.nickname_validation import validate_nickname
|
||||
from api.utils.crypt import decrypt
|
||||
from rag.utils.redis_conn import REDIS_CONN
|
||||
from api.apps import login_required, current_user, login_user, logout_user
|
||||
@@ -357,6 +358,12 @@ async def setting_user():
|
||||
continue
|
||||
update_dict[k] = request_data[k]
|
||||
|
||||
if "nickname" in update_dict:
|
||||
error_message, error_code = validate_nickname(update_dict["nickname"])
|
||||
if error_message:
|
||||
return get_json_result(data=False, message=error_message, code=error_code)
|
||||
update_dict["nickname"] = update_dict["nickname"].strip()
|
||||
|
||||
try:
|
||||
UserService.update_by_id(current_user.id, update_dict)
|
||||
return get_json_result(data=True)
|
||||
@@ -512,6 +519,11 @@ async def user_add():
|
||||
|
||||
# Construct user info data
|
||||
nickname = req["nickname"]
|
||||
error_message, error_code = validate_nickname(nickname)
|
||||
if error_message:
|
||||
return get_json_result(data=False, message=error_message, code=error_code)
|
||||
nickname = nickname.strip()
|
||||
|
||||
user_dict = {
|
||||
"access_token": get_uuid(),
|
||||
"email": email_address,
|
||||
|
||||
@@ -25,4 +25,5 @@ REQUEST_MAX_WAIT_SEC = 300
|
||||
DATASET_NAME_LIMIT = 128
|
||||
FILE_NAME_LEN_LIMIT = 255
|
||||
MEMORY_NAME_LIMIT = 128
|
||||
NICKNAME_MAX_LENGTH = 100
|
||||
MEMORY_SIZE_LIMIT = 10*1024*1024 # Byte
|
||||
|
||||
51
api/utils/nickname_validation.py
Normal file
51
api/utils/nickname_validation.py
Normal file
@@ -0,0 +1,51 @@
|
||||
#
|
||||
# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import logging
|
||||
import re
|
||||
|
||||
from api.constants import NICKNAME_MAX_LENGTH
|
||||
from common.constants import RetCode
|
||||
|
||||
# Match frontend NICKNAME_PATTERN: letters, numbers, space, and . _ ' -
|
||||
_NICKNAME_PATTERN = re.compile(r"^[\w ._'-]+$", re.UNICODE)
|
||||
|
||||
|
||||
def _reject_nickname(message: str) -> tuple[str, int]:
|
||||
logging.warning("Nickname validation failed: %s", message)
|
||||
return message, RetCode.ARGUMENT_ERROR
|
||||
|
||||
|
||||
def validate_nickname(nickname: str | None) -> tuple[str | None, int | None]:
|
||||
"""
|
||||
Validate a user nickname/display name.
|
||||
|
||||
Returns:
|
||||
A tuple of (error_message, error_code) if validation fails,
|
||||
or (None, None) if validation passes.
|
||||
"""
|
||||
if not isinstance(nickname, (str, type(None))):
|
||||
return _reject_nickname("Nickname must be a string.")
|
||||
if nickname is None:
|
||||
return _reject_nickname("Nickname is required.")
|
||||
|
||||
nickname = nickname.strip()
|
||||
if not nickname:
|
||||
return _reject_nickname("Nickname cannot be empty.")
|
||||
if len(nickname) > NICKNAME_MAX_LENGTH:
|
||||
return _reject_nickname(f"Nickname must be at most {NICKNAME_MAX_LENGTH} characters.")
|
||||
if not _NICKNAME_PATTERN.fullmatch(nickname):
|
||||
return _reject_nickname("Nickname contains invalid characters.")
|
||||
return None, None
|
||||
@@ -708,6 +708,11 @@ def test_logout_setting_profile_matrix_unit(monkeypatch):
|
||||
assert res["code"] == module.RetCode.AUTHENTICATION_ERROR
|
||||
assert "Password error" in res["message"]
|
||||
|
||||
_set_request_json(monkeypatch, module, {"nickname": "carh!@#$%^&*()_+WFAGD"})
|
||||
res = _run(module.setting_user())
|
||||
assert res["code"] == module.RetCode.ARGUMENT_ERROR
|
||||
assert "invalid characters" in res["message"]
|
||||
|
||||
_set_request_json(
|
||||
monkeypatch,
|
||||
module,
|
||||
|
||||
61
test/unit_test/api/utils/test_nickname_validation.py
Normal file
61
test/unit_test/api/utils/test_nickname_validation.py
Normal file
@@ -0,0 +1,61 @@
|
||||
#
|
||||
# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
import pytest
|
||||
|
||||
from api.constants import NICKNAME_MAX_LENGTH
|
||||
from api.utils.nickname_validation import validate_nickname
|
||||
from common.constants import RetCode
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"nickname",
|
||||
[
|
||||
"John Doe",
|
||||
"张三",
|
||||
"O'Brien",
|
||||
"valid-name_123",
|
||||
"a" * NICKNAME_MAX_LENGTH,
|
||||
],
|
||||
)
|
||||
def test_validate_nickname_accepts_valid_values(nickname):
|
||||
message, code = validate_nickname(nickname)
|
||||
assert message is None
|
||||
assert code is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"nickname, expected_message",
|
||||
[
|
||||
(None, "Nickname is required."),
|
||||
("", "Nickname cannot be empty."),
|
||||
(" ", "Nickname cannot be empty."),
|
||||
("carh!@#$%^&*()_+WFAGD", "Nickname contains invalid characters."),
|
||||
("John\tDoe", "Nickname contains invalid characters."),
|
||||
("John\nDoe", "Nickname contains invalid characters."),
|
||||
("a" * (NICKNAME_MAX_LENGTH + 1), f"Nickname must be at most {NICKNAME_MAX_LENGTH} characters."),
|
||||
],
|
||||
)
|
||||
def test_validate_nickname_rejects_invalid_values(nickname, expected_message):
|
||||
message, code = validate_nickname(nickname)
|
||||
assert message == expected_message
|
||||
assert code == RetCode.ARGUMENT_ERROR
|
||||
|
||||
|
||||
def test_validate_nickname_rejects_non_string_input():
|
||||
message, code = validate_nickname(123)
|
||||
assert message == "Nickname must be a string."
|
||||
assert code == RetCode.ARGUMENT_ERROR
|
||||
@@ -1500,6 +1500,9 @@ Example: Virtual Hosted Style`,
|
||||
api: 'API',
|
||||
username: 'Name',
|
||||
usernameMessage: 'Please input your username!',
|
||||
usernameMaxLength: 'Name must be at most {{max}} characters.',
|
||||
usernameInvalidCharacters:
|
||||
"Name can only contain letters, numbers, spaces, and . _ ' -",
|
||||
photo: 'Your photo',
|
||||
photoDescription: 'This will be displayed on your profile.',
|
||||
colorSchema: 'Color schema',
|
||||
|
||||
@@ -1229,6 +1229,9 @@ NER:使用 spaCy NER 和基于规则的关键词提取来抽取实体和关系
|
||||
api: 'API',
|
||||
username: '用户名',
|
||||
usernameMessage: '请输入用户名',
|
||||
usernameMaxLength: '名称最多 {{max}} 个字符。',
|
||||
usernameInvalidCharacters:
|
||||
"名称只能包含字母、数字、空格以及 . _ ' - 字符。",
|
||||
photo: '头像',
|
||||
photoDescription: '这将显示在您的个人资料上。',
|
||||
colorSchema: '主题',
|
||||
|
||||
3
web/src/pages/user-setting/profile/constants.ts
Normal file
3
web/src/pages/user-setting/profile/constants.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export const NICKNAME_MAX_LENGTH = 100;
|
||||
|
||||
export const NICKNAME_PATTERN = /^[\p{L}\p{N} ._'-]+$/u;
|
||||
@@ -23,6 +23,7 @@ import { FC, useEffect, useMemo } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
import { ProfileSettingWrapperCard } from '../components/user-setting-header';
|
||||
import { NICKNAME_MAX_LENGTH, NICKNAME_PATTERN } from './constants';
|
||||
import { EditType, modalTitle, useProfile } from './hooks/use-profile';
|
||||
|
||||
const timezoneOptions = TimezoneList.map(({ name }) => ({
|
||||
@@ -33,8 +34,14 @@ const timezoneOptions = TimezoneList.map(({ name }) => ({
|
||||
const baseSchema = z.object({
|
||||
userName: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, { message: t('setting.usernameMessage') })
|
||||
.trim(),
|
||||
.max(NICKNAME_MAX_LENGTH, {
|
||||
message: t('setting.usernameMaxLength', { max: NICKNAME_MAX_LENGTH }),
|
||||
})
|
||||
.regex(NICKNAME_PATTERN, {
|
||||
message: t('setting.usernameInvalidCharacters'),
|
||||
}),
|
||||
timeZone: z
|
||||
.string()
|
||||
.trim()
|
||||
@@ -150,8 +157,8 @@ const ProfilePage: FC = () => {
|
||||
<label className="w-[190px] text-sm font-medium">
|
||||
{t('username')}
|
||||
</label>
|
||||
<div className="flex-1 flex items-center gap-4 min-w-60">
|
||||
<div className="text-sm text-text-primary border border-border-button flex-1 rounded-md py-1.5 px-2">
|
||||
<div className="flex-1 flex items-center gap-4 min-w-0">
|
||||
<div className="text-sm text-text-primary border border-border-button flex-1 min-w-0 rounded-md py-1.5 px-2 truncate">
|
||||
{profile.userName}
|
||||
</div>
|
||||
|
||||
@@ -262,6 +269,7 @@ const ProfilePage: FC = () => {
|
||||
<FormControl className="w-full">
|
||||
<Input
|
||||
placeholder=""
|
||||
maxLength={NICKNAME_MAX_LENGTH}
|
||||
{...field}
|
||||
className="bg-bg-input border-border-default"
|
||||
/>
|
||||
|
||||
Reference in New Issue
Block a user