You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

76 lines
1.8 KiB

  1. package helpers
  2. import "fmt"
  3. type setupStatusResponse struct {
  4. Success bool `json:"success"`
  5. Data struct {
  6. Status bool `json:"status"`
  7. RootInit bool `json:"root_init"`
  8. } `json:"data"`
  9. Message string `json:"message,omitempty"`
  10. }
  11. type setupResponse struct {
  12. Success bool `json:"success"`
  13. Message string `json:"message,omitempty"`
  14. }
  15. type loginResponse struct {
  16. Success bool `json:"success"`
  17. Data struct {
  18. ID int `json:"id"`
  19. } `json:"data"`
  20. Message string `json:"message,omitempty"`
  21. }
  22. func SetupRoot(client *APIClient, username, password string) error {
  23. var setupStatus setupStatusResponse
  24. if err := client.GetJSON("/api/setup", 200, &setupStatus); err != nil {
  25. return err
  26. }
  27. if setupStatus.Data.Status {
  28. return nil
  29. }
  30. var resp setupResponse
  31. if err := client.PostJSON("/api/setup", map[string]any{
  32. "username": username,
  33. "password": password,
  34. "confirmPassword": password,
  35. "SelfUseModeEnabled": false,
  36. "DemoSiteEnabled": false,
  37. }, 200, &resp); err != nil {
  38. return err
  39. }
  40. if !resp.Success {
  41. return fmt.Errorf("setup root failed: %s", resp.Message)
  42. }
  43. return nil
  44. }
  45. func Login(client *APIClient, username, password string) error {
  46. var resp loginResponse
  47. if err := client.PostJSON("/api/user/login", map[string]any{
  48. "username": username,
  49. "password": password,
  50. }, 200, &resp); err != nil {
  51. return err
  52. }
  53. if !resp.Success {
  54. return fmt.Errorf("login failed: %s", resp.Message)
  55. }
  56. if resp.Data.ID == 0 {
  57. return fmt.Errorf("login succeeded but user id is empty")
  58. }
  59. client.UserID = resp.Data.ID
  60. return nil
  61. }
  62. func SetupAndLoginRoot(client *APIClient, username, password string) error {
  63. if err := SetupRoot(client, username, password); err != nil {
  64. return err
  65. }
  66. return Login(client, username, password)
  67. }