Skip to content

Instantly share code, notes, and snippets.

@chrishannah
Created December 31, 2022 17:23
Show Gist options
  • Save chrishannah/5f64b90a35a01717eda06dcd9fefa59a to your computer and use it in GitHub Desktop.
Save chrishannah/5f64b90a35a01717eda06dcd9fefa59a to your computer and use it in GitHub Desktop.
A bash script that allows you to mass delete blog posts from a Ghost blog via a text file of post ids.
#!/usr/bin/env bash
# Admin API key goes here
KEY="this is your admin api key"
# Split the key into ID and SECRET
TMPIFS=$IFS
IFS=':' read ID SECRET <<<"$KEY"
IFS=$TMPIFS
# Prepare header and payload
NOW=$(date +'%s')
FIVE_MINS=$(($NOW + 300))
HEADER="{\"alg\": \"HS256\",\"typ\": \"JWT\", \"kid\": \"$ID\"}"
PAYLOAD="{\"iat\":$NOW,\"exp\":$FIVE_MINS,\"aud\": \"/admin/\"}"
# Helper function for performing base64 URL encoding
base64_url_encode() {
declare input=${1:-$(</dev/stdin)}
# Use `tr` to URL encode the output from base64.
printf '%s' "${input}" | base64 | tr -d '=' | tr '+' '-' | tr '/' '_'
}
# Prepare the token body
header_base64=$(base64_url_encode "$HEADER")
payload_base64=$(base64_url_encode "$PAYLOAD")
header_payload="${header_base64}.${payload_base64}"
# Create the signature
signature=$(printf '%s' "${header_payload}" | openssl dgst -binary -sha256 -mac HMAC -macopt hexkey:$SECRET | base64_url_encode)
# Concat payload and signature into a valid JWT token
TOKEN="${header_payload}.${signature}"
echo $TOKEN
# Mass delete posts
# The name of a file that contains a list of post ids that are to be deleted.
FILENAME="posts.txt"
LINES=$(cat $FILENAME)
for LINE in $LINES; do
curl -X "DELETE" \
-H "Authorization: Ghost $TOKEN" \
-H "Content-Type: application/json" \
-H "Accept-Version: v5.22" \ # the version of Ghost (only major.minor needed) that your blog uses
"https://yourdomain.com/ghost/api/admin/posts/$LINE" # your ghost blog
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment