Skip to content

Instantly share code, notes, and snippets.

@Thann
Last active June 12, 2017 23:42
Show Gist options
  • Save Thann/1b77765ba7280ac2327da5d2f55279b0 to your computer and use it in GitHub Desktop.
Save Thann/1b77765ba7280ac2327da5d2f55279b0 to your computer and use it in GitHub Desktop.
Purse Api Client
#!/bin/env bash
# Purse Api Client
# Usage:
# domain api.purse.io # sets domain, defaults to local.
# login [username] # logs in as user.
# <url> [options] # call out to curl with token.
#
PURSE_CLIENT_TOKEN_FILE="$HOME/.purse_client_token";
PURSE_CLIENT_URL_FILE="$HOME/.purse_client_url";
set_domain () {
PURSE_CLIENT_BASE_URL="https://$1/api/v1";
echo "$PURSE_CLIENT_BASE_URL" > "$PURSE_CLIENT_URL_FILE";
}
# Read url file
if [ -e "$PURSE_CLIENT_URL_FILE" ]; then
PURSE_CLIENT_BASE_URL=$(cat "$PURSE_CLIENT_URL_FILE");
fi
# Use local dev by default
if [ -z "$PURSE_CLIENT_BASE_URL" ]; then
set_domain "api.local.dev.purse.io";
echo "Using: $PURSE_CLIENT_BASE_URL";
fi
first_arg="$1"; # defaut to "help"
if [ -z "$1" ]; then first_arg='help'; fi
case "$first_arg" in
help | h)
echo "Usage:
# domain api.purse.io # sets domain, defaults to local.
# login [username] # logs in as user.
# <url> [options] # call out to curl with token."
;;
domain | d )
if [ -z "$2" ]; then
# print url
echo "$PURSE_CLIENT_BASE_URL";
else
# set url
set_domain "$2";
fi
;;
login | l )
( #subshell to prevent leaking password if sourced.
if [ -z "$2" ]; then
echo -n "Enter email: ";
read username;
else
username="$2";
fi
# If no '@', use username as password.
if [[ ! "$username" =~ '@' ]]; then
password="$username"
username="$username@mail.com"
else
echo -n "Enter password: ";
read -s password;
echo ""
fi
echo "Using: $PURSE_CLIENT_BASE_URL";
response=$(curl -s -X POST -H 'content-type:application/json' \
-d "{\"username\": \"$username\",\"password\": \"$password\"}" \
"$PURSE_CLIENT_BASE_URL/auth/" "${@:2}");
if ! [ -z "$3" ]; then # show response is there is a third flag.
echo "RESPONSE: $response"
fi
# if token, save to token-file.
if [[ "$response" =~ '"token":' ]]; then
# pull toeken out of response
token=$(echo "$response" | sed -n 's/.*"token": "\(.*\)".*/\1/p')
echo "$token" > "$PURSE_CLIENT_TOKEN_FILE";
chmod 600 "$PURSE_CLIENT_TOKEN_FILE";
else
echo "$response";
fi
)
;;
logout | logoff )
echo > "$PURSE_CLIENT_TOKEN_FILE";
;;
*)
token=$(cat "$PURSE_CLIENT_TOKEN_FILE")
# echo curl -H 'content-type: application/json' \
# -H "Authorization: JWT $token" \
# "$PURSE_CLIENT_BASE_URL/$1" ${@:2};
if [ -z "$token" ] ; then
response=$(curl -s -H 'content-type:application/json' \
"$PURSE_CLIENT_BASE_URL/$1" "${@:2}");
else
response=$(curl -s -H 'content-type:application/json' \
-H "Authorization: JWT $token" \
"$PURSE_CLIENT_BASE_URL/$1" "${@:2}");
fi
echo "$response"
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment