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 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. pwd "code.gitea.io/gitea/modules/auth/password"
  10. "code.gitea.io/gitea/modules/setting"
  11. "github.com/urfave/cli"
  12. )
  13. var microcmdUserChangePassword = cli.Command{
  14. Name: "change-password",
  15. Usage: "Change a user's password",
  16. Action: runChangePassword,
  17. Flags: []cli.Flag{
  18. cli.StringFlag{
  19. Name: "username,u",
  20. Value: "",
  21. Usage: "The user to change password for",
  22. },
  23. cli.StringFlag{
  24. Name: "password,p",
  25. Value: "",
  26. Usage: "New password to set for user",
  27. },
  28. },
  29. }
  30. func runChangePassword(c *cli.Context) error {
  31. if err := argsSet(c, "username", "password"); err != nil {
  32. return err
  33. }
  34. ctx, cancel := installSignals()
  35. defer cancel()
  36. if err := initDB(ctx); err != nil {
  37. return err
  38. }
  39. if len(c.String("password")) < setting.MinPasswordLength {
  40. return fmt.Errorf("Password is not long enough. Needs to be at least %d", setting.MinPasswordLength)
  41. }
  42. if !pwd.IsComplexEnough(c.String("password")) {
  43. return errors.New("Password does not meet complexity requirements")
  44. }
  45. pwned, err := pwd.IsPwned(context.Background(), c.String("password"))
  46. if err != nil {
  47. return err
  48. }
  49. if pwned {
  50. 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")
  51. }
  52. uname := c.String("username")
  53. user, err := user_model.GetUserByName(ctx, uname)
  54. if err != nil {
  55. return err
  56. }
  57. if err = user.SetPassword(c.String("password")); err != nil {
  58. return err
  59. }
  60. if err = user_model.UpdateUserCols(ctx, user, "passwd", "passwd_hash_algo", "salt"); err != nil {
  61. return err
  62. }
  63. fmt.Printf("%s's password has been successfully updated!\n", user.Name)
  64. return nil
  65. }