118 lines
4.6 KiB
Python
118 lines
4.6 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Ensure physical API runs under systemd with correct SESSION_SECRET; verify login."""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import sys
|
|
import http.cookiejar
|
|
import urllib.request
|
|
|
|
import paramiko
|
|
|
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
|
|
|
REMOTE = r'''
|
|
import os, sys, json, urllib.request, subprocess, time
|
|
os.chdir("/opt/douyinWEB/backend")
|
|
sys.path.insert(0, ".")
|
|
|
|
# 1) Show what settings sees vs environ
|
|
from app.config import settings
|
|
from app.session_auth import _secret, hash_password, ensure_default_admin_credentials, verify_admin
|
|
from app import db
|
|
|
|
print("settings.session_secret_len", len(str(settings.session_secret or "")))
|
|
print("settings.session_secret_pref", str(settings.session_secret or "")[:8])
|
|
print("_secret_len", len(_secret()), "_secret_pref", _secret()[:8])
|
|
print("env DY_SESSION_SECRET", "set" if os.environ.get("DY_SESSION_SECRET") else "MISSING", "len", len(os.environ.get("DY_SESSION_SECRET") or ""))
|
|
|
|
# 2) Force API onto systemd with full env (kill orphans)
|
|
subprocess.run("systemctl kill -s SIGKILL douyinweb-api || true", shell=True)
|
|
subprocess.run("pkill -9 -f 'uvicorn app.main:app' || true", shell=True)
|
|
time.sleep(2)
|
|
subprocess.run("systemctl reset-failed douyinweb-api || true", shell=True)
|
|
subprocess.run("systemctl start douyinweb-api", shell=True)
|
|
|
|
ok=False
|
|
for i in range(60):
|
|
time.sleep(2)
|
|
try:
|
|
with urllib.request.urlopen("http://127.0.0.1:8014/api/health", timeout=4) as r:
|
|
if r.status==200:
|
|
print("API_UP", i); ok=True; break
|
|
except Exception:
|
|
pass
|
|
if i%5==0:
|
|
print("wait", i)
|
|
print("api_ok", ok)
|
|
|
|
# 3) Re-hash with the LIVE process secret by calling through HTTP after ensure in a one-shot with systemd env
|
|
# Run ensure inside a subprocess that loads systemd environment
|
|
script = r"""
|
|
import os,sys
|
|
os.chdir('/opt/douyinWEB/backend'); sys.path.insert(0,'.')
|
|
# pull env from running api process
|
|
import subprocess
|
|
pid=subprocess.getoutput('systemctl show douyinweb-api -p MainPID --value').strip()
|
|
env={}
|
|
if pid.isdigit() and int(pid)>1:
|
|
raw=open(f'/proc/{pid}/environ','rb').read().decode('utf-8','replace').split('\0')
|
|
for x in raw:
|
|
if '=' in x:
|
|
k,v=x.split('=',1); env[k]=v
|
|
for k,v in env.items():
|
|
if k.startswith('DY_') or k in ('TZ',):
|
|
os.environ[k]=v
|
|
from importlib import reload
|
|
import app.config as cfg
|
|
reload(cfg)
|
|
from app.config import settings
|
|
from app.session_auth import ensure_default_admin_credentials, verify_admin, hash_password, _secret
|
|
from app import db
|
|
print('live_secret_len', len(_secret()), 'pref', _secret()[:8])
|
|
print('env_secret_len', len(os.environ.get('DY_SESSION_SECRET') or ''))
|
|
ensure_default_admin_credentials()
|
|
# force sync hash to current secret+password
|
|
exp=hash_password(str(settings.admin_password or ''))
|
|
db.update_settings_map({'admin_username': str(settings.admin_username or 'hackrobot'), 'admin_password_hash': exp})
|
|
print('verify', verify_admin('hackrobot', 'Xiao4669805@'))
|
|
"""
|
|
open('/tmp/_resync_hash.py','w').write(script)
|
|
print(subprocess.getoutput('/opt/douyinWEB/backend/.venv/bin/python /tmp/_resync_hash.py'))
|
|
|
|
# 4) login test
|
|
req=urllib.request.Request('http://127.0.0.1:8014/api/auth/login', data=json.dumps({'username':'hackrobot','password':'Xiao4669805@'}).encode(), headers={'Content-Type':'application/json'}, method='POST')
|
|
with urllib.request.urlopen(req, timeout=10) as r:
|
|
print('local_login', r.status, r.read()[:80], 'set-cookie', (r.headers.get('Set-Cookie') or '')[:90])
|
|
'''
|
|
|
|
c = paramiko.SSHClient()
|
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False)
|
|
sftp = c.open_sftp()
|
|
with sftp.file("/tmp/_auth_resync.py", "w") as f:
|
|
f.write(REMOTE)
|
|
sftp.close()
|
|
_, o, e = c.exec_command(
|
|
"echo '4669805' | sudo -S -p '' /opt/douyinWEB/backend/.venv/bin/python -u /tmp/_auth_resync.py",
|
|
timeout=180,
|
|
)
|
|
print((o.read() + e.read()).decode("utf-8", "replace"))
|
|
c.close()
|
|
|
|
# public login
|
|
cj = http.cookiejar.CookieJar()
|
|
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
|
|
req = urllib.request.Request(
|
|
"https://dy.nomadro.com/api/auth/login",
|
|
data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(),
|
|
headers={"Content-Type": "application/json"},
|
|
method="POST",
|
|
)
|
|
with op.open(req, timeout=25) as r:
|
|
print("public_login", r.status, r.read()[:120])
|
|
print("cookies", [(x.name, x.domain, x.secure) for x in cj])
|
|
req2 = urllib.request.Request("https://dy.nomadro.com/api/auth/status")
|
|
with op.open(req2, timeout=20) as r:
|
|
print("public_status", r.read().decode())
|