Files
overleaf-registration-be/handlers.go
corrado.mulas 0937f3c06a First commit
2024-11-20 00:30:13 +01:00

81 lines
2.2 KiB
Go

package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
)
// RegistrationRequest represents the incoming registration request.
type RegistrationRequest struct {
Email string `json:"email"`
Captcha string `json:"captcha"`
}
func registerHandler(w http.ResponseWriter, r *http.Request) {
// Allow only POST requests
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Parse the request body
var req RegistrationRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, fmt.Sprintf("Invalid request body: %v", err), http.StatusBadRequest)
return
}
// Validate email
if !validateEmailDomain(req.Email) {
http.Error(w, "Email domain is not allowed", http.StatusBadRequest)
return
}
// Validate reCAPTCHA token
valid, err := validateRecaptcha(req.Captcha)
if err != nil {
http.Error(w, fmt.Sprintf("CAPTCHA validation failed: %v", err), http.StatusInternalServerError)
return
}
if !valid {
http.Error(w, "Invalid CAPTCHA", http.StatusUnauthorized)
return
}
// Initialize Overleaf instance
baseURL := os.Getenv("OL_INSTANCE")
if baseURL == "" {
http.Error(w, "OL_INSTANCE is not set", http.StatusInternalServerError)
return
}
overleaf := NewOverleaf(baseURL)
// Admin login using environment variables
adminEmail := os.Getenv("OL_ADMIN_EMAIL")
adminPassword := os.Getenv("OL_ADMIN_PASSWORD")
if adminEmail == "" || adminPassword == "" {
http.Error(w, "OL_ADMIN_EMAIL or OL_ADMIN_PASSWORD is not set", http.StatusInternalServerError)
return
}
if err := overleaf.Login(adminEmail, adminPassword); err != nil {
http.Error(w, fmt.Sprintf("Admin login failed: %v", err), http.StatusInternalServerError)
return
}
// Create the user in Overleaf
if err := overleaf.RegisterUser(req.Email); err != nil {
http.Error(w, fmt.Sprintf("Failed to create user: %v", err), http.StatusInternalServerError)
return
}
// Respond with success
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{
"message": "User registered successfully. Please check your email to set your password.",
})
}