reset_password.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package user
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "math/big"
  6. "os"
  7. "path"
  8. "github.com/0xJacky/Nginx-UI/model"
  9. "github.com/0xJacky/Nginx-UI/query"
  10. "github.com/0xJacky/Nginx-UI/settings"
  11. "github.com/gin-gonic/gin"
  12. "github.com/uozi-tech/cosy"
  13. sqlite "github.com/uozi-tech/cosy-driver-sqlite"
  14. "github.com/uozi-tech/cosy/logger"
  15. cSettings "github.com/uozi-tech/cosy/settings"
  16. "github.com/urfave/cli/v3"
  17. "golang.org/x/crypto/bcrypt"
  18. )
  19. func generateRandomPassword(length int) (string, error) {
  20. const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+"
  21. password := make([]byte, length)
  22. charsetLength := big.NewInt(int64(len(charset)))
  23. for i := 0; i < length; i++ {
  24. randomIndex, err := rand.Int(rand.Reader, charsetLength)
  25. if err != nil {
  26. return "", err
  27. }
  28. password[i] = charset[randomIndex.Int64()]
  29. }
  30. return string(password), nil
  31. }
  32. func ResetInitUserPassword(ctx context.Context, command *cli.Command) error {
  33. confPath := command.String("config")
  34. settings.Init(confPath)
  35. cSettings.ServerSettings.RunMode = gin.ReleaseMode
  36. logger.Init(cSettings.ServerSettings.RunMode)
  37. logger.Infof("confPath: %s", confPath)
  38. if _, err := os.Stat(confPath); os.IsNotExist(err) {
  39. return ErrConfigNotFound
  40. }
  41. dbPath := path.Join(path.Dir(confPath), settings.DatabaseSettings.Name+".db")
  42. logger.Infof("dbPath: %s", dbPath)
  43. // check if db file exists
  44. if _, err := os.Stat(dbPath); os.IsNotExist(err) {
  45. return ErrDBFileNotFound
  46. }
  47. db := cosy.InitDB(sqlite.Open(path.Dir(cSettings.ConfPath), settings.DatabaseSettings))
  48. model.Use(db)
  49. query.Init(db)
  50. u := query.User
  51. user, err := u.FirstByID(1)
  52. if err != nil {
  53. return ErrInitUserNotExists
  54. }
  55. pwd, err := generateRandomPassword(12)
  56. if err != nil {
  57. return err
  58. }
  59. pwdBytes, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
  60. if err != nil {
  61. return err
  62. }
  63. _, err = u.Where(u.ID.Eq(1)).Updates(&model.User{
  64. Password: string(pwdBytes),
  65. })
  66. if err != nil {
  67. return err
  68. }
  69. a := query.AuthToken
  70. _, _ = a.Where(a.UserID.Eq(1)).Delete()
  71. logger.Infof("User: %s, Password: %s", user.Name, pwd)
  72. return nil
  73. }