reposync/get_gitlink_token.py

160 lines
4.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
GitLink OAuth2 Token 获取脚本
"""
import requests
import json
import os
def get_gitlink_oauth_token(username, password):
"""
通过用户名和密码获取GitLink OAuth2 token
Args:
username: GitLink用户名
password: GitLink密码
Returns:
str: 访问令牌
"""
url = "https://gitlink.org.cn/oauth/token"
# OAuth2 客户端信息这些是GitLink的官方客户端ID和密钥
client_id = "cPY5xnUHvNjcG6pon2IizuPzmci7PDjtndbgxjNKJDM"
client_secret = "yb-2WGqGm6RercEJq0o_QM6aZtHzRExhQB5TiAQ-Z1M"
payload = {
"grant_type": "password",
"username": username,
"password": password,
"client_id": client_id,
"client_secret": client_secret
}
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
try:
print(f"正在获取 {username} 的GitLink OAuth2 token...")
response = requests.post(url, data=payload, headers=headers, timeout=30)
print(f"状态码: {response.status_code}")
print(f"响应内容: {response.text}")
if response.status_code == 200:
token_data = response.json()
access_token = token_data.get('access_token')
if access_token:
print(f"✅ 成功获取token: {access_token[:20]}...")
return access_token
else:
print("❌ 响应中没有access_token")
return None
else:
print(f"❌ 获取token失败状态码: {response.status_code}")
return None
except Exception as e:
print(f"❌ 请求失败: {e}")
return None
def test_token_with_api(token):
"""
测试token是否有效
Args:
token: 访问令牌
"""
print(f"\n=== 测试token有效性 ===")
# 测试用户信息API
user_url = "https://www.gitlink.org.cn/api/v1/user"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
try:
response = requests.get(user_url, headers=headers, timeout=10)
print(f"用户信息API状态码: {response.status_code}")
if response.status_code == 200:
user_data = response.json()
print(f"✅ Token有效用户信息: {user_data.get('login', 'Unknown')}")
return True
else:
print(f"❌ Token无效响应: {response.text}")
return False
except Exception as e:
print(f"❌ 测试失败: {e}")
return False
def save_token_to_env(token):
"""
将token保存到env.ini文件
Args:
token: 访问令牌
"""
env_file = "env.ini"
if os.path.exists(env_file):
# 读取现有文件
with open(env_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
# 更新或添加GITLINK_TOKEN
updated = False
for i, line in enumerate(lines):
if line.startswith('export GITLINK_TOKEN='):
lines[i] = f'export GITLINK_TOKEN={token}\n'
updated = True
break
if not updated:
# 在GitLink配置区域添加token
for i, line in enumerate(lines):
if '# GitLink配置' in line:
lines.insert(i + 1, f'export GITLINK_TOKEN={token}\n')
break
# 写回文件
with open(env_file, 'w', encoding='utf-8') as f:
f.writelines(lines)
print(f"✅ Token已保存到 {env_file}")
else:
print(f"{env_file} 文件不存在")
def main():
print("=== GitLink OAuth2 Token 获取工具 ===")
# 从用户输入获取凭据
username = input("请输入GitLink用户名: ").strip()
password = input("请输入GitLink密码: ").strip()
if not username or not password:
print("❌ 用户名和密码不能为空")
return
# 获取token
token = get_gitlink_oauth_token(username, password)
if token:
# 测试token
if test_token_with_api(token):
# 保存到配置文件
save_token_to_env(token)
print(f"\n🎉 成功获取并配置GitLink token!")
print(f"Token: {token[:20]}...")
else:
print("\n❌ Token获取成功但验证失败请检查用户名密码")
else:
print("\n❌ 获取token失败")
if __name__ == "__main__":
main()