admin_users.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package api
  2. import (
  3. "github.com/grafana/grafana/pkg/api/dtos"
  4. "github.com/grafana/grafana/pkg/bus"
  5. "github.com/grafana/grafana/pkg/metrics"
  6. m "github.com/grafana/grafana/pkg/models"
  7. "github.com/grafana/grafana/pkg/util"
  8. )
  9. func AdminCreateUser(c *m.Context, form dtos.AdminCreateUserForm) {
  10. cmd := m.CreateUserCommand{
  11. Login: form.Login,
  12. Email: form.Email,
  13. Password: form.Password,
  14. Name: form.Name,
  15. }
  16. if len(cmd.Login) == 0 {
  17. cmd.Login = cmd.Email
  18. if len(cmd.Login) == 0 {
  19. c.JsonApiErr(400, "Validation error, need specify either username or email", nil)
  20. return
  21. }
  22. }
  23. if len(cmd.Password) < 4 {
  24. c.JsonApiErr(400, "Password is missing or too short", nil)
  25. return
  26. }
  27. if err := bus.Dispatch(&cmd); err != nil {
  28. c.JsonApiErr(500, "failed to create user", err)
  29. return
  30. }
  31. metrics.M_Api_Admin_User_Create.Inc()
  32. user := cmd.Result
  33. result := m.UserIdDTO{
  34. Message: "User created",
  35. Id: user.Id,
  36. }
  37. c.JSON(200, result)
  38. }
  39. func AdminUpdateUserPassword(c *m.Context, form dtos.AdminUpdateUserPasswordForm) {
  40. userId := c.ParamsInt64(":id")
  41. if len(form.Password) < 4 {
  42. c.JsonApiErr(400, "New password too short", nil)
  43. return
  44. }
  45. userQuery := m.GetUserByIdQuery{Id: userId}
  46. if err := bus.Dispatch(&userQuery); err != nil {
  47. c.JsonApiErr(500, "Could not read user from database", err)
  48. return
  49. }
  50. passwordHashed := util.EncodePassword(form.Password, userQuery.Result.Salt)
  51. cmd := m.ChangeUserPasswordCommand{
  52. UserId: userId,
  53. NewPassword: passwordHashed,
  54. }
  55. if err := bus.Dispatch(&cmd); err != nil {
  56. c.JsonApiErr(500, "Failed to update user password", err)
  57. return
  58. }
  59. c.JsonOK("User password updated")
  60. }
  61. func AdminUpdateUserPermissions(c *m.Context, form dtos.AdminUpdateUserPermissionsForm) {
  62. userId := c.ParamsInt64(":id")
  63. cmd := m.UpdateUserPermissionsCommand{
  64. UserId: userId,
  65. IsGrafanaAdmin: form.IsGrafanaAdmin,
  66. }
  67. if err := bus.Dispatch(&cmd); err != nil {
  68. c.JsonApiErr(500, "Failed to update user permissions", err)
  69. return
  70. }
  71. c.JsonOK("User permissions updated")
  72. }
  73. func AdminDeleteUser(c *m.Context) {
  74. userId := c.ParamsInt64(":id")
  75. cmd := m.DeleteUserCommand{UserId: userId}
  76. if err := bus.Dispatch(&cmd); err != nil {
  77. c.JsonApiErr(500, "Failed to delete user", err)
  78. return
  79. }
  80. c.JsonOK("User deleted")
  81. }