userService.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package service
  2. import (
  3. "confrontation-training/common"
  4. "confrontation-training/constant"
  5. "confrontation-training/global"
  6. "confrontation-training/models"
  7. "gorm.io/gorm"
  8. )
  9. type UserService struct {
  10. }
  11. // FindUserByPhone find by phone
  12. func (u *UserService) FindUserByPhone(phone string) (models.User, int64) {
  13. var user models.User
  14. count := global.Db.Where("phone = ?", phone).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. Phone: user.Phone,
  24. }
  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(" phone = ? and password = ? and role = ?", userLogin.Phone, 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) FindUserByPhoneAndRole(phone string, role uint8) *models.User {
  37. var user models.User
  38. rows := global.Db.Where(" phone = ? and role = ?", phone, role).First(&user).RowsAffected
  39. if rows == 0 {
  40. return nil
  41. } else {
  42. return &user
  43. }
  44. }
  45. func (u *UserService) RestPassword(phone string) *gorm.DB {
  46. user, count := u.FindUserByPhone(phone)
  47. if count <= 0 {
  48. return nil
  49. }
  50. userUpdate := models.User{
  51. Password: constant.DefaultPassword,
  52. }
  53. userUpdate.ID = user.ID
  54. result := global.Db.Updates(&userUpdate)
  55. return result
  56. }
  57. func (u *UserService) GetUserList(param models.UserListParam) ([]models.User, int64) {
  58. query := models.User{
  59. Role: param.Role,
  60. }
  61. if len(param.UserName) > 0 {
  62. query.UserName = param.UserName
  63. }
  64. page := models.Page{
  65. PageNum: param.PageNum,
  66. PageSize: param.PageSize,
  67. }
  68. userList := make([]models.User, 0)
  69. rows := common.RestPage(page, "ct_users", query, "", &userList, &[]models.User{})
  70. return userList, rows
  71. }
  72. func (u *UserService) ChangePassword(id uint, newPassword string) int64 {
  73. userUpdate := models.User{
  74. Password: newPassword,
  75. }
  76. userUpdate.ID = id
  77. count := global.Db.Debug().Updates(&userUpdate).RowsAffected
  78. return count
  79. }