Files
b0esche_cloud/go_cloud/internal/storage/nextcloud.go
2026-01-11 00:48:04 +01:00

77 lines
2.4 KiB
Go

package storage
import (
"bytes"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
"net/http"
"strings"
)
// CreateNextcloudUser creates a new Nextcloud user account via OCS API
func CreateNextcloudUser(nextcloudBaseURL, adminUser, adminPass, username, password string) error {
// Remove any path from base URL, we need just the scheme://host:port
baseURL := strings.Split(nextcloudBaseURL, "/remote.php")[0]
url := fmt.Sprintf("%s/ocs/v1.php/cloud/users", baseURL)
// OCS API expects form-encoded data, not JSON
formData := fmt.Sprintf("userid=%s&password=%s",
strings.ReplaceAll(username, " ", "+"),
strings.ReplaceAll(password, " ", "+"))
req, err := http.NewRequest("POST", url, bytes.NewBufferString(formData))
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.SetBasicAuth(adminUser, adminPass)
req.Header.Set("OCS-APIRequest", "true")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to create user: %w", err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
// 200 = success, 409 = user already exists (which is fine)
if resp.StatusCode != 200 && resp.StatusCode != 409 {
return fmt.Errorf("failed to create Nextcloud user (status %d): %s", resp.StatusCode, string(body))
}
fmt.Printf("[NEXTCLOUD] Created user account: %s with generated password\n", username)
return nil
}
// GenerateSecurePassword generates a random secure password
func GenerateSecurePassword(length int) (string, error) {
bytes := make([]byte, length)
if _, err := rand.Read(bytes); err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(bytes)[:length], nil
}
// NewUserWebDAVClient creates a WebDAV client for a specific user
func NewUserWebDAVClient(nextcloudBaseURL, username, password string) *WebDAVClient {
// Remove any path from base URL, we need just the scheme://host:port
baseURL := strings.Split(nextcloudBaseURL, "/remote.php")[0]
// Build the full WebDAV URL for this user
fullURL := fmt.Sprintf("%s/remote.php/dav/files/%s", baseURL, username)
fmt.Printf("[WEBDAV-USER] Input URL: %s, Base: %s, Full: %s, User: %s\n", nextcloudBaseURL, baseURL, fullURL, username)
return &WebDAVClient{
baseURL: fullURL,
user: username,
pass: password,
basePrefix: "/",
httpClient: &http.Client{},
}
}