Compare commits

...

2 Commits

Author SHA1 Message Date
Andreas Düren
ded9e1d174 Added registration code display in logs 2025-03-18 20:04:02 +01:00
Andreas Düren
e093bfc571 Fixed frontend URL error by injecting config.js and runtime-config.js before Caddy starts 2025-03-18 20:03:16 +01:00

213
start.sh
View File

@ -622,10 +622,15 @@ EOF
package main package main
import ( import (
"encoding/json"
"fmt" "fmt"
"io"
"log" "log"
"math/rand"
"net/http" "net/http"
"os" "os"
"strconv"
"strings"
"time" "time"
) )
@ -641,21 +646,149 @@ func main() {
log.Println("PGPORT:", os.Getenv("PGPORT")) log.Println("PGPORT:", os.Getenv("PGPORT"))
log.Println("API_ENDPOINT:", os.Getenv("ENTE_API_ENDPOINT")) log.Println("API_ENDPOINT:", os.Getenv("ENTE_API_ENDPOINT"))
// Create a logger that logs to both stdout and a file
logFile, err := os.OpenFile("/app/data/logs/api_requests.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
log.Printf("Error opening log file: %v", err)
}
defer logFile.Close()
multiWriter := io.MultiWriter(os.Stdout, logFile)
logger := log.New(multiWriter, "", log.LstdFlags)
rand.Seed(time.Now().UnixNano())
// Map to store verification codes
verificationCodes := make(map[string]string)
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, \`{"status":"ok","version":"mock-1.0.0","time":"%s"}\`, time.Now().Format(time.RFC3339)) fmt.Fprintf(w, \`{"status":"ok","version":"mock-1.0.0","time":"%s"}\`, time.Now().Format(time.RFC3339))
}) })
// Handle registration requests
http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading request body", http.StatusBadRequest)
return
}
logger.Printf("REGISTRATION REQUEST: %s", string(body))
// Extract email from request - simplified parsing
emailStart := strings.Index(string(body), "\"email\":\"")
var email string
if emailStart >= 0 {
emailStart += 9 // Length of "\"email\":\""
emailEnd := strings.Index(string(body)[emailStart:], "\"")
if emailEnd >= 0 {
email = string(body)[emailStart : emailStart+emailEnd]
}
}
// Generate verification code
verificationCode := strconv.Itoa(100000 + rand.Intn(900000)) // 6-digit code
if email != "" {
verificationCodes[email] = verificationCode
logger.Printf("===================================================")
logger.Printf("⚠️ VERIFICATION CODE for %s: %s", email, verificationCode)
logger.Printf("===================================================")
}
// Return a success response
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, \`{"status":"ok","message":"Verification code sent (check logs)"}\`)
} else {
// Just handle other methods with a generic response
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, \`{"status":"mock","endpoint":"%s","method":"%s"}\`, r.URL.Path, r.Method)
}
})
// Handle verification endpoint
http.HandleFunc("/users/verification", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading request body", http.StatusBadRequest)
return
}
logger.Printf("VERIFICATION REQUEST: %s", string(body))
// Extract email and code
var email, code string
emailStart := strings.Index(string(body), "\"email\":\"")
if emailStart >= 0 {
emailStart += 9
emailEnd := strings.Index(string(body)[emailStart:], "\"")
if emailEnd >= 0 {
email = string(body)[emailStart : emailStart+emailEnd]
}
}
codeStart := strings.Index(string(body), "\"code\":\"")
if codeStart >= 0 {
codeStart += 8
codeEnd := strings.Index(string(body)[codeStart:], "\"")
if codeEnd >= 0 {
code = string(body)[codeStart : codeStart+codeEnd]
}
}
// Verify the code
isValid := false
if email != "" && code != "" {
expectedCode, exists := verificationCodes[email]
if exists && expectedCode == code {
isValid = true
logger.Printf("✅ SUCCESSFUL VERIFICATION for %s with code %s", email, code)
} else {
logger.Printf("❌ FAILED VERIFICATION for %s with code %s (expected %s)",
email, code, expectedCode)
}
}
w.Header().Set("Content-Type", "application/json")
if isValid {
// Return a successful verification response
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, \`{"status":"ok","token":"mock-token-12345"}\`)
} else {
// Return an error
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, \`{"status":"error","message":"Invalid verification code"}\`)
}
} else {
// Handle other methods with a generic response
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, \`{"status":"mock","endpoint":"%s","method":"%s"}\`, r.URL.Path, r.Method)
}
})
// Generic handler for all other requests
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Printf("Received request for %s via %s", r.URL.Path, r.Method) logger.Printf("Received request for %s via %s", r.URL.Path, r.Method)
if r.Method == "POST" || r.Method == "PUT" {
body, _ := io.ReadAll(r.Body)
if len(body) > 0 {
logger.Printf("Request body: %s", string(body))
}
}
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, \`{"status":"mock","endpoint":"%s","method":"%s","time":"%s"}\`, fmt.Fprintf(w, \`{"status":"mock","endpoint":"%s","method":"%s","time":"%s"}\`,
r.URL.Path, r.Method, time.Now().Format(time.RFC3339)) r.URL.Path, r.Method, time.Now().Format(time.RFC3339))
}) })
log.Printf("Mock Ente API server listening on port %s\n", port) logger.Printf("Mock Ente API server listening on port %s\n", port)
if err := http.ListenAndServe("0.0.0.0:" + port, nil); err != nil { if err := http.ListenAndServe("0.0.0.0:" + port, nil); err != nil {
log.Fatalf("Server failed: %v", err) logger.Fatalf("Server failed: %v", err)
} }
} }
EOT EOT
@ -1037,6 +1170,66 @@ echo "==> Created Caddy config at /app/data/caddy/Caddyfile"
# Start Caddy server # Start Caddy server
echo "==> Starting Caddy server" echo "==> Starting Caddy server"
# First inject the config.js script tags into all HTML files
echo "==> Injecting config.js into web application HTML files"
# Function to inject the script tag
inject_script_tag() {
file="$1"
if [ -f "$file" ]; then
echo "==> Injecting config.js into $file"
# Make a backup just in case
cp "$file" "${file}.bak"
# Insert the script tag right after the opening head tag
sed -i 's/<head>/<head>\n <script src="\/config.js" type="text\/javascript"><\/script>/' "$file"
else
echo "==> WARNING: Could not find $file to inject config script"
fi
}
# Inject into all the web apps
inject_script_tag "/app/web/photos/index.html"
inject_script_tag "/app/web/accounts/index.html"
inject_script_tag "/app/web/auth/index.html"
inject_script_tag "/app/web/cast/index.html"
# Also create a runtime-config.js file with properly escaped content
cat > /app/web/photos/runtime-config.js <<EOT
// Runtime configuration for Ente
window.ENTE_CONFIG = {
API_URL: '${API_ENDPOINT}',
PUBLIC_ALBUMS_URL: '${CLOUDRON_APP_ORIGIN}/public'
};
// Next.js environment variables
window.process = window.process || {};
window.process.env = window.process.env || {};
window.process.env.NEXT_PUBLIC_ENTE_ENDPOINT = '${API_ENDPOINT}';
window.process.env.NEXT_PUBLIC_ENTE_PUBLIC_ALBUMS_ENDPOINT = '${CLOUDRON_APP_ORIGIN}/public';
console.log('Ente runtime config loaded from runtime-config.js');
console.log('API_URL:', window.ENTE_CONFIG.API_URL);
console.log('PUBLIC_ALBUMS_URL:', window.ENTE_CONFIG.PUBLIC_ALBUMS_URL);
EOT
# Copy the runtime-config.js to each app directory
for app_dir in /app/web/photos /app/web/accounts /app/web/auth /app/web/cast; do
cp /app/web/photos/runtime-config.js "$app_dir/"
# Update the HTML to include this file too
index_file="$app_dir/index.html"
if [ -f "$index_file" ]; then
echo "==> Adding runtime-config.js to $index_file"
sed -i 's/<\/head>/<script src="runtime-config.js" type="text\/javascript"><\/script>\n <\/head>/' "$index_file"
fi
done
# Ensure all files are readable
chmod -R 644 /app/web/*/runtime-config.js
echo "==> Config injected into all web applications"
caddy start --config /app/data/caddy/Caddyfile --adapter caddyfile & caddy start --config /app/data/caddy/Caddyfile --adapter caddyfile &
CADDY_PID=$! CADDY_PID=$!
echo "==> Caddy started with PID $CADDY_PID" echo "==> Caddy started with PID $CADDY_PID"
@ -1093,8 +1286,18 @@ else
echo "==> Response: $CONFIG_JS_TEST" echo "==> Response: $CONFIG_JS_TEST"
fi fi
echo "==> Entering wait state - press Ctrl+C to stop" echo "==> Entering wait state - watching logs for registration codes"
# Wait for all background processes to complete (or for user to interrupt) echo "==> Registration verification codes will appear in the logs below"
echo "==> Press Ctrl+C to stop"
# Set up a tail process to show logs in real-time while maintaining the wait state
tail -f /app/data/logs/api_requests.log &
TAIL_PID=$!
# Trap to kill the tail process when the script exits
trap 'kill -TERM $TAIL_PID; kill -TERM $SERVER_PID; kill -TERM $PUBLIC_SERVER_PID; kill -TERM $CADDY_PID; exit' TERM INT
# Wait for all processes
wait $SERVER_PID wait $SERVER_PID
wait $PUBLIC_SERVER_PID wait $PUBLIC_SERVER_PID
wait $CADDY_PID wait $CADDY_PID