refactor(git-hangman-lab): rewrite generate-access-token to use HTTP API instead of gitea CLI

- Use -u username:password basic auth for all API calls
- GET /users/{name}/tokens to find existing token
- DELETE /users/{name}/tokens/{id} to remove existing token
- POST /users/{name}/tokens with {"name": "...", "scopes": ["all"]}
- Extract 'sha1' field from POST response as the token value
- Use ego-mgr get default-username instead of secret-mgr get-username
This commit is contained in:
2026-04-14 23:08:41 +00:00
parent 9bd1452042
commit 0c5e6b8688

View File

@@ -1,18 +1,47 @@
#!/bin/bash
set -euo pipefail
# Get the directory where this script is located
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# Verify git credentials first
"$SCRIPT_DIR/check-git-cred"
username=$(secret-mgr get-username --key git)
output=$("$SCRIPT_DIR/gitea" admin user generate-access-token --username "$username" --token-name "$username" 2>&1) || {
echo "Failed to generate access token: $output"
USERNAME=$(ego-mgr get default-username)
PASSWORD=$(secret-mgr get-secret --key git)
# Check if token already exists
EXISTING=$(curl -s -u "${USERNAME}:${PASSWORD}" \
"https://git.hangman-lab.top/api/v1/users/${USERNAME}/tokens")
EXISTING_ID=$(echo "$EXISTING" | python3 -c "
import sys, json
tokens = json.load(sys.stdin)
name = '$USERNAME'
for t in tokens:
if t.get('name') == name:
print(t.get('id'))
" 2>/dev/null)
if [[ -n "$EXISTING_ID" ]]; then
curl -s -u "${USERNAME}:${PASSWORD}" -X DELETE \
"https://git.hangman-lab.top/api/v1/users/${USERNAME}/tokens/${EXISTING_ID}" > /dev/null || true
fi
# Create new token
RESP=$(curl -s -u "${USERNAME}:${PASSWORD}" -X POST \
-H "Content-Type: application/json" \
-d "{\"name\": \"${USERNAME}\", \"scopes\": [\"all\"]}" \
"https://git.hangman-lab.top/api/v1/users/${USERNAME}/tokens")
TOKEN=$(echo "$RESP" | python3 -c "
import sys, json
d = json.load(sys.stdin)
print(d.get('sha1', ''))
" 2>/dev/null)
if [[ -z "$TOKEN" ]]; then
echo "Failed to generate access token: $RESP"
exit 1
}
token=$(echo "$output" | awk '{print $NF}')
secret-mgr set --key git-access-token --username "$username" --secret "$token"
fi
secret-mgr set --key git-access-token --username "$USERNAME" --secret "$TOKEN"
echo "Access token generated and stored successfully"