First commit

This commit is contained in:
corrado.mulas
2024-11-20 16:55:35 +01:00
parent d43964d565
commit 05aa2a9008

View File

@@ -3,12 +3,10 @@ package main
import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
"github.com/PuerkitoBio/goquery"
)
@@ -19,135 +17,121 @@ type Overleaf struct {
CSRF string
}
// NewOverleaf initializes a new Overleaf instance with a cookie jar
// NewOverleaf initializes a new Overleaf instance with a cookie jar for session management
func NewOverleaf(baseURL string) *Overleaf {
jar, _ := cookiejar.New(nil) // Initialize cookie jar
jar, _ := cookiejar.New(nil)
client := &http.Client{
Jar: jar, // Attach cookie jar to client
Jar: jar,
}
return &Overleaf{
BaseURL: strings.TrimSuffix(baseURL, "/"),
BaseURL: baseURL,
Client: client,
}
}
// logCookies logs cookies stored in the client's cookie jar for a given endpoint
func logCookies(client *http.Client, endpoint string) {
u, _ := url.Parse(endpoint)
cookies := client.Jar.Cookies(u)
for _, cookie := range cookies {
log.Printf("Cookie for %s: %s=%s", endpoint, cookie.Name, cookie.Value)
}
}
// get performs a GET request
// get performs a GET request and returns the HTTP response
func (o *Overleaf) get(endpoint string) (*http.Response, error) {
url := fmt.Sprintf("%s%s", o.BaseURL, endpoint)
resp, err := o.Client.Get(url)
if err == nil {
logCookies(o.Client, url) // Log cookies after GET request
}
return resp, err
}
// post performs a POST request
func (o *Overleaf) post(endpoint string, data map[string]string) (*http.Response, error) {
url := fmt.Sprintf("%s%s", o.BaseURL, endpoint)
data["_csrf"] = o.CSRF
formData := encodeFormData(data)
req, err := http.NewRequest("POST", url, bytes.NewBufferString(formData))
fullURL := fmt.Sprintf("%s%s", o.BaseURL, endpoint)
resp, err := o.Client.Get(fullURL)
if err != nil {
return nil, fmt.Errorf("failed to create POST request: %v", err)
return nil, fmt.Errorf("GET request failed: %v", err)
}
return resp, nil
}
// post performs a POST request with form data
func (o *Overleaf) post(endpoint string, data map[string]string) (*http.Response, error) {
fullURL := fmt.Sprintf("%s%s", o.BaseURL, endpoint)
// Encode form data using url.Values
formData := url.Values{}
for key, value := range data {
formData.Set(key, value)
}
req, err := http.NewRequest("POST", fullURL, bytes.NewBufferString(formData.Encode()))
if err != nil {
return nil, fmt.Errorf("POST request creation failed: %v", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := o.Client.Do(req)
if err == nil {
logCookies(o.Client, url) // Log cookies after POST request
if err != nil {
return nil, fmt.Errorf("POST request failed: %v", err)
}
return resp, err
return resp, nil
}
// obtainCSRF retrieves the CSRF token
func (o *Overleaf) obtainCSRF() error {
resp, err := o.get("/login")
// obtainCSRF fetches the CSRF token from the specified endpoint
func (o *Overleaf) obtainCSRF(endpoint string) error {
resp, err := o.get(endpoint)
if err != nil {
return fmt.Errorf("failed to load login page: %v", err)
return fmt.Errorf("failed to fetch page for CSRF token: %v", err)
}
defer resp.Body.Close()
// Parse the HTML to extract the CSRF token
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return fmt.Errorf("failed to parse login page HTML: %v", err)
return fmt.Errorf("failed to parse 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")
return fmt.Errorf("CSRF token not found")
}
o.CSRF = csrf
log.Printf("Obtained CSRF token: %s", o.CSRF)
log.Printf("Obtained CSRF token: %s", csrf)
return nil
}
// Login authenticates as admin
// Login logs in as an admin and saves the session
func (o *Overleaf) Login(email, password string) error {
if err := o.obtainCSRF(); err != nil {
// Fetch the login page to get the CSRF token
if err := o.obtainCSRF("/login"); err != nil {
return fmt.Errorf("failed to obtain CSRF token: %v", err)
}
// Send login request
resp, err := o.post("/login", map[string]string{
"email": email,
"password": password,
"_csrf": o.CSRF,
})
if err != nil {
return fmt.Errorf("failed to send login request: %v", err)
return fmt.Errorf("login request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
log.Printf("Login response: %s", string(body))
return fmt.Errorf("admin login returned status %d: %s", resp.StatusCode, string(body))
return fmt.Errorf("login failed with status code: %d", resp.StatusCode)
}
log.Println("Admin login successful.")
return nil
}
// RegisterUser registers a new user
// RegisterUser registers a new user using the admin session
func (o *Overleaf) RegisterUser(email string) error {
log.Printf("Attempting to register user with email: %s", email)
log.Printf("Using CSRF token: %s", o.CSRF)
// Fetch the admin registration page to get the CSRF token
if err := o.obtainCSRF("/admin/register"); err != nil {
return fmt.Errorf("failed to obtain CSRF token for registration: %v", err)
}
// Send user registration request
resp, err := o.post("/admin/register", map[string]string{
"email": email,
"_csrf": o.CSRF,
})
if err != nil {
return fmt.Errorf("failed to send register request: %v", err)
return fmt.Errorf("registration request failed: %v", err)
}
defer resp.Body.Close()
// Log response for debugging
body, _ := io.ReadAll(resp.Body)
log.Printf("Register user response: %s", string(body))
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("register user returned status %d: %s", resp.StatusCode, string(body))
return fmt.Errorf("user registration failed with status code: %d", resp.StatusCode)
}
log.Println("User registered successfully.")
return nil
}
// encodeFormData encodes a map into x-www-form-urlencoded format
func encodeFormData(data map[string]string) string {
var formData []string
for key, value := range data {
formData = append(formData, fmt.Sprintf("%s=%s", key, value))
}
return strings.Join(formData, "&")
}