更新代码

This commit is contained in:
2025-09-14 18:05:12 +08:00
parent ba18997410
commit d83f30c07b
4 changed files with 476 additions and 9 deletions

View File

@@ -218,7 +218,28 @@ def create_auth_challenge(
request_body["scopes"] = scopes
return _make_request('POST', url, headers, request_body=request_body)
def perform_auth_challenge(
def get_auth_methods(
account: str,
) -> dict:
"""获取认证方式"""
url = f"{DOMAIN}/api/auth/challenge/{account}/factors"
headers = {
'accept': 'application/json',
}
return _make_request('GET', url, headers)
def send_verification_code(
id: str,
factor_id: str,
) -> dict:
"""发送验证码"""
url = f"{DOMAIN}/api/auth/challenge/{id}/factors/{factor_id}"
headers = {
'accept': 'application/json',
}
return _make_request('POST', url, headers)
def perform_auth_challenge_password(
challenge_id: str,
factor_id: str,
password: str

View File

@@ -1,29 +1,32 @@
import flask
from flask import Flask
import os
from .SNAPI import *
from . import CallServerAPIs
from . import PyWebPageAPI
app = Flask(__name__)
UA = f"SolianForPythonApp/0.0.1(A) ({PyWebPageAPI.GetDeviceInfo()})"
app = flask.Flask(__name__, template_folder='../webfile', static_folder='../webfile/static', static_url_path='/static')
app = Flask(__name__, template_folder='../webfile', static_folder='../webfile/static', static_url_path='/static')
@app.errorhandler(500)
def internal_server_error(error):
# 返回500错误的HTML页面
return flask.render_template("/error/500.html",error=error,static_url_path='/static')
return flask.render_template("/error/500.html", error=error)
@app.errorhandler(404)
def not_found(error):
# 返回404错误的HTML页面
return flask.render_template("/error/404.html",error=error,static_url_path='/static'),404
return flask.render_template("/error/404.html", error=error), 404
@app.errorhandler(403)
def forbidden(error):
# 返回403错误的HTML页面
return flask.render_template("/error/403.html",error=error,static_url_path='/static'),403
return flask.render_template("/error/403.html", error=error), 403
@app.route('/')
def index():
return flask.render_template('index.html',static_url_path='/static')
return flask.render_template('index.html')
@app.route('/Account')
def Account():
@@ -33,14 +36,73 @@ def Account():
def Realm():
return flask.render_template('Realm.html')
@app.route('/login/')
def Login():
return flask.render_template('login.html')
@app.route('/Chat')
def Chat():
return flask.render_template('Chat.html')
@app.route('/api/posts', methods=['GET'])
def GetPosts():
data = CallServerAPIs.ActivityAPIs()
return flask.jsonify({
"title": data[0]["data"]["title"],
"description": data[0]["data"]["description"],
"content": data[0]["data"]["content"],
"username": data[0]["data"]["publisher"]["name"],
"nickname": data[0]["data"]["publisher"]["nick"]
})
@app.route('/api/auth/check-account', methods=['GET'])
def CheckAccount():
account = flask.request.args.get('account')
# 调用SNAPI检查账号是否存在
try:
global resp
resp = AccountServices.create_auth_challenge(platform=1,
device_id=UA,
device_name=UA,
account=account)
return flask.jsonify(resp), 200
except Exception as e:
return flask.jsonify({'error': str(e)}), 400
@app.route('/api/auth/methods', methods=['GET'])
def GetAuthMethods():
account = flask.request.args.get('account')
# 调用SNAPI获取认证方式
methods = AccountServices.get_auth_methods(resp['id'])
# 返回支持的认证方式
return flask.jsonify([
methods
]), 200
@app.route('/api/auth/send-verification', methods=['POST'])
def SendVerification():
data = flask.request.json
account = data.get('account')
method = data.get('method')
# 这里应该调用实际的API发送验证码
AccountServices.send_verification_code(account, method)
return flask.jsonify({'success': True}), 200
@app.route('/api/auth/verify-code', methods=['POST'])
def VerifyCode():
data = flask.request.json
account = data.get('account')
code = data.get('code')
# 这里应该调用实际的API验证验证码
# 模拟验证成功
return flask.jsonify({
'access_token': 'mock_access_token',
'refresh_token': 'mock_refresh_token'
}), 200
def AppStart(host: str, port: int):
"""启动Flask应用"""
app.run(host=host, port=port, debug=True, use_reloader=False)
if __name__ == '__main__':
app.run(host="127.0.0.1", port=5000, debug=True)
app.run(host="127.0.0.1", port=5000, debug=True)

View File

@@ -27,7 +27,10 @@
<h2>账户设置</h2>
<div class="card">
<h3>账户信息</h3>
<p>这里是账户设置界面。</p>
<div class="account-actions">
<button onclick="window.location.href='/login'" style="margin-right: 10px;">登录</button>
<button onclick="window.location.href='/register'" style="margin-right: 10px;">注册</button>
</div>
</div>
</div>
</div>

381
webfile/login.html Normal file
View File

@@ -0,0 +1,381 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录 - Solian</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
body {
background-color: #f5f5f5;
color: #333;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}
.container {
width: 100%;
max-width: 400px;
padding: 40px;
background-color: white;
border-radius: 10px;
box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
position: relative;
}
.back-btn {
position: absolute;
top: 20px;
left: 20px;
color: #4a6baf;
text-decoration: none;
font-size: 14px;
display: flex;
align-items: center;
}
.back-btn:hover {
text-decoration: underline;
}
h1 {
text-align: center;
margin-bottom: 30px;
color: #4a6baf;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 8px;
font-weight: 500;
}
input {
width: 100%;
padding: 12px 15px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 16px;
transition: border-color 0.3s;
}
input:focus {
border-color: #4a6baf;
outline: none;
}
button {
width: 100%;
padding: 12px;
background-color: #4a6baf;
color: white;
border: none;
border-radius: 5px;
font-size: 16px;
font-weight: 500;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #3a5a9f;
}
.links {
margin-top: 20px;
text-align: center;
font-size: 14px;
}
.links a {
color: #4a6baf;
text-decoration: none;
}
.links a:hover {
text-decoration: underline;
}
.divider {
margin: 20px 0;
text-align: center;
position: relative;
}
.divider::before {
content: "";
position: absolute;
top: 50%;
left: 0;
right: 0;
height: 1px;
background-color: #ddd;
z-index: -1;
}
.divider span {
background-color: white;
padding: 0 10px;
color: #777;
}
</style>
</head>
<body>
<div class="container">
<a href="/Account" class="back-btn">← 返回</a>
<h1>欢迎回来</h1>
<div id="step1">
<div class="form-group">
<label for="account">账号</label>
<input type="text" id="account" name="account" required>
</div>
<button id="checkAccountBtn">下一步</button>
</div>
<div id="step2" style="display:none;">
<h3 style="text-align: center; margin-bottom: 20px; color: #4a6baf;">选择登录方式</h3>
<div id="authMethods" style="margin-bottom: 20px;"></div>
<button id="confirmMethodBtn" style="display: none; width: 100%; padding: 12px; background-color: #4a6baf; color: white; border: none; border-radius: 5px; font-size: 16px; font-weight: 500; cursor: pointer; transition: background-color 0.3s;">确认</button>
</div>
<div id="step3" style="display:none;">
<div id="passwordForm" style="display:none;">
<div class="form-group">
<label for="password">密码</label>
<input type="password" id="password" name="password" required>
</div>
<button id="submitPasswordBtn">登录</button>
</div>
<div id="verificationForm" style="display:none;">
<div class="form-group">
<label for="verificationCode">验证码</label>
<input type="text" id="verificationCode" name="verificationCode" required>
</div>
<button id="submitVerificationBtn">验证</button>
</div>
</div>
<div class="links">
<a href="#" id="termsLink">用户协议</a> ·
<a href="#" id="privacyLink">隐私政策</a>
</div>
</div>
<script>
// 第一步:验证账号是否存在
document.getElementById('checkAccountBtn').addEventListener('click', async function() {
const account = document.getElementById('account').value;
try {
const response = await fetch(`/api/auth/check-account?account=${account}`);
if (!response.ok) {
throw new Error('账号不存在');
}
// 获取支持的认证方式
const methodsResponse = await fetch(`/api/auth/methods?account=${account}`);
const methods = await methodsResponse.json();
// 显示认证方式选择
const methodsContainer = document.getElementById('authMethods');
methodsContainer.innerHTML = '';
methods.forEach(method => {
const methodDiv = document.createElement('div');
methodDiv.style.marginBottom = '15px';
methodDiv.style.padding = '15px';
methodDiv.style.borderRadius = '8px';
methodDiv.style.backgroundColor = '#f8f9fa';
methodDiv.style.transition = 'all 0.3s';
methodDiv.style.cursor = 'pointer';
methodDiv.style.border = '1px solid #e0e0e0';
let methodName = '';
switch(method.type) {
case 0: methodName = '密码'; break;
case 1: methodName = '邮箱'; break;
case 2: methodName = '应用内验证'; break;
default: methodName = '未知验证方式';
}
methodDiv.innerHTML = `
<input type="radio" name="authMethod" value="${method.id}" id="method_${method.id}" style="display: none;">
<label for="method_${method.id}" style="display: flex; align-items: center; cursor: pointer;">
<span style="display: inline-block; width: 20px; height: 20px; border: 2px solid #4a6baf; border-radius: 50%; margin-right: 10px; position: relative;"></span>
<span style="font-size: 16px;">${methodName}</span>
</label>
`;
methodDiv.addEventListener('mouseenter', () => {
methodDiv.style.backgroundColor = '#f0f4ff';
methodDiv.style.borderColor = '#4a6baf';
});
methodDiv.addEventListener('mouseleave', () => {
methodDiv.style.backgroundColor = '#f8f9fa';
methodDiv.style.borderColor = '#e0e0e0';
});
methodDiv.addEventListener('click', () => {
document.getElementById(`method_${method.id}`).checked = true;
});
methodsContainer.appendChild(methodDiv);
});
document.getElementById('step1').style.display = 'none';
document.getElementById('step2').style.display = 'block';
document.getElementById('confirmMethodBtn').style.display = 'block';
} catch (error) {
alert(error.message);
}
});
// 第二步:确认认证方式
document.getElementById('confirmMethodBtn').addEventListener('click', async function() {
const account = document.getElementById('account').value;
const selectedMethod = document.querySelector('input[name="authMethod"]:checked').value;
try {
if (selectedMethod === 'password') {
// 直接显示密码输入
document.getElementById('step2').style.display = 'none';
document.getElementById('step3').style.display = 'block';
document.getElementById('passwordForm').style.display = 'block';
} else {
// 发送验证码/邮件
await fetch('/api/auth/send-verification', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
account: account,
method: selectedMethod
})
});
// 显示验证码输入
document.getElementById('step2').style.display = 'none';
document.getElementById('step3').style.display = 'block';
document.getElementById('verificationForm').style.display = 'block';
}
} catch (error) {
alert(error.message);
}
});
// 密码登录
document.getElementById('submitPasswordBtn').addEventListener('click', async function() {
const account = document.getElementById('account').value;
const password = document.getElementById('password').value;
try {
// 1. 创建认证挑战
const challengeResponse = await fetch('/api/auth/challenge', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'accept': 'application/json'
},
body: JSON.stringify({
platform: 1, // Web平台
account: account,
device_id: 'web-browser',
device_name: 'Web浏览器'
})
});
if (!challengeResponse.ok) {
throw new Error('创建认证挑战失败');
}
const challengeData = await challengeResponse.json();
const challengeId = challengeData.challenge_id;
// 2. 执行认证挑战
const authResponse = await fetch(`/api/auth/challenge/${challengeId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'accept': 'application/json'
},
body: JSON.stringify({
factor_id: 'password',
password: password
})
});
if (!authResponse.ok) {
throw new Error('认证失败');
}
// 3. 获取令牌
const authData = await authResponse.json();
localStorage.setItem('auth_token', authData.access_token);
// 登录成功,跳转到首页
window.location.href = '/';
} catch (error) {
alert(error.message);
}
});
// 验证码登录
document.getElementById('submitVerificationBtn').addEventListener('click', async function() {
const account = document.getElementById('account').value;
const code = document.getElementById('verificationCode').value;
try {
const response = await fetch('/api/auth/verify-code', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
account: account,
code: code
})
});
if (!response.ok) {
throw new Error('验证失败');
}
const authData = await response.json();
localStorage.setItem('auth_token', authData.access_token);
// 登录成功,跳转到首页
window.location.href = '/';
} catch (error) {
alert(error.message);
}
});
// 用户协议和隐私政策链接
document.getElementById('termsLink').addEventListener('click', function(e) {
e.preventDefault();
alert('用户协议内容');
});
document.getElementById('privacyLink').addEventListener('click', function(e) {
e.preventDefault();
alert('隐私政策内容');
});
</script>
</body>
</html>