monotreme.org/scripts/forgot_password.cgi

97 lines
2.2 KiB
Text
Raw Normal View History

2024-09-22 03:41:33 +01:00
#!/bin/bash
echo "Content-type: text/html"
echo ""
# Log the raw POST data for debugging
read POST_DATA
echo "POST Data: $POST_DATA" >> /tmp/forgot_password.log
# URL decoding function
urldecode() {
local url_encoded="${1//+/ }"
printf '%b' "${url_encoded//%/\\x}"
}
# Parse the form data using IFS
USERNAME=""
EMAIL=""
IFS='&' # Split fields by "&"
for param in $POST_DATA; do
IFS='=' read -r key value <<< "$param"
key=$(urldecode "$key")
value=$(urldecode "$value")
case $key in
username) USERNAME="$value" ;;
email) EMAIL="$value" ;;
esac
done
# Check if the user exists in the database
DB_PATH="/var/lib/monotreme/data/monotreme .db"
2024-09-22 03:41:33 +01:00
USER_EXISTS=$(sqlite3 $DB_PATH "SELECT COUNT(*) FROM users WHERE username='$USERNAME' AND email='$EMAIL';")
if [ "$USER_EXISTS" -eq 0 ]; then
cat <<EOF
<html>
<head><title>Reset Failed</title></head>
<body>
<h1>User not found!</h1>
<a href="/login/forgot/">Try again</a>
</body>
</html>
EOF
exit 1
fi
# Generate a unique token for resetting the password
TOKEN=$(openssl rand -hex 16)
# Set token expiration to 1 hour from now (Unix timestamp)
EXPIRATION=$(($(date +%s) + 3600))
# Store the reset token and expiration in the database
sqlite3 $DB_PATH "UPDATE users SET reset_token='$TOKEN', reset_expires=$EXPIRATION WHERE username='$USERNAME';"
2024-09-22 03:41:33 +01:00
# Send reset link email
2024-09-22 19:07:54 +01:00
RESET_LINK="https://monotreme.org/cgi-bin/reset_password.cgi?token=$TOKEN"
2024-09-22 03:41:33 +01:00
EMAIL_BODY=$(cat <<EOF
From: info@monotreme.org
To: $EMAIL
Subject: Password Reset Request
Hello $USERNAME,
A request has been made to reset your password. If you did not make this request, you can ignore this email.
To reset your password, click the link below or copy it into your browser:
$RESET_LINK
This link will expire in 1 hour.
Best regards,
monotreme.org team
EOF
)
# Log the email body for debugging
echo "Email Body: $EMAIL_BODY" >> /tmp/forgot_password.log
# Send the email
echo "$EMAIL_BODY" | msmtp --account=monotreme "$EMAIL"
# Response back to the browser
cat <<EOF
<html>
<head><title>Password Reset Sent</title></head>
<body>
<h1>Reset link sent!</h1>
<p>A reset link has been sent to $EMAIL. Please check your email.</p>
<a href="/login/">Go to login page</a>
</body>
</html>
EOF