Browse Source

add log table

conradlan 2 years ago
parent
commit
a5b495fa52
2 changed files with 64 additions and 3 deletions
  1. 8 2
      app/api/api_v1/endpoints/line.py
  2. 56 1
      app/main.py

+ 8 - 2
app/api/api_v1/endpoints/line.py

@@ -300,7 +300,10 @@ async def send(
     amount: int,
     db_: Session = Depends(deps.get_db),
     ):
-    to_userid = crud.user.get_by_address(db_, address=to)
+    try:
+        to_userid = crud.user.get_by_address(db_, address=to)
+    except:
+        to_userid = "外部"
     db = dataset.connect(
         'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4'
     )
@@ -331,7 +334,10 @@ async def send(
         fr = "您給"+ to_name +"的NFT(" + title + "), 已發送成功!"
         to_message = from_name +"給您的NFT("+title+"), 已收到!"
         push_text(userid, fr)
-        push_text(to_userid, to_message)
+        try:
+            push_text(to_userid, to_message)
+        except:
+            pass
     else:
         # push訊息
         message = "交易失敗!如果有疑問,請洽網站的服務信箱!"

+ 56 - 1
app/main.py

@@ -1,8 +1,19 @@
-from fastapi import FastAPI
+from sqlalchemy import null
+from starlette.types import Message
+from fastapi import FastAPI, Request, Depends
 from starlette.middleware.cors import CORSMiddleware
+import base64
+import json
+import dataset
+from datetime import datetime
+# from starlette.middleware.authentication import AuthenticationMiddleware
 
+from app.crud.crud_user import user
 from app.api.api_v1.api import api_router
 from app.core.config import settings
+from app.api import deps
+from sqlalchemy.orm import Session
+
 
 app = FastAPI(
     title=settings.PROJECT_NAME, openapi_url=f"{settings.API_V1_STR}/openapi.json")
@@ -12,11 +23,55 @@ app = FastAPI(
 if settings.BACKEND_CORS_ORIGINS:
     app.add_middleware(
         CORSMiddleware,
+        # AuthenticationMiddleware,
         allow_origins=["*"],
         allow_credentials=True,
         allow_methods=["*"],
         allow_headers=["*"],
     )
 
+async def set_body(request: Request, body: bytes):
+    async def receive() -> Message:
+        return {"type": "http.request", "body": body}
+    request._receive = receive
+ 
+async def get_body(request: Request) -> bytes:
+    body = await request.body()
+    await set_body(request, body)
+    return body
+ 
+@app.middleware("http")
+async def app_entry(request: Request, call_next,
+):
+    db = dataset.connect(
+                'mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4'
+                )
+    await set_body(request, await request.body())
+    # body = await get_body(request)
+    # body = str(body).replace("\"","\'")
+    headers = str(request.headers).replace("\"","\'")
+    try:
+        userid = int(json.loads(base64.b64decode(request.headers['authorization'][7:].split('.')[1]).decode('utf-8'))['sub'])
+    except:
+        if( "/api/v1/line/collection/" or "/api/v1/line/receive/" or "/api/v1/line/shop/" in request.url.path):
+            lineid = request.url.path.split("/")[-1]
+            
+            sql = 'SELECT id, userid FROM users where userid =\'' + lineid + '\''
+            try:
+                userid = int(db.query(sql).next()['id'])
+            except:
+                userid = -1
+    db.query('Insert into log (create_time, url_path, headers, userid) VALUE (\'' + str(datetime.now()) + '\' ,\'' + request.url.path + '\' , \"' + headers + '\" , '+ str(userid) + ')')
+    response = await call_next(request)
+    return response
+    # response = await call_next(request)
+
+    
+    # print(request.url.path)
+    # print(request.headers)
+
+
+    # return response
+
 
 app.include_router(api_router, prefix=settings.API_V1_STR)