aaron-1015 пре 3 година
родитељ
комит
f55b2fac64
7 измењених фајлова са 159 додато и 46 уклоњено
  1. BIN
      __pycache__/main.cpython-37.pyc
  2. BIN
      __pycache__/models.cpython-37.pyc
  3. 29 18
      main.py
  4. 2 2
      models.py
  5. 28 26
      static/index.js
  6. 23 0
      templates/register.html
  7. 77 0
      test.ipynb

BIN
__pycache__/main.cpython-37.pyc


BIN
__pycache__/models.cpython-37.pyc


+ 29 - 18
main.py

@@ -15,8 +15,8 @@ from typing import List, Optional
 import os
 
 # time
-import datetime
-from datetime import timedelta
+# import datetime
+from datetime import timedelta, datetime
 
 # db
 import dataset
@@ -62,18 +62,11 @@ templates = Jinja2Templates(directory='templates')
 async def index(request: Request):
     print(request)
     return templates.TemplateResponse(name='index.html', context={'request': request})
-
-
-# @app.get('/make_video', response_class=HTMLResponse)
-# async def index(request: Request):
-#     print(request)
-#     return templates.TemplateResponse(name='make_video.html', context={'request': request})
-
+     
 @app.get('/login', response_class=HTMLResponse)
 async def login(request: Request):
     return templates.TemplateResponse(name='login.html', context={'request': request})
 
-
 @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')
@@ -99,7 +92,25 @@ async def login_for_access_token(request: Request, form_data: OAuth2PasswordRequ
     return {"access_token": access_token, "token_type": "bearer"}
 
     
+@app.get('/register', response_class=HTMLResponse)
+async def login(request: Request):
+    return templates.TemplateResponse(name='register.html', context={'request': request})
 
+@app.post('/register')
+async def register(request: Request, form_data: OAuth2PasswordRequestForm = Depends()):
+    user = models.User(**await request.form())
+    print(form_data.username, form_data.password, user)
+    
+    # 密碼加密
+    user.password = get_password_hash(user.password)
+    
+    # 存入DB
+    db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/aaron_testdb?charset=utf8mb4')
+    user_table = db['users']
+    user_table.insert(dict(user))
+    
+    # 跳轉頁面至登入
+    return templates.TemplateResponse(name='login.html', context={'request': request})
 
 @app.get('/home', response_class=HTMLResponse)
 async def login(request: Request):
@@ -138,7 +149,7 @@ async def login(request: Request):
 # Login funtion part
 def check_user_exists(username):
     db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/aaron_testdb?charset=utf8mb4')
-    if int(next(iter(db.query('SELECT COUNT(*) FROM aaron_testdb.user WHERE username = "'+username+'"')))['COUNT(*)']) > 0:
+    if int(next(iter(db.query('SELECT COUNT(*) FROM aaron_testdb.users WHERE userName = "'+username+'"')))['COUNT(*)']) > 0:
         return True
     else:
         return False
@@ -149,15 +160,15 @@ def get_user(username: str):
     if not check_user_exists(username):  # if user don't exist
         return False
     user_dict = next(
-        iter(db.query('SELECT * FROM aaron_testdb.user where username ="'+username+'"')))
+        iter(db.query('SELECT * FROM aaron_testdb.users where userName ="'+username+'"')))
     user = models.User(**user_dict)
     return user
     
-# def user_register(user):
-#     db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/aaron_testdb?charset=utf8mb4')
-#     table = db['users']
-#     user.password = get_password_hash(user.password)
-#     table.insert(dict(user))
+def user_register(user):
+    db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/aaron_testdb?charset=utf8mb4')
+    table = db['users']
+    user.password = get_password_hash(user.password)
+    table.insert(dict(user))
 
 def get_password_hash(password):
     """ 加密密碼 """
@@ -172,7 +183,7 @@ def authenticate_user(username: str, password: str):
     db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/aaron_testdb?charset=utf8mb4')
     if not check_user_exists(username):  # if user don't exist
         return False
-    user_dict = next(iter(db.query('SELECT * FROM aaron_testdb.user where username ="'+username+'"')))
+    user_dict = next(iter(db.query('SELECT * FROM aaron_testdb.users where userName ="'+username+'"')))
     user = models.User(**user_dict)
     if not verify_password(password, user.password):
         return False

+ 2 - 2
models.py

@@ -4,8 +4,8 @@ import datetime
 
 
 class User(BaseModel):
-    userName: str
-    userPassword: str
+    username: str
+    password: str
     changPwdTime: Optional[datetime.datetime] = None
     isAdmin: Optional[bool] = None
     isEnable: Optional[bool] = True

+ 28 - 26
static/index.js

@@ -1,29 +1,31 @@
 
