mission-control/scripts/lib/api_client.sh

112 lines
2.5 KiB
Bash
Executable File

#!/bin/bash
# Mission Control API Client Library
# Shared HTTP client for Mission Control CLI scripts
# Follows the same pattern as gantt-board/scripts/lib/api_client.sh
set -euo pipefail
# Configuration
MC_API_URL="${MC_API_URL:-http://localhost:3001/api}"
MC_COOKIE_FILE="${MC_COOKIE_FILE:-$HOME/.config/mission-control/cookies.txt}"
# Ensure cookie directory exists
mkdir -p "$(dirname "$MC_COOKIE_FILE")"
# Make authenticated API call to Mission Control
# Usage: mc_api_call <method> <endpoint> [data]
mc_api_call() {
local method="$1"
local endpoint="$2"
local data="${3:-}"
local url="${MC_API_URL}${endpoint}"
local curl_opts=(
-s
-b "$MC_COOKIE_FILE"
-c "$MC_COOKIE_FILE"
-H "Content-Type: application/json"
)
if [[ -n "$data" ]]; then
curl_opts+=(-d "$data")
fi
curl "${curl_opts[@]}" -X "$method" "$url"
}
# GET request helper
# Usage: mc_get <endpoint>
mc_get() {
mc_api_call "GET" "$1"
}
# POST request helper
# Usage: mc_post <endpoint> [data]
mc_post() {
local endpoint="$1"
local data="${2:-}"
mc_api_call "POST" "$endpoint" "$data"
}
# DELETE request helper
# Usage: mc_delete <endpoint>
mc_delete() {
mc_api_call "DELETE" "$1"
}
# URL encode a string
# Usage: url_encode <string>
url_encode() {
local str="$1"
printf '%s' "$str" | jq -sRr @uri
}
# Check if user is authenticated (cookie exists and is valid)
mc_is_authenticated() {
if [[ ! -f "$MC_COOKIE_FILE" ]]; then
return 1
fi
# Try to get session - if it fails, not authenticated
local response
response=$(mc_get "/auth/session" 2>/dev/null || echo '{"user":null}')
# Check if we got a valid user back
echo "$response" | jq -e '.user != null' >/dev/null 2>&1
}
# Login to Mission Control
# Usage: mc_login <email> <password>
mc_login() {
local email="$1"
local password="$2"
local response
response=$(mc_post "/auth/login" "$(jq -n --arg email "$email" --arg password "$password" '{email:$email,password:$password}')")
if echo "$response" | jq -e '.error' >/dev/null 2>&1; then
echo "Login failed: $(echo "$response" | jq -r '.error')" >&2
return 1
fi
echo "Login successful"
return 0
}
# Logout from Mission Control
mc_logout() {
mc_post "/auth/logout"
rm -f "$MC_COOKIE_FILE"
echo "Logged out"
}
# Export functions for use in other scripts
export -f mc_api_call
export -f mc_get
export -f mc_post
export -f mc_delete
export -f url_encode
export -f mc_is_authenticated
export -f mc_login
export -f mc_logout