sacn_accout_system/plugin/flarum.py

116 lines
4.3 KiB
Python
Raw Normal View History

2024-08-17 11:25:51 +08:00
from fastapi import FastAPI, Response, Cookie
from datetime import datetime
import aiohttp
import json
2024-08-25 20:51:14 +08:00
from server import db
2024-08-17 11:25:51 +08:00
from typing import Annotated
2024-08-25 20:51:14 +08:00
from server import cfg
2024-08-17 11:25:51 +08:00
2024-08-25 20:51:14 +08:00
FL_SERVER = cfg.config["flarum"]["fl_server"]
FL_APIKEY = cfg.config["flarum"]["fl_apikey"]
async def reload():
global FL_SERVER
global FL_APIKEY
FL_SERVER = cfg.config["flarum"]["fl_server"]
FL_APIKEY = cfg.config["flarum"]["fl_apikey"]
2024-08-17 11:25:51 +08:00
def main(app: FastAPI, ROOT: str, apikeys: dict):
async def check_apikey(tkn: str):
res = apikeys.get(tkn, None)
if (res is None):
return ""
if (res[1] < datetime.now()):
del apikeys[tkn]
return ""
return res[0]
@app.get("/app/flarum/patch.js")
async def patchjson():
return Response("""
setTimeout(function() {
var signup_obj = document.getElementsByClassName(
2024-08-20 21:37:47 +08:00
"item-logIn")[0]
2024-08-17 11:25:51 +08:00
if(signup_obj!=undefined){
signup_obj.style.display = "none";
}
2024-08-20 21:37:47 +08:00
var btn_obj=document.getElementsByClassName("item-logIn")[0]
if(btn_obj != undefined){
btn_obj.innerHTML = "<a href='"""+ROOT+"""/login?redirect_url="+window.location.href+"'>注册/登录</a>"}
2024-08-17 11:25:51 +08:00
}, 500);
2024-08-20 21:37:47 +08:00
2024-08-17 11:25:51 +08:00
setTimeout(function() {
var hashs = window.location.hash
if(hashs!==""){
var exp=/(?<=#access_token\\=).*(?=&token_type)/g
var res = hashs.match(exp)
if(res!=null){
var key = res[0]
var xhr = new XMLHttpRequest()
var csrf = JSON.parse(document.getElementById("flarum-json-payload").innerText)["session"]["csrfToken"]
2024-08-20 21:37:47 +08:00
xhr.open('post','/app/flarum/login?apikey='+key+'&csrftoken='+csrf);
2024-08-17 11:25:51 +08:00
xhr.onreadyStatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText)
2024-08-20 21:37:47 +08:00
window.location.hash = ""
location.reload()
2024-08-17 11:25:51 +08:00
}
}
xhr.send()
}
}
}, 1000);
""", 200, None, media_type="application/javascript")
@app.post("/app/flarum/login")
async def login(apikey: str, csrftoken: str, resp: Response, flarum_session: Annotated[str | None, Cookie()] = None):
username = await check_apikey(apikey)
if (username == ""):
return {"msg": "token无效"}
if (flarum_session is None):
return {"msg": "session无效"}
user_passwd = await db.get_user_passwd(username)
data_obj = {"data":
{"attributes":
{
"username": username,
"email": await db.get_email(username),
"isEmailConfirmed": True,
"password": user_passwd
}
}
}
headers = {
"Authorization": f"Token {FL_APIKEY}",
"Content-Type": "application/json;charset=utf-8"
}
async with aiohttp.ClientSession() as session:
async with session.post(FL_SERVER+"/api/users", headers=headers, data=json.dumps(data_obj)) as response:
if (response.status != 201):
pass
data_obj = {
"identification": username,
"password": user_passwd,
"remember": True
}
headers = {
"Authorization": f"Token {FL_APIKEY}",
"Content-Type": "application/json;charset=utf-8",
"Cookie": f"flarum_session={flarum_session}",
"X-Csrf-Token": csrftoken
}
async with aiohttp.ClientSession() as session:
async with session.post(FL_SERVER+"/login", headers=headers, data=json.dumps(data_obj)) as response:
cookies = response.cookies
flarum_session = cookies.get('flarum_session')
flarum_remember = cookies.get('flarum_remember')
resp.set_cookie("flarum_session", flarum_session)
resp.set_cookie("flarum_remember", flarum_remember)
return {"msg": ""}