Created
August 15, 2024 17:38
-
-
Save Digital39999/26c8d94a4377b1aee08cd853170bfd2f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# How to get auth token: | |
# 1. Go to https://www.npmjs.com/settings/YOUR_USERNAME/tokens | |
# 2. Click on "Create New Token" | |
# 3. Enter the token name and click on "Create Token" -> "Classic Token" | |
# 4. Select "Publish" and click on "Generate Token" | |
# 5. Copy the generated token and paste it in the tokens array below | |
declare -A tokens | |
tokens=( | |
["work"]="YOUR_WORK_AUTH_TOKEN" | |
["personal"]="YOUR_PERSONAL_AUTH_TOKEN" | |
["another_account"]="YOUR_ANOTHER_ACCOUNT_AUTH_TOKEN" | |
) | |
fetch_user() { | |
local token=$1 | |
user_info=$(curl -s -H "Authorization: Bearer $token" https://registry.npmjs.org/-/whoami) | |
if [[ $? -ne 0 || -z "$user_info" ]]; then | |
echo "Failed to fetch user information." | |
exit 1 | |
fi | |
echo $user_info | |
} | |
echo "Available accounts:" | |
index=1 | |
for account in "${!tokens[@]}"; do | |
echo "$index) $account" | |
account_list[$index]=$account | |
((index++)) | |
done | |
echo | |
read -p "Enter the number of the account you want to switch to: " selected_number | |
if [[ -z "${account_list[$selected_number]}" ]]; then | |
echo "Invalid selection!" | |
exit 1 | |
fi | |
selected_account="${account_list[$selected_number]}" | |
selected_token="${tokens[$selected_account]}" | |
user_json=$(fetch_user "$selected_token") | |
user_name=$(echo "$user_json" | jq -r '.username') | |
echo "//registry.npmjs.org/:_authToken=${selected_token}" > ~/.npmrc | |
echo | |
echo "Switched to '$selected_account' account successfully!" | |
echo "Logged in as: ${user_name}" | |
echo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment