Files
overleaf-registration-be/overleaf.go
corrado.mulas 207ed263cd First commit
2024-11-20 03:33:07 +01:00

153 lines
3.8 KiB
Go

package main
import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
"github.com/PuerkitoBio/goquery"
)
type Overleaf struct {
BaseURL string
Client *http.Client
CSRF string
}
func NewOverleaf(baseURL string) *Overleaf {
// Create a new HTTP client with a cookie jar
jar, _ := cookiejar.New(nil)
client := &http.Client{
Jar: jar,
}
return &Overleaf{
BaseURL: strings.TrimSuffix(baseURL, "/"),
Client: client,
}
}
// get performs a GET request
func (o *Overleaf) get(endpoint string) (*http.Response, error) {
fullURL := fmt.Sprintf("%s%s", o.BaseURL, endpoint)
resp, err := o.Client.Get(fullURL)
if err != nil {
return nil, fmt.Errorf("GET request to %s failed: %w", fullURL, err)
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("GET request to %s returned status %d: %s", fullURL, resp.StatusCode, string(body))
}
return resp, nil
}
// post performs a POST request
func (o *Overleaf) post(endpoint string, data map[string]string) (*http.Response, error) {
if o.CSRF == "" {
if err := o.obtainCSRF(); err != nil {
return nil, fmt.Errorf("failed to obtain CSRF token: %w", err)
}
}
fullURL := fmt.Sprintf("%s%s", o.BaseURL, endpoint)
data["_csrf"] = o.CSRF
formData := encodeFormData(data)
req, err := http.NewRequest("POST", fullURL, bytes.NewBufferString(formData))
if err != nil {
return nil, fmt.Errorf("failed to create POST request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := o.Client.Do(req)
if err != nil {
return nil, fmt.Errorf("POST request to %s failed: %w", fullURL, err)
}
return resp, nil
}
func (o *Overleaf) obtainCSRF() error {
// Perform a GET request to retrieve the login page
resp, err := o.get("/login")
if err != nil {
return fmt.Errorf("failed to load login page: %v", err)
}
defer resp.Body.Close()
// Parse the HTML to find the CSRF token
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return fmt.Errorf("failed to parse login page HTML: %v", err)
}
csrf, exists := doc.Find(`meta[name="ol-csrfToken"]`).Attr("content")
if !exists {
return fmt.Errorf("CSRF token not found in login page")
}
o.CSRF = csrf
return nil
}
func (o *Overleaf) Login(email, password string) error {
// Retrieve CSRF token
if err := o.obtainCSRF(); err != nil {
return fmt.Errorf("failed to obtain CSRF token: %v", err)
}
// Log the CSRF token for debugging
log.Printf("Obtained CSRF token: %s", o.CSRF)
// Create the login request
resp, err := o.post("/login", map[string]string{
"email": email,
"password": password,
"_csrf": o.CSRF, // Include the CSRF token
})
if err != nil {
return fmt.Errorf("failed to send login request: %v", err)
}
defer resp.Body.Close()
// Log response for debugging
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
log.Printf("Login response: %s", string(body))
return fmt.Errorf("admin login returned status %d: %s", resp.StatusCode, string(body))
}
log.Println("Admin login successful.")
return nil
}
// RegisterUser registers a new user
func (o *Overleaf) RegisterUser(email string) error {
resp, err := o.post("/admin/register", map[string]string{
"email": email,
})
if err != nil {
return fmt.Errorf("failed to register user: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("register user returned status %d: %s", resp.StatusCode, string(body))
}
return nil
}
// encodeFormData encodes a map into x-www-form-urlencoded format
func encodeFormData(data map[string]string) string {
formData := url.Values{}
for key, value := range data {
formData.Set(key, value)
}
return formData.Encode()
}