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.

admin_user_change_password.go 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package cmd
  4. import (
  5. "errors"
  6. "fmt"
  7. user_model "code.gitea.io/gitea/models/user"
  8. "code.gitea.io/gitea/modules/auth/password"
  9. "code.gitea.io/gitea/modules/optional"
  10. "code.gitea.io/gitea/modules/setting"
  11. user_service "code.gitea.io/gitea/services/user"
  12. "github.com/urfave/cli/v2"
  13. )
  14. var microcmdUserChangePassword = &cli.Command{
  15. Name: "change-password",
  16. Usage: "Change a user's password",
  17. Action: runChangePassword,
  18. Flags: []cli.Flag{
  19. &cli.StringFlag{
  20. Name: "username",
  21. Aliases: []string{"u"},
  22. Value: "",
  23. Usage: "The user to change password for",
  24. },
  25. &cli.StringFlag{
  26. Name: "password",
  27. Aliases: []string{"p"},
  28. Value: "",
  29. Usage: "New password to set for user",
  30. },
  31. &cli.BoolFlag{
  32. Name: "must-change-password",
  33. Usage: "User must change password",
  34. },
  35. },
  36. }
  37. func runChangePassword(c *cli.Context) error {
  38. if err := argsSet(c, "username", "password"); err != nil {
  39. return err
  40. }
  41. ctx, cancel := installSignals()
  42. defer cancel()
  43. if err := initDB(ctx); err != nil {
  44. return err
  45. }
  46. user, err := user_model.GetUserByName(ctx, c.String("username"))
  47. if err != nil {
  48. return err
  49. }
  50. var mustChangePassword optional.Option[bool]
  51. if c.IsSet("must-change-password") {
  52. mustChangePassword = optional.Some(c.Bool("must-change-password"))
  53. }
  54. opts := &user_service.UpdateAuthOptions{
  55. Password: optional.Some(c.String("password")),
  56. MustChangePassword: mustChangePassword,
  57. }
  58. if err := user_service.UpdateAuth(ctx, user, opts); err != nil {
  59. switch {
  60. case errors.Is(err, password.ErrMinLength):
  61. return fmt.Errorf("Password is not long enough. Needs to be at least %d", setting.MinPasswordLength)
  62. case errors.Is(err, password.ErrComplexity):
  63. return errors.New("Password does not meet complexity requirements")
  64. case errors.Is(err, password.ErrIsPwned):
  65. return errors.New("The password you chose is on a list of stolen passwords previously exposed in public data breaches. Please try again with a different password.\nFor more details, see https://haveibeenpwned.com/Passwords")
  66. default:
  67. return err
  68. }
  69. }
  70. fmt.Printf("%s's password has been successfully updated!\n", user.Name)
  71. return nil
  72. }