userService.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package service
  2. import (
  3. "AIT/common"
  4. "AIT/constant"
  5. "AIT/global"
  6. "AIT/models"
  7. "gorm.io/gorm"
  8. )
  9. type UserService struct {
  10. }
  11. // FindUserByUsername find by username
  12. func (u *UserService) FindUserByUsername(userName string) (models.User, int64) {
  13. var user models.User
  14. count := global.Db.Where("user_name = ?", userName).First(&user).RowsAffected
  15. return user, count
  16. }
  17. // CreateUser create user
  18. func (u *UserService) CreateUser(user models.UserRegister) *gorm.DB {
  19. userCreate := models.User{
  20. UserName: user.UserName,
  21. Password: user.Password,
  22. Role: user.Role,
  23. }
  24. userCreate.Id = common.GenerateUUID()
  25. return global.Db.Create(&userCreate)
  26. }
  27. func (u *UserService) Login(userLogin models.UserLogin) *models.User {
  28. var user models.User
  29. rows := global.Db.Where(" user_name = ? and password = ? and role = ?", userLogin.Username, userLogin.Password, userLogin.Role).First(&user).RowsAffected
  30. if rows == 0 {
  31. return nil
  32. } else {
  33. return &user
  34. }
  35. }
  36. func (u *UserService) FindUserByUsernameAndRole(username string, role uint8) *models.User {
  37. var user models.User
  38. rows := global.Db.Where(" user_name = ? and role = ?", username, role).First(&user).RowsAffected
  39. if rows == 0 {
  40. return nil
  41. } else {
  42. return &user
  43. }
  44. }
  45. func (u *UserService) RestPassword(username string) *gorm.DB {
  46. user, count := u.FindUserByUsername(username)
  47. if count <= 0 {
  48. return nil
  49. }
  50. userUpdate := models.User{
  51. Password: constant.DefaultUserPassword,
  52. }
  53. userUpdate.Id = user.Id
  54. if user.Id != "" {
  55. result := global.Db.Debug().Updates(&userUpdate)
  56. return result
  57. } else {
  58. return nil
  59. }
  60. }
  61. func (u *UserService) GetUserList(param models.UserListParam) ([]models.User, int64) {
  62. query := models.User{
  63. Role: param.Role,
  64. }
  65. if len(param.UserName) > 0 {
  66. query.UserName = param.UserName
  67. }
  68. page := models.Page{
  69. PageNum: param.PageNum,
  70. PageSize: param.PageSize,
  71. }
  72. userList := make([]models.User, 0)
  73. rows := common.RestPage(page, "user", query, "", &userList, &[]models.User{})
  74. return userList, rows
  75. }
  76. func (u *UserService) ChangePassword(id string, newPassword string) int64 {
  77. userUpdate := models.User{
  78. Password: newPassword,
  79. }
  80. userUpdate.Id = id
  81. count := global.Db.Debug().Updates(&userUpdate).RowsAffected
  82. return count
  83. }