Skip to content

Instantly share code, notes, and snippets.

@drewgillson
Created August 20, 2020 00:13
Show Gist options
  • Save drewgillson/2349e772d7833bfafceac1275204aa09 to your computer and use it in GitHub Desktop.
Save drewgillson/2349e772d7833bfafceac1275204aa09 to your computer and use it in GitHub Desktop.
#!/bin/bash
# This script logs into the Looker UI using the specified credentials and generates a new API3 key. It was written on Mac OS X
# and may need to be slightly adapted if running on Linux (possibly just replacing ggrep with grep)
if [ ! -f /usr/local/bin/ggrep ]; then
echo "Install GNU grep by running 'brew install grep'"
exit 1
fi
if [ ! -f /usr/local/bin/jq ]; then
echo "Install jq by running 'brew install jq'"
exit 1
fi
# You need to URL encode the $USER and $PASS variables
export USER="drew.gillson%40looker.com"
export PASS="..."
export SRC_CLIENT_ID="aAbBcCdDeEfFgGhH"
export SRC_CLIENT_SECRET="..."
export SRC_URL="http://your.looker.com"
export SRC_API_URL="$SRC_URL:19999/api/3.1"
export SRC_AUTH_TOKEN=`curl -k -s -X POST -d "client_id=$SRC_CLIENT_ID&client_secret=$SRC_CLIENT_SECRET" "$SRC_API_URL/login" | jq -r ".access_token"`
# The /admin/users/api3_key endpoint is not meant for public use, so we need to pass CSRF headers and pretend to be the Looker frontend
curl -k -s -j -c cookieJar -b cookieJar "$SRC_URL/login/email" > /dev/null
curl -k -s -c cookieJar -b cookieJar -X POST -H 'Content-Type: application/x-www-form-urlencoded' --data "email=$USER&password=$PASS&csrf-token=`ggrep CSRF-TOKEN cookieJar | sed -E 's/^.*CSRF-TOKEN( |\s)*//'`" "$SRC_URL/login" #> /dev/null
export CSRF="`curl -k -s -c cookieJar -b cookieJar $SRC_URL/folders/home | ggrep -o -P '(?<=meta name="csrf-token" content=").*(?=" /><meta content)' | head -n 1`"
# Create the new API3 key by submitting a POST request
curl -k -s -c cookieJar -b cookieJar -X POST "$SRC_URL/admin/users/api3_key/1" -H "X-CSRF-Token: $CSRF" > /dev/null
# Download the page and then parse it to extract the most recent Client ID and Client Secret in the table
curl -k -s -c cookieJar -b cookieJar "$SRC_URL/admin/users/api3_key/1" -H "X-CSRF-Token: $CSRF" > output.html
export CLIENT_ID="`cat output.html | sed 's/<td>/\'$'\n<td>/g' | ggrep -o -P "(<td>)([A-Za-z0-9]*)(</td>)" | cut -c 5-24 | tac | head -n 1`"
export CLIENT_SECRET="`cat output.html | sed 's/<\/lk-hidden-field>/\'$'\n<\/lk-hidden-field>/g' | ggrep -o -P '(?<=lk-hidden-field content\=").*(">)' | cut -c 1-34 | tac | head -n 1 | sed 's/\&#39;//g'`"
echo "Client ID"
echo $CLIENT_ID
echo ""
echo "Client Secret"
echo $CLIENT_SECRET
echo ""
rm -f cookieJar output.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment