skip_install.go 1.7 KB

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