gitea源码

admin_user_change_password.go 2.2KB

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