curl

curl

This curl example fetches a new access token when half of the time until expiration has passed.

#!/bin/sh login=$( jq -n -c --arg username "$USERNAME" --arg password "$PASSWORD" '{"username": $username, "password": $password}' ) cookies=$( mktemp cookies.XXXXXXXXXX ) refresh() { if [ `date --utc --iso-8601=seconds` \< "$refresh" ]; then # no refresh needed return fi local response local body local now local expiration local seconds response=$( curl -w'\n%{response_code}\n' -sS -j -c "$cookies" -H "X-Okapi-Tenant: $TENANT" -H "Content-type: application/json" -d "$login" $OKAPI/authn/login-with-expiry ) body=$( printf '%s\n' "$response" | head -n -1 ) if printf '%s' "$response" | tail -1 | grep --invert-match 201; then printf '%s' "$body" rm "$cookies" exit 1 fi now=$( date --utc +%s ) expiration=$( date --date=`printf '%s' "$body" | jq -r .accessTokenExpiration` --utc +%s ) # refresh after half of the time seconds=$( expr \( $expiration - $now \) / 2 ) refresh=$( date --date="$seconds seconds" --utc --iso-8601=seconds ) } for offset in `seq 0 10 40`; do refresh; curl -w"\n" -sS -D - -b "$cookies" -H "X-Okapi-Tenant: $TENANT" -H "X-Okapi-URL: $OKAPIURL" \ -H "Content-type: application/json" -H "Accept: application/json" \ --data-urlencode "query=$1" \ --data-urlencode "limit=10" \ --data-urlencode "offset=$offset" \ --get "$OKAPI/item-storage/items" done rm "$cookies"