Browse Source

history filer done

ming 3 năm trước cách đây
mục cha
commit
a01fbb9293

BIN
api/__pycache__/main.cpython-39.pyc


+ 35 - 31
api/main.py

@@ -89,9 +89,22 @@ async def get_home_page(request: Request, response: Response):
     return templates.TemplateResponse("index.html", {"request": request, "response": response})
 
 @app.get("/make_video", response_class=HTMLResponse)
-async def get_home_page(request: Request, response: Response):
+async def get_home_page(request: Request, response: Response, Authorize: AuthJWT = Depends()):
+    try:
+        Authorize.jwt_required()
+    except:
+        return '請先登入帳號'
+    current_user = Authorize.get_jwt_subject()
     return templates.TemplateResponse("make_video.html", {"request": request, "response": response})
 
+
+@app.get('/user_profile', response_class=HTMLResponse)
+def protected(request: Request, Authorize: AuthJWT = Depends()):
+    Authorize.jwt_required()
+    current_user = Authorize.get_jwt_subject()
+    return current_user
+
+
 # login & register page
 @app.get("/login", response_class=HTMLResponse)
 async def get_login_and_register_page(request: Request):
@@ -151,26 +164,7 @@ def protected(request: Request, Authorize: AuthJWT = Depends()):
     current_user = Authorize.get_jwt_subject()
     return current_user
 
-@app.post('/get_user')
-def get_user_post(token: str = Depends(oauth2_scheme)):
-    db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
-    credentials_exception = HTTPException(
-        status_code=status.HTTP_401_UNAUTHORIZED,
-        detail="Could not validate credentials",
-        headers={"WWW-Authenticate": "Bearer"},
-    )
-    try:
-        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
-        username: str = payload.get("sub")
-        if username is None:
-            raise credentials_exception
-        token_data = models.TokenData(username=username)
-    except JWTError:
-        raise credentials_exception
-    user = get_user(username=token_data.username)
-    if user is None:
-        raise credentials_exception
-    return user
+
 
 
 @app.get('/logout')
@@ -210,8 +204,8 @@ async def create_upload_file(file: UploadFile = File(...)):
         return {'msg':'檔案無法使用'}
     return {"msg": 'www.choozmo.com:8168/'+tmp_img_sub_folder+img_name+'.jpg'}
 
-@app.post("/make_anchor_video_v2")
-async def make_anchor_video_v2(req:models.request):
+@app.post("/make_anchor_video")
+async def make_anchor_video(req:models.request,token: str = Depends(oauth2_scheme)):
     if len(req.image_urls) != len(req.text_content):
         return {'msg':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}
     for idx in range(len(req.image_urls)):
@@ -230,7 +224,8 @@ async def make_anchor_video_v2(req:models.request):
                 im= im.convert("RGB")
         except:
             return {'msg':"無法辨別圖片網址"+imgu}
-    save_history(req,name_hash)
+    user_id = get_user_id(token)
+    save_history(req,name_hash,user_id)
     x = threading.Thread(target=gen_video_queue, args=(name_hash,req.name, req.text_content, req.image_urls,int(req.avatar)))
     x.start()
     return {"msg":"製作影片需要時間,請您耐心等候,成果會傳送至LINE群組中"} 
@@ -259,14 +254,21 @@ async def make_anchor_video_eng(req:models.request_eng):
     return {"msg":"製作影片需要時間,請您耐心等候,成果會傳送至LINE群組中"} 
 
 @app.get("/history_input")
-async def history_input():
+async def history_input(request: Request, Authorize: AuthJWT = Depends()):
+    Authorize.jwt_required()
+    current_user = Authorize.get_jwt_subject()
+
     db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
-    statement = 'SELECT * FROM history_input ORDER BY timestamp DESC LIMIT 50'
+    user_id = first(db.query('SELECT * FROM users where username="' + current_user +'"'))['id']
+    statement = 'SELECT * FROM history_input WHERE user_id="'+str(user_id)+'" ORDER BY timestamp DESC LIMIT 50'
+
     logs = []
     for row in db.query(statement):
         logs.append({'id':row['id'],'name':row['name'],'text_content':row['text_content'].split(','),'link':row['link'],'image_urls':row['image_urls'].split(',')})
     return logs
 
+
+
 @AuthJWT.load_config
 def get_config():
     return models.Settings()
@@ -278,7 +280,7 @@ def authjwt_exception_handler(request: Request, exc: AuthJWTException):
         content={"detail": exc.message}
     )
 
-async def get_current_user(token: str = Depends(oauth2_scheme)):
+def get_user_id(token):
     db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
     credentials_exception = HTTPException(
         status_code=status.HTTP_401_UNAUTHORIZED,
@@ -290,13 +292,14 @@ async def get_current_user(token: str = Depends(oauth2_scheme)):
         username: str = payload.get("sub")
         if username is None:
             raise credentials_exception
-        token_data = TokenData(username=username)
+        token_data = models.TokenData(username=username)
     except JWTError:
         raise credentials_exception
     user = get_user(username=token_data.username)
     if user is None:
         raise credentials_exception
-    return user
+    user_id = first(db.query('SELECT * FROM users where username="' + user.username+'"'))['id']
+    return user_id
 
 def check_user_exists(username):
     db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
@@ -343,7 +346,7 @@ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
     encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
     return encoded_jwt
 
-def save_history(req,name_hash):
+def save_history(req,name_hash,user_id):
     db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
     log_table = db['history_input']
     txt_content_seperate_by_dot = ''
@@ -356,7 +359,8 @@ def save_history(req,name_hash):
     img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
     time_stamp = datetime.fromtimestamp(time.time())
     time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
-    pk = log_table.insert({'name':req.name,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot,'link':'www.choozmo.com:8168/'+video_sub_folder+name_hash+'.mp4','timestamp':time_stamp})
+    pk = log_table.insert({'name':req.name,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot
+    ,'user_id':user_id,'link':'www.choozmo.com:8168/'+video_sub_folder+name_hash+'.mp4','timestamp':time_stamp})
     
 def get_url_type(url):
     req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'})

+ 115 - 114
api/static/script_util.js

@@ -13,12 +13,12 @@ var modalImg = document.querySelector("#avatarmega .modal-img");
 var modalTitle = document.querySelector("#avatarmega .modal-title");
 var avatarSelector = document.getElementById("avatar");
 var card = document.getElementsByClassName('card');
-card = [... card];
+card = [...card];
 avatarSelector.addEventListener('change', avatarChange);
 avatarChange();
 
 function addCardListener() {
-  for(let i = 0;i < card.length; i++){
+  for (let i = 0; i < card.length; i++) {
     card[i].addEventListener('click', openavatarModel);
   }
 }
@@ -29,11 +29,11 @@ function avatarChange() {
   var value = avatarSelector.options[avatarSelector.selectedIndex].text;
   $('.owl-carousel').trigger('to.owl.carousel', avatarSelector.selectedIndex);
   console.log(value);
-  for(let i = 0;i < card.length; i++) {
+  for (let i = 0; i < card.length; i++) {
     card[i].classList.remove('active');
-    if(card[i].dataset.avatar == value) {
+    if (card[i].dataset.avatar == value) {
       card[i].classList.add('active');
-    } 
+    }
   }
 }
 
@@ -61,7 +61,7 @@ function prepareUpload(event) {
     url: 'http://www.choozmo.com:8888/uploadfile',
     dataType: 'json',
     success: function (jsonData) {
-      event.target.previousSibling.value =jsonData.msg;
+      event.target.previousSibling.value = jsonData.msg;
       $(this).prev().val(jsonData.msg);
       event.target.nextSibling.innerHTML = '';
       event.target.nextSibling.textContent = '上傳檔案';
@@ -103,32 +103,28 @@ $(".next").click(function () {
   dataOBJ = { "name": name_title, "text_content": txtARR, "image_urls": imgARR, "avatar": avatar, "client_id": client_id }
   objstr = JSON.stringify(dataOBJ);
   console.log(dataOBJ)
-  //alert('資料已送出! 請耐心等候')
-  $.ajax({
-    url: 'http://www.choozmo.com:8888/make_anchor_video_v2',
-    //url: 'http://www.choozmo.com:8888/qqreq',
-    dataType : 'json', // 預期從server接收的資料型態
-    contentType : 'application/json; charset=utf-8', // 要送到server的資料型態
-    type: 'post',
-    data: objstr,
-    success: function(suc_data) {
+  jwt_token =  get_jwt_token()
+  var xhr = new XMLHttpRequest();
+  xhr.open("POST", "http://127.0.0.1:8000/make_anchor_video");
+  xhr.setRequestHeader("accept", "application/json");
+  xhr.setRequestHeader("Authorization","Bearer "+jwt_token)
+  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
+  xhr.onreadystatechange = function () {
+    if (xhr.readyState === 4) {
       Swal.fire({
         title: "資料已送出",
         icon: 'success',
-        text: `${suc_data.msg}`,
+        text: '資料已傳送,請耐心等候',
         confirmButtonColor: '#3085d6',
-      });  
-      },
-    //data:JSON.stringify({n1:"12",n2:"22"}),
-    error: function (error) {
-      console.error(error)
+      });
     }
-  });
-  
-  });
+  };
+  var data = renderXHR_data(dataOBJ)
+  console.log(data)
+  result = xhr.send(objstr);
+});
 
 $(".gen_avatar").click(function () {
-
   dataOBJ = { "imgurl": $('.img_src').val() }
   objstr = JSON.stringify(dataOBJ);
   console.log(dataOBJ)
@@ -154,7 +150,7 @@ var loaded_data = ''
 function openNav() {
   document.getElementById("mySidenav").style.width = "250px";
   document.querySelector('.loader').style.display = "block";
-  $.get("http://www.choozmo.com:8888/history_input", function (data, status) {
+  $.get("http://127.0.0.1:8000/history_input", function (data, status) {
     console.log(data)
     loaded_data = data
     for (var obj of data) {
@@ -199,13 +195,32 @@ function closeNav() {
 function view() {
   event.stopPropagation();
   console.log(event.target);
-  if(event.target.nodeName === 'I') {
+  if (event.target.nodeName === 'I') {
     return;
   } else {
     window.open(`http://${event.target.dataset.url}`, '_blank');
   }
 }
 
+function renderXHR_data(jsonObj) {
+  XHRstring = ''
+  for (const [key, value] of Object.entries(jsonObj)) {
+    console.log(value)
+    if (typeof (value) == "object") {
+      XHRstring += (key+'=['+value.join(',')+']&')
+    }
+    else {
+      XHRstring += (key + '=' + value + '&')
+    }
+  }
+  XHRstring = XHRstring.substring(0, XHRstring.length - 1);
+  return XHRstring
+}
+
+function get_jwt_token(){
+  jwt_raw = document.cookie.split(';').filter(s=>s.includes('jwt_token'))[0]
+  return jwt_raw.split('=')[1]
+}
 
 function load_data() {
   var title = document.getElementById("title");
@@ -221,7 +236,7 @@ function load_data() {
   $(".linker__box").show();
 
   let historyItem = loaded_data.filter(item => item.id == tid)[0];
-    console.log(historyItem);
+  console.log(historyItem);
   $(".title_new").val(loaded_data.find(item => item.id == tid).name);
 
   let txtlength = historyItem.text_content.length;
@@ -229,34 +244,34 @@ function load_data() {
 
   subtitleInputs.innerHTML = '';
   imgInputs.innerHTML = '';
-  for (let i = 0; i < txtlength ; i++) {
+  for (let i = 0; i < txtlength; i++) {
     var txtinput = document.createElement("input");
-        txtinput.setAttribute('type', 'text');
-        txtinput.setAttribute('name', `t${i+1}`);
-        txtinput.value = historyItem.text_content[i];
-        txtinput.setAttribute('placeholder', `${i+1}`);
-        txtinput.classList.add('txtsrc',`txtsrc${i+1}`)
-        subtitleInputs.appendChild(txtinput);
+    txtinput.setAttribute('type', 'text');
+    txtinput.setAttribute('name', `t${i + 1}`);
+    txtinput.value = historyItem.text_content[i];
+    txtinput.setAttribute('placeholder', `${i + 1}`);
+    txtinput.classList.add('txtsrc', `txtsrc${i + 1}`)
+    subtitleInputs.appendChild(txtinput);
   }
   for (let i = 0; i < imglength; i++) {
     var imginput = document.createElement("input");
-        imginput.setAttribute('type', 'text');
-        imginput.setAttribute('name', `m${i+1}`);
-        imginput.classList.add('imgsrc', `imgsrc${i+1}`);
-        imginput.value = historyItem.image_urls[i];
-        imginput.setAttribute('placeholder', `${i+1}`);
-        imgInputs.appendChild(imginput);
-
-        var imgupload = document.createElement("input");
-        imgupload.setAttribute('id', `img${i+1}`);
-        imgupload.setAttribute('type', `file`);
-        imgupload.classList.add('img_uploader', 'img_up');
-        imgInputs.appendChild(imgupload);
-        var imguploadlabel = document.createElement("label");
-        imguploadlabel.setAttribute('for', `img${i+1}`);
-        imguploadlabel.classList.add('upload-btn');
-        imguploadlabel.textContent = '上傳檔案';
-        imgInputs.appendChild(imguploadlabel);
+    imginput.setAttribute('type', 'text');
+    imginput.setAttribute('name', `m${i + 1}`);
+    imginput.classList.add('imgsrc', `imgsrc${i + 1}`);
+    imginput.value = historyItem.image_urls[i];
+    imginput.setAttribute('placeholder', `${i + 1}`);
+    imgInputs.appendChild(imginput);
+
+    var imgupload = document.createElement("input");
+    imgupload.setAttribute('id', `img${i + 1}`);
+    imgupload.setAttribute('type', `file`);
+    imgupload.classList.add('img_uploader', 'img_up');
+    imgInputs.appendChild(imgupload);
+    var imguploadlabel = document.createElement("label");
+    imguploadlabel.setAttribute('for', `img${i + 1}`);
+    imguploadlabel.classList.add('upload-btn');
+    imguploadlabel.textContent = '上傳檔案';
+    imgInputs.appendChild(imguploadlabel);
   }
 
 }
@@ -266,11 +281,11 @@ var subtitleInputs = document.querySelector(".subtitle-inputs");
 var imgInputs = document.querySelector(".img-inputs");
 let length = 5;
 function initial() {
-    for(let i = 0;i < length; i++) {
-        rendertxtBlock(i+1);
-        renderimgBlock(i+1);
-    }
-    console.log(document.querySelectorAll(".txtsrc").length + 1);
+  for (let i = 0; i < length; i++) {
+    rendertxtBlock(i + 1);
+    renderimgBlock(i + 1);
+  }
+  console.log(document.querySelectorAll(".txtsrc").length + 1);
 }
 
 initial();
@@ -282,51 +297,51 @@ addbtn.addEventListener('click', addtxtBlock);
 addimgbtn.addEventListener('click', addimgBlock);
 
 function addtxtBlock() {
-    let newIdx = document.querySelectorAll(".txtsrc").length + 1;
-    rendertxtBlock(newIdx);
+  let newIdx = document.querySelectorAll(".txtsrc").length + 1;
+  rendertxtBlock(newIdx);
 }
 
 function addimgBlock() {
-    let newimgIdx = document.querySelectorAll(".imgsrc").length + 1;
-    renderimgBlock(newimgIdx);
+  let newimgIdx = document.querySelectorAll(".imgsrc").length + 1;
+  renderimgBlock(newimgIdx);
 }
 
-function rendertxtBlock(i){
-    var txtinput = document.createElement("input");
-        txtinput.setAttribute('type', 'text');
-        txtinput.setAttribute('name', `t${i}`);
-        txtinput.value = "";
-        txtinput.setAttribute('placeholder', `${i}`);
-        txtinput.classList.add('txtsrc',`txtsrc${i}`)
-        subtitleInputs.appendChild(txtinput);
+function rendertxtBlock(i) {
+  var txtinput = document.createElement("input");
+  txtinput.setAttribute('type', 'text');
+  txtinput.setAttribute('name', `t${i}`);
+  txtinput.value = "";
+  txtinput.setAttribute('placeholder', `${i}`);
+  txtinput.classList.add('txtsrc', `txtsrc${i}`)
+  subtitleInputs.appendChild(txtinput);
 }
 
 function renderimgBlock(i) {
-    var imginput = document.createElement("input");
-        imginput.setAttribute('type', 'text');
-        imginput.setAttribute('name', `m${i}`);
-        imginput.classList.add('imgsrc', `imgsrc${i}`);
-        imginput.value = "";
-        imginput.setAttribute('placeholder', `${i}`);
-        imgInputs.appendChild(imginput);
-
-        var imgupload = document.createElement("input");
-        imgupload.setAttribute('id', `img${i}`);
-        imgupload.setAttribute('type', `file`);
-        imgupload.classList.add('img_uploader', 'img_up');
-        imgInputs.appendChild(imgupload);
-        var imguploadlabel = document.createElement("label");
-        imguploadlabel.setAttribute('for', `img${i}`);
-        imguploadlabel.classList.add('upload-btn');
-        imguploadlabel.textContent = '上傳檔案';
-        imgInputs.appendChild(imguploadlabel);
-        $('input[type=file]').on('change', prepareUpload);
+  var imginput = document.createElement("input");
+  imginput.setAttribute('type', 'text');
+  imginput.setAttribute('name', `m${i}`);
+  imginput.classList.add('imgsrc', `imgsrc${i}`);
+  imginput.value = "";
+  imginput.setAttribute('placeholder', `${i}`);
+  imgInputs.appendChild(imginput);
+
+  var imgupload = document.createElement("input");
+  imgupload.setAttribute('id', `img${i}`);
+  imgupload.setAttribute('type', `file`);
+  imgupload.classList.add('img_uploader', 'img_up');
+  imgInputs.appendChild(imgupload);
+  var imguploadlabel = document.createElement("label");
+  imguploadlabel.setAttribute('for', `img${i}`);
+  imguploadlabel.classList.add('upload-btn');
+  imguploadlabel.textContent = '上傳檔案';
+  imgInputs.appendChild(imguploadlabel);
+  $('input[type=file]').on('change', prepareUpload);
 }
 
 
 $('.owl-carousel').owlCarousel({
-  loop:true,
-  margin:10,
+  loop: true,
+  margin: 10,
   nav: false,
   mouseDrag: true,
   touchDrag: true,
@@ -334,29 +349,15 @@ $('.owl-carousel').owlCarousel({
   autoplay: true,
   autoplayTimeout: 8000,
   autoplayHoverPause: false,
-  responsive:{
-      0:{
-          items:1
-      },
-      600:{
-          items:2
-      },
-      1000:{
-          items:4
-      }
+  responsive: {
+    0: {
+      items: 1
+    },
+    600: {
+      items: 2
+    },
+    1000: {
+      items: 4
+    }
   }
 })
-
-$.ajax({
-  url: 'http://127.0.0.1:8000/user_profile2',
-  dataType: 'json', // 預期從server接收的資料型態
-  contentType: 'application/json; charset=utf-8', // 要送到server的資料型態
-  type: 'post',
-  success: function (suc_data) {
-    alert(suc_data.msg)
-  },
-  //data:JSON.stringify({n1:"12",n2:"22"}),
-  error: function (error) {
-    console.error(error)
-  }
-});

+ 4 - 7
api/templates/index.html

@@ -6,17 +6,11 @@
     <meta charset="UTF-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
-    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
-        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
     <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
         integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
         crossorigin="anonymous"></script>
-        <meta charset="UTF-8">
-        <meta name="viewport" content="width=device-width, initial-scale=1.0">
-        <title>AI ANCHOR GO</title>
+        <title>AI spokes girl</title>
         <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
-        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp"
-          crossorigin="anonymous">
         <link rel="stylesheet"
           href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt"
           crossorigin="anonymous">
@@ -50,6 +44,9 @@
                     <li class="nav-item">
                         <a class="nav-link active" aria-current="page" href="/index">Home</a>
                     </li>
+                    <li class="nav-item">
+                        <a class="nav-link active" aria-current="page" href="/make_video">製作影片</a>
+                    </li>
                 </ul>
                 
                 <ul class="navbar-nav mb-2 mb-lg-0">

+ 1 - 1
api/templates/login.html

@@ -48,7 +48,7 @@
                         <label for="password">Password</label>
                     </div>
                     <div class="d-flex justify-content-center">
-                        <button id="go_login" class="btn btn-primary align-items-center">Login</button>
+                        <button id="btn_login" class="btn btn-primary align-items-center">Login</button>
                     </div>
          
 

+ 1 - 8
api/templates/make_video.html

@@ -10,7 +10,7 @@
   <div class="container-fluid">
     <div id="mySidenav" class="sidenav">
       <!-- <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a> -->
-      <h2 class="go_title">AI ANCHOR GO</h2>
+      <h2 class="go_title" href="/index"><a class="nav-link active" aria-current="page" href="/index">AI Spokes Girl</a></h2>
       <ul class="nav-list">
         <li class="nav-list-item pb-1 mb-3" data-bs-toggle="modal" data-bs-target="#howto"><i class="fas fa-book-open me-2"></i>使用說明</li>
         <li class="nav-list-item pb-1" data-bs-toggle="modal" data-bs-target="#history" onclick="openNav()"><i class="fas fa-history me-2"></i>歷史紀錄</li>
@@ -33,7 +33,6 @@
         <fieldset>
           <h3  class="fs-subtitle">選擇人物<img class="ms-1" src="static/img/question.png" alt="" data-bs-toggle="tooltip" data-bs-placement="right" title="將作為影片的講者"></h3>
           <select id="avatar" class='avatar'>
-            <option value="6">Angus</option>
             <option value="7">Peggy</option>
             <option value="8">Stacy</option>
             <option value="10">Nina黑</option>
@@ -43,12 +42,6 @@
             <option value="12">Angela</option>
           </select>
           <div class="owl-carousel owl-theme">
-            <div class="card item" data-avatar="Angus" data-img="angus">
-              <div class="imgfr"><img src="static/img/angus.webp" class="card-img-top" alt="..."></div>
-              <div class="card-body">
-                <h5 class="card-title">Angus</h5>
-              </div>
-            </div>
             <div class="card item" data-avatar="Peggy" data-img="peggy">
               <div class="imgfr"><img src="static/img/peggy.webp" class="card-img-top" alt="..."></div>
               <div class="card-body">

+ 6 - 31
api/templates/script_index.js

@@ -1,48 +1,23 @@
 
-$("#go_login").click(function () {
-
+$("#btn_login").click(function () {
   var url = "http://127.0.0.1:8000/login";
-
   var xhr = new XMLHttpRequest();
   xhr.open("POST", 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);
-      console.log(xhr.responseText);
+      responseOBJ = JSON.parse(xhr.responseText)
+      console.log(responseOBJ.access_token);
+      document.cookie = 'jwt_token='+responseOBJ.access_token
       alert('登入成功')
-      window.location.replace( "/index" )
+      window.location.replace("/index")
     }
   };
-  var data = "grant_type=&username="+$('#username').val()+"&password=qwe&scope=&client_id=&client_secret=";
+  var data = "grant_type=&username=" + $('#username').val() + "&password=qwe&scope=&client_id=&client_secret=";
   xhr.send(data);
-
 });
 
 
-$(".gen_avatar").click(function () {
-  dataOBJ = { "imgurl": $('.img_src').val() }
-  objstr = JSON.stringify(dataOBJ);
-  console.log(dataOBJ)
-  //alert('資料已送出! 請耐心等候')
-  $.ajax({
-    url: 'http://127.0.0.1:8000/refresh',
-    headers: {
-      'x-csrf-jwt': token
-  },
-    dataType: 'json', // 預期從server接收的資料型態
-    contentType: 'application/json; charset=utf-8', // 要送到server的資料型態
-    type: 'post',
-    success: function (suc_data) {
-      alert(suc_data.msg)
-    },
-    //data:JSON.stringify({n1:"12",n2:"22"}),
-    error: function (error) {
-      console.error(error)
-    }
-  });
 
-});