Ver Fonte

edit login-2

aaron-1015 há 3 anos atrás
pai
commit
2cb00f62c8
3 ficheiros alterados com 6 adições e 5 exclusões
  1. BIN
      __pycache__/main.cpython-39.pyc
  2. 3 3
      main.py
  3. 3 2
      static/index.js

BIN
__pycache__/main.cpython-39.pyc


+ 3 - 3
main.py

@@ -73,7 +73,7 @@ async def index(request: Request):
 async def login(request: Request):
     return templates.TemplateResponse(name='login.html', context={'request': request})
 
-@app.post("/login", response_class=HTMLResponse)
+@app.post("/login")
 async def login_for_access_token(request: Request, form_data: OAuth2PasswordRequestForm = Depends(), Authorize: AuthJWT = Depends()):
     db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/aaron_testdb?charset=utf8mb4')
     user = authenticate_user(form_data.username, form_data.password)
@@ -95,8 +95,8 @@ async def login_for_access_token(request: Request, form_data: OAuth2PasswordRequ
     refresh_token = Authorize.create_refresh_token(subject=user.username)
     Authorize.set_access_cookies(access_token)
     Authorize.set_refresh_cookies(refresh_token)
-    return templates.TemplateResponse("home.html", {"request": request, "msg": 'Login'})
-    # return {"access_token": access_token, "token_type": "bearer"}
+    # return templates.TemplateResponse("home.html", {"request": request, "msg": 'Login'})
+    return {"access_token": access_token, "token_type": "bearer"}       # 回傳token給前端
 
     
 @app.get('/register', response_class=HTMLResponse)

+ 3 - 2
static/index.js

@@ -10,13 +10,14 @@ $("#btn_login").click(function () {
     xhr.onreadystatechange = function () {
       if (xhr.readyState === 4) {
         console.log(xhr.status);
-        responseOBJ = JSON.parse(xhr.responseText)
+        responseOBJ = JSON.parse(xhr.responseText)          // error
         console.log(responseOBJ.access_token);
         // document.cookie = 'jwt_token='+responseOBJ.jwt_token    // access_token -> jwt_token
-        document.cookie = 'jwt_token='+responseOBJ.access_token;
+        document.cookie = 'jwt_token='+responseOBJ.access_token; 
         console.log('cookie: ');
         console.log(document.cookie);     // test log
         console.log('登入成功');
+        alert('登入成功!!')
         window.location.replace("/home")
       }
     };