Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #filepath to store credentials
- my_creds=~/oauth_cache.txt
- client_id=''
- client_secret=''
- redirectURI=''
- if [ -s $my_creds ]; then
- # if we already have a token stored, use it
- . $my_creds
- time_now=`date +%s`
- else
- scope='https://www.googleapis.com/auth/analytics'
- # Form the request URL
- # http://goo.gl/U0uKEb
- auth_url="https://accounts.google.com/o/oauth2/auth?client_id=$client_id&scope=$scope&response_type=code&redirect_uri=$redirectURI"
- echo "Please go to:"
- echo
- echo "$auth_url"
- echo
- echo "after accepting, enter the code you are given:"
- read auth_code
- # swap authorization code for access and refresh tokens
- # http://goo.gl/Mu9E5J
- auth_result=$(curl -s https://accounts.google.com/o/oauth2/token \
- -H "Content-Type: application/x-www-form-urlencoded" \
- -d code=$auth_code \
- -d client_id=$client_id \
- -d client_secret=$client_secret \
- -d redirect_uri=urn:ietf:wg:oauth:2.0:oob \
- -d grant_type=authorization_code)
- access_token=$(echo -e "$auth_result" | \
- ggrep -Po '"access_token" *: *.*?[^\\]",' | \
- awk -F'"' '{ print $4 }')
- refresh_token=$(echo -e "$auth_result" | \
- ggrep -Po '"refresh_token" *: *.*?[^\\]",*' | \
- awk -F'"' '{ print $4 }')
- expires_in=$(echo -e "$auth_result" | \
- ggrep -Po '"expires_in" *: *.*' | \
- awk -F' ' '{ print $3 }' | awk -F',' '{ print $1}')
- time_now=`date +%s`
- expires_at=$((time_now + expires_in - 60))
- echo -e "access_token=$access_token\nrefresh_token=$refresh_token\nexpires_at=$expires_at" > $my_creds
- echo -e "\n#Static data\nclientID=$client_id\nclientSecret=$client_secret\nredirectURI=$redirectURI" >> $my_creds
- fi
- # if our access token is expired, use the refresh token to get a new one
- # http://goo.gl/71rN6V
- if [ $time_now -gt $expires_at ]; then
- refresh_result=$(curl -s https://accounts.google.com/o/oauth2/token \
- -H "Content-Type: application/x-www-form-urlencoded" \
- -d refresh_token=$refresh_token \
- -d client_id=$client_id \
- -d client_secret=$client_secret \
- -d grant_type=refresh_token)
- access_token=$(echo -e "$refresh_result" | \
- ggrep -Po '"access_token" *: *.*?[^\\]",' | \
- awk -F'"' '{ print $4 }')
- expires_in=$(echo -e "$refresh_result" | \
- ggrep -Po '"expires_in" *: *.*' | \
- awk -F' ' '{ print $3 }' | awk -F',' '{ print $1 }')
- time_now=`date +%s`
- expires_at=$(($time_now + $expires_in - 60))
- echo -e "access_token=$access_token\nrefresh_token=$refresh_token\nexpires_at=$expires_at" > $my_creds
- echo -e "\n#Static data\nclientID=$client_id\nclientSecret=$client_secret\nredirectURI=$redirectURI" >> $my_creds
- fi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement