添加用户名验证

This commit is contained in:
cxykevin 2024-08-31 07:32:43 +08:00
parent 10988194a8
commit 00d25a5f80
2 changed files with 20 additions and 0 deletions

View File

@ -24,3 +24,4 @@ invalid_checkid = "不存在的验证id"
created_successfully = "创建成功" created_successfully = "创建成功"
invalid_token = "token无效" invalid_token = "token无效"
invalid_redirect_url = "无效的重定向URL" invalid_redirect_url = "无效的重定向URL"
invalid_username = "用户名仅为数字字母或 '-' 与 '_' 组成,且长度>3"

View File

@ -107,6 +107,17 @@ def check_passwd(passwd: str):
return 1 return 1
def check_username(passwd: str):
if (len(passwd) < 3):
return 1
pattern = r'[A-Za-z0-9\_\-]{3,16}'
if re.match(pattern, passwd):
return 0
else:
return 1
async def authenticate_user(username: str, password: str): async def authenticate_user(username: str, password: str):
hashed_password = await db.get_user(username) hashed_password = await db.get_user(username)
if not hashed_password: if not hashed_password:
@ -144,6 +155,10 @@ async def check_apikey(tkn: str):
@app.post("/api/login") @app.post("/api/login")
async def login_callback(response: Response, username: str = Form(), password: str = Form()): async def login_callback(response: Response, username: str = Form(), password: str = Form()):
if (check_username(username)):
return {"msg": cfg.lang["invalid_username"]}
if (check_passwd(password)):
return {"msg": cfg.lang["weak_passwd"]}
if (await authenticate_user(username, password)): if (await authenticate_user(username, password)):
tokennow = await create_token(username) tokennow = await create_token(username)
tkn = prep_uuid(uuid.uuid4().hex) tkn = prep_uuid(uuid.uuid4().hex)
@ -162,6 +177,8 @@ regex = re.compile(
async def login_callback(username: str = Form(), password: str = Form(), email: str = Form()): async def login_callback(username: str = Form(), password: str = Form(), email: str = Form()):
if (check_passwd(password)): if (check_passwd(password)):
return {"msg": cfg.lang["weak_passwd"], "code": 1} return {"msg": cfg.lang["weak_passwd"], "code": 1}
if (check_username(username)):
return {"msg": cfg.lang["invalid_username"]}
if (not re.fullmatch(regex, email)): if (not re.fullmatch(regex, email)):
return {"msg": cfg.lang["invalid_email"], "code": 1} return {"msg": cfg.lang["invalid_email"], "code": 1}
if not (await db.check_user(username)): if not (await db.check_user(username)):
@ -215,6 +232,8 @@ async def resetpasswd(uid: str, response: Response):
@app.post("/api/send_resetpasswd") @app.post("/api/send_resetpasswd")
async def resetpasswd(username: str = Form()): async def resetpasswd(username: str = Form()):
if (check_username(username)):
return {"msg": cfg.lang["invalid_username"]}
if (await db.check_user(username)): if (await db.check_user(username)):
email = await db.get_email(username) email = await db.get_email(username)
tkn = prep_uuid(uuid.uuid4().hex) tkn = prep_uuid(uuid.uuid4().hex)