|
#!/bin/bash |
|
set -x |
|
|
|
# Ensure EMAIL and PASSWORD are provided |
|
if [ $# -lt 2 ]; then |
|
echo "Usage: $0 <EMAIL> <PASSWORD> [API_URL]" |
|
exit 1 |
|
fi |
|
|
|
EMAIL="$1" |
|
PASSWORD="$2" |
|
API_URL="${3:-http://localhost:3040}" # Default to localhost if not provided |
|
|
|
# Define cookie file names |
|
csrf_cookie_file="csrf_cookies.txt" |
|
login_cookie_file="login_cookies.txt" |
|
|
|
# Define API endpoints |
|
CSRF_URL="$API_URL/api/auth/csrf" |
|
SIGNUP_URL="$API_URL/api/signup" |
|
LOGIN_URL="$API_URL/api/auth/callback/credentials" |
|
|
|
# Fetch CSRF token and store cookies |
|
csrf_token=$(curl -s -X GET "$CSRF_URL" -c "$csrf_cookie_file" | jq -r '.csrfToken') |
|
|
|
# Exit if CSRF token is missing |
|
[ -z "$csrf_token" ] || [ "$csrf_token" == "null" ] && { echo "Failed to retrieve CSRF token"; exit 1; } |
|
|
|
# Perform signup request using CSRF token and cookies |
|
signup_response=$(curl -s -i -w "\n%{http_code}" -X POST "$SIGNUP_URL" \ |
|
-H "Content-Type: application/json" \ |
|
-b "$csrf_cookie_file" \ |
|
--cookie-jar "$login_cookie_file" \ |
|
-d "{\"csrfToken\":\"$csrf_token\",\"email\":\"$EMAIL\",\"password\":\"$PASSWORD\"}") |
|
|
|
signup_body=$(echo "$signup_response" | sed '$d') |
|
signup_status=$(echo "$signup_response" | tail -n1) |
|
|
|
if [[ "$signup_status" == "200" ]]; then |
|
echo "Signup successful. Use $login_cookie_file for authenticated requests:" |
|
echo "curl \"$API_URL/api/me\" -b $login_cookie_file" |
|
exit 0 |
|
elif echo "$signup_body" | grep -iq "already exists"; then |
|
echo "User already exists. Attempting to log in..." |
|
|
|
login_response=$(curl -s -i -w "\n%{http_code}" -X POST "$LOGIN_URL" \ |
|
-H "Content-Type: application/json" \ |
|
-b "$csrf_cookie_file" \ |
|
--cookie-jar "$login_cookie_file" \ |
|
-d "{\"email\":\"$EMAIL\",\"password\":\"$PASSWORD\",\"csrfToken\":\"$csrf_token\"}") |
|
|
|
login_body=$(echo "$login_response" | sed '$d') |
|
login_status=$(echo "$login_response" | tail -n1) |
|
|
|
if [[ "$login_status" == "200" || "$login_status" == "302" ]]; then |
|
echo "Login successful. Use $login_cookie_file for authenticated requests:" |
|
echo "curl \"$API_URL/api/me\" -b $login_cookie_file" |
|
exit 0 |
|
else |
|
echo "Login failed: $login_body" |
|
exit 1 |
|
fi |
|
else |
|
echo "Signup failed: $signup_body" |
|
exit 1 |
|
fi |