skip_install.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package kernal
  2. import (
  3. "github.com/0xJacky/Nginx-UI/model"
  4. "github.com/0xJacky/Nginx-UI/query"
  5. "github.com/0xJacky/Nginx-UI/settings"
  6. "github.com/caarlos0/env/v11"
  7. "github.com/google/uuid"
  8. "github.com/pkg/errors"
  9. "github.com/uozi-tech/cosy/logger"
  10. cSettings "github.com/uozi-tech/cosy/settings"
  11. "golang.org/x/crypto/bcrypt"
  12. "gorm.io/gorm"
  13. )
  14. type predefinedUser struct {
  15. Name string `json:"name"`
  16. Password string `json:"password"`
  17. }
  18. func skipInstall() {
  19. logger.Info("Skip installation mode enabled")
  20. if cSettings.AppSettings.JwtSecret == "" {
  21. cSettings.AppSettings.JwtSecret = uuid.New().String()
  22. }
  23. if settings.NodeSettings.Secret == "" {
  24. settings.NodeSettings.Secret = uuid.New().String()
  25. logger.Infof("Secret: %s", settings.NodeSettings.Secret)
  26. }
  27. err := settings.Save()
  28. if err != nil {
  29. logger.Fatal(err)
  30. }
  31. }
  32. func registerPredefinedUser() {
  33. // when skip installation mode is enabled, the predefined user will be created
  34. if !settings.NodeSettings.SkipInstallation {
  35. return
  36. }
  37. pUser := &predefinedUser{}
  38. err := env.ParseWithOptions(pUser, env.Options{
  39. Prefix: "NGINX_UI_PREDEFINED_USER_",
  40. UseFieldNameByDefault: true,
  41. })
  42. if err != nil {
  43. logger.Fatal(err)
  44. }
  45. u := query.User
  46. _, err = u.First()
  47. // Only effect when there is no user in the database
  48. if !errors.Is(err, gorm.ErrRecordNotFound) || pUser.Name == "" || pUser.Password == "" {
  49. return
  50. }
  51. // Create a new user with the predefined name and password
  52. pwd, _ := bcrypt.GenerateFromPassword([]byte(pUser.Password), bcrypt.DefaultCost)
  53. err = u.Create(&model.User{
  54. Name: pUser.Name,
  55. Password: string(pwd),
  56. })
  57. if err != nil {
  58. logger.Error(err)
  59. }
  60. }