Pārlūkot izejas kodu

user login test

Mia Cheng 1 gadu atpakaļ
vecāks
revīzija
4d6942b1d3
1 mainītis faili ar 10 papildinājumiem un 7 dzēšanām
  1. 10 7
      app/api/users.py

+ 10 - 7
app/api/users.py

@@ -40,13 +40,15 @@ async def query_user(user_id: str):
 
 @users.post("/login")
 async def login(data: OAuth2PasswordRequestForm = Depends()):
-    email = data.email
+    username = data.username
     password = data.password
-
-    user = await query_user(email)
+    password_bytes = password.encode('utf-8')  # 輸入的密碼
+    print(password_bytes)
+    user = await query_user(username)
+    stored_hashed_password_bytes = user.password.encode('utf-8')
     print(user)
     access_token = manager.create_access_token(
-        data={'sub': email}
+        data={'sub': username}
     )
     if not user:
         # you can return any response or error of your choice
@@ -54,8 +56,9 @@ async def login(data: OAuth2PasswordRequestForm = Depends()):
 
     # elif password != user.password:
     #     raise InvalidCredentialsException
+
     else:
-        if bcrypt.checkpw(user.password.encode('utf-8'), password):
+        if bcrypt.checkpw(password_bytes, stored_hashed_password_bytes):
             return {'access_token': access_token}
         else:
             return {"message": "Invalid username or password"}
@@ -70,8 +73,8 @@ async def logout():
 async def add(username: str = Form(default=''), password: str = Form(default=''), email: str = Form(default=''), re_password: str = Form(default='')):
     if username and password and email:
         if password == re_password:
-            hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
-            u = await User.create(username=username, password=hashed_password, email=email)
+            hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
+            u = await User.create(username=username, password=hashed_password, email=email,point='1000')
             if u:
                 # send_email()
                 return {"msg": "已寄送認證信", "code": 200}