first commit
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
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
|
||||
Reference in New Issue
Block a user