#!/bin/bash # Variables GITEA_HOST=$1 # Your Gitea host URL, e.g., https://gitea.your.host USERNAME=$2 # Your Gitea username ACTION=$3 # Action to perform: 'create' or 'list' TOKEN_NAME=$4 # Name of the token to be created (only needed for 'create' action) OTP=$5 # One-Time Password for 2FA (optional) # Prompt for password securely read -sp "Enter your Gitea password: " PASSWORD echo # Function to create a new API token create_token() { # Prepare the JSON data, ensuring correct quoting JSON_DATA='{"name": "'"$TOKEN_NAME"'"}' # Escape special characters in the password ESCAPED_PASSWORD=$(printf '%q' "$PASSWORD") # Construct the curl command, paying careful attention to quoting CURL_CMD="curl -s -X POST -u \"$USERNAME:$ESCAPED_PASSWORD\" \"$GITEA_HOST/api/v1/users/$USERNAME/tokens\" -H 'accept: application/json' -H 'Content-Type: application/json' -d '$JSON_DATA'" # Use eval to execute the CURL_CMD string as a command, ensuring complex strings are correctly handled RESPONSE=$(eval "$CURL_CMD") # Extract and display the token (assuming the response handling remains the same) TOKEN=$(echo "$RESPONSE" | grep -o '"sha1":"[^"]*' | grep -o '[^"]*$') if [ -n "$TOKEN" ]; then echo "Token created successfully: $TOKEN" else echo "Failed to create token. Response was: $RESPONSE" fi } # Function to list existing API tokens list_tokens() { # Headers based on whether 2FA is used if [ -z "$OTP" ]; then HEADERS="" else HEADERS="-H 'X-Gitea-OTP: $OTP'" fi # List API Tokens RESPONSE=$(curl -s $HEADERS -u $USERNAME:$PASSWORD $GITEA_HOST/api/v1/users/$USERNAME/tokens) echo "Existing tokens: $RESPONSE" } # Perform action based on the command line argument case "$ACTION" in "create") create_token ;; "list") list_tokens ;; *) echo "Invalid action: $ACTION. Use 'create' to create a new token or 'list' to list existing tokens." ;; esac