Files
2026-04-07 16:05:05 +08:00

35 lines
1.0 KiB
Python

import bcrypt
from ..models import User
class AuthService:
@staticmethod
def register(username, password, email=None):
if User.query.filter_by(username=username).first():
raise ValueError("用户名已存在")
if email and User.query.filter_by(email=email).first():
raise ValueError("邮箱已被使用")
hashed_password = bcrypt.hashpw(
password.encode("utf-8"), bcrypt.gensalt()
).decode("utf-8")
user = User(username=username, password=hashed_password, email=email)
user.save()
return user
@staticmethod
def login(username, password):
user = User.query.filter_by(username=username).first()
if not user:
raise ValueError("用户名或密码错误")
if not bcrypt.checkpw(password.encode("utf-8"), user.password.encode("utf-8")):
raise ValueError("用户名或密码错误")
if not user.is_active:
raise ValueError("用户已被禁用")
return user