-$("#btn_login").click(function () {
-    var url = "login";
-    var xhr = new XMLHttpRequest();
-    xhr.open("POST", url);
-    console.log('url:');
-    console.log(url);
-    xhr.setRequestHeader("accept", "application/json");
-    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
-    xhr.onreadystatechange = function () {
-      if (xhr.readyState === 4) {
-        console.log(xhr.status);
-        responseOBJ = JSON.parse(xhr.responseText)
-        console.log(responseOBJ.access_token);
-        // document.cookie = 'jwt_token='+responseOBJ.jwt_token    // access_token -> jwt_token
-        document.cookie = 'jwt_token='+responseOBJ.access_token;
-        console.log('cookie: ');
-        console.log(document.cookie);     // test log
-        alert('登入成功')
-        window.location.replace("/index")
-      }
-    };
-    var data = "grant_type=&username=" + $('#username').val() + "&password="+$('#password').val()+"&scope=&client_id=&client_secret=";
-    console.log("data:");
-    console.log(data);    // test 
-    xhr.send(data);
-  });
+// $("#btn_login").click(function () {
+//     var url = "login";
+//     var xhr = new XMLHttpRequest();
+//     xhr.open("POST", url);
+//     console.log('url:');
+//     console.log(url);
+//     xhr.setRequestHeader("accept", "application/json");
+//     xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
+//     xhr.onreadystatechange = function () {
+//       if (xhr.readyState === 4) {
+//         console.log(xhr.status);
+//         responseOBJ = JSON.parse(xhr.responseText)
+//         console.log(responseOBJ.access_token);
+//         // document.cookie = 'jwt_token='+responseOBJ.jwt_token    // access_token -> jwt_token
+//         document.cookie = 'jwt_token='+responseOBJ.access_token;
+//         console.log('cookie: ');
+//         console.log(document.cookie);     // test log
+//         alert('登入成功')
+//         window.location.replace("/index")
+//       }
+//     };
+//     var data = "grant_type=&username=" + $('#username').val() + "&password="+$('#password').val()+"&scope=&client_id=&client_secret=";
+//     console.log("data:");
+//     console.log(data);    // test 
+//     xhr.send(data);
+//   });
+  
+  
   
   

+ 23 - 0
templates/register.html

@@ -0,0 +1,23 @@
+{% extends "index.html" %}
+{% block title %}註冊{% endblock %}
+{% block head %}
+{{ super() }}
+{% endblock %}
+
+
+{% block body %}
+<div class="tab-pane fade p-lg-3" id="register" role="tabpanel" aria-labelledby="register-tab">
+    <form method="post" action="register">
+        <div class="form-floating mb-3">
+            <input type="text" class="form-control" id="username" name="username" placeholder="請輸入帳號">
+        </div>
+        <div class="form-floating mb-3">
+            <input type="password" class="form-control" id="password" name="password"  placeholder="請輸入密碼">
+        </div>
+        <div class="d-flex justify-content-center">
+            <button type="submit" class="btn btn-primary align-items-center" id="btn_register">註冊</button>
+        </div>
+
+    </form>
+</div>
+{% endblock %}

+ 77 - 0
test.ipynb

@@ -0,0 +1,77 @@
+{
+ "cells": [
+  {
+   "cell_type": "code",
+   "execution_count": 5,
+   "metadata": {
+    "ExecuteTime": {
+     "end_time": "2021-08-03T04:52:27.320427Z",
+     "start_time": "2021-08-03T04:52:27.285576Z"
+    }
+   },
+   "outputs": [
+    {
+     "ename": "ModuleNotFoundError",
+     "evalue": "No module named '__main__.mechancial'; '__main__' is not a package",
+     "output_type": "error",
+     "traceback": [
+      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
+      "\u001b[1;31mModuleNotFoundError\u001b[0m                       Traceback (most recent call last)",
+      "\u001b[1;32m<ipython-input-5-52ec032c6dad>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m     22\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mdataset\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     23\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[0mpasslib\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mcontext\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 24\u001b[1;33m \u001b[1;32mfrom\u001b[0m \u001b[1;33m.\u001b[0m\u001b[0mmechancial\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mmodels\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     25\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     26\u001b[0m \u001b[1;31m# authorize\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
+      "\u001b[1;31mModuleNotFoundError\u001b[0m: No module named '__main__.mechancial'; '__main__' is not a package"
+     ]
+    }
+   ],
+   "source": [
+    "# fastapi\n",
+    "from fastapi import FastAPI, Request, Response, HTTPException, status, Depends\n",
+    "from fastapi import templating\n",
+    "from fastapi.templating import Jinja2Templates\n",
+    "from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse\n",
+    "from fastapi.middleware.cors import CORSMiddleware\n",
+    "\n",
+    "# static file\n",
+    "from fastapi.staticfiles import StaticFiles\n",
+    "\n",
+    "# fastapi view function parameters\n",
+    "from typing import List, Optional\n",
+    "\n",
+    "# path\n",
+    "import os\n",
+    "\n",
+    "# time\n",
+    "import datetime\n",
+    "from datetime import timedelta\n",
+    "\n",
+    "# db\n",
+    "import dataset\n",
+    "from passlib import context\n",
+    "from .mechancial import models\n",
+    "\n",
+    "# authorize\n",
+    "from passlib.context import CryptContext\n",
+    "pwd_context = CryptContext(schemes=[\"bcrypt\"], deprecated=\"auto\")\n",
+    "from jose import JWTError, jwt\n",
+    "from fastapi_jwt_auth import AuthJWT\n",
+    "from fastapi_jwt_auth.exceptions import AuthJWTException\n",
+    "from fastapi.security import OAuth2AuthorizationCodeBearer, OAuth2PasswordRequestForm"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "metadata": {},
+   "outputs": [],
+   "source": []
+  }
+ ],
+ "metadata": {
+  "kernelspec": {
+   "display_name": "Python 3.7.3 64-bit",
+   "language": "python",
+   "name": "python37364bit6893c7013b164b1189a865dcaea9fb2f"
+  }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 4
+}