diff --git a/git-hangman-lab/scripts/generate-access-token b/git-hangman-lab/scripts/generate-access-token index c76e1ca..7385717 100755 --- a/git-hangman-lab/scripts/generate-access-token +++ b/git-hangman-lab/scripts/generate-access-token @@ -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"