Files
overleaf-registration-be/overleaf.go
corrado.mulas 36fa1d9db4 First commit
2024-11-19 23:46:08 +01:00

118 lines
2.5 KiB
Go

package main
import (
"bytes"
"errors"
"fmt"
"io"
"net/http"
"strings"
"github.com/PuerkitoBio/goquery"
)
type Overleaf struct {
BaseURL string
Client *http.Client
CSRF string
}
// NewOverleaf initializes a new Overleaf instance
func NewOverleaf(baseURL string) *Overleaf {
return &Overleaf{
BaseURL: strings.TrimSuffix(baseURL, "/"),
Client: &http.Client{},
}
}
// get performs a GET request
func (o *Overleaf) get(endpoint string) (*http.Response, error) {
url := fmt.Sprintf("%s%s", o.BaseURL, endpoint)
return o.Client.Get(url)
}
// 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, err
}
}
url := fmt.Sprintf("%s%s", o.BaseURL, endpoint)
data["_csrf"] = o.CSRF
formData := encodeFormData(data)
req, err := http.NewRequest("POST", url, bytes.NewBufferString(formData))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return o.Client.Do(req)
}
// obtainCSRF retrieves the CSRF token
func (o *Overleaf) obtainCSRF() error {
resp, err := o.get("/login")
if err != nil {
return err
}
defer resp.Body.Close()
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return err
}
csrf, exists := doc.Find(`meta[name="ol-csrfToken"]`).Attr("content")
if !exists {
return errors.New("CSRF token not found")
}
o.CSRF = csrf
return nil
}
// Login as admin
func (o *Overleaf) Login(email, password string) error {
resp, err := o.post("/login", map[string]string{
"email": email,
"password": password,
})
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return errors.New("failed to log in as admin")
}
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 err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("failed to register user: %s", string(body))
}
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, "&")
}