user_service.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package service
  2. import (
  3. "context"
  4. "errors"
  5. "github.com/jinzhu/gorm"
  6. "github.com/longjoy/micro-go-course/section08/user/dao"
  7. "github.com/longjoy/micro-go-course/section08/user/redis"
  8. "log"
  9. "time"
  10. )
  11. type UserInfoDTO struct {
  12. ID int64 `json:"id"`
  13. Username string `json:"username"`
  14. Email string `json:"email"`
  15. }
  16. type RegisterUserVO struct {
  17. Username string
  18. Password string
  19. Email string
  20. }
  21. var (
  22. ErrUserExisted = errors.New("user is existed")
  23. ErrPassword = errors.New("email and password are not match")
  24. ErrRegistering = errors.New("email is registering")
  25. )
  26. type UserService interface {
  27. // 登录接口
  28. Login(ctx context.Context, email, password string) (*UserInfoDTO, error)
  29. // 注册接口
  30. Register(ctx context.Context, vo *RegisterUserVO) (*UserInfoDTO, error)
  31. }
  32. type UserServiceImpl struct {
  33. userDAO dao.UserDAO
  34. }
  35. func MakeUserServiceImpl(userDAO dao.UserDAO) UserService {
  36. return &UserServiceImpl{
  37. userDAO: userDAO,
  38. }
  39. }
  40. func (userService *UserServiceImpl) Login(ctx context.Context, email, password string) (*UserInfoDTO, error) {
  41. user, err := userService.userDAO.SelectByEmail(email)
  42. if err == nil {
  43. if user.Password == password {
  44. return &UserInfoDTO{
  45. ID: user.ID,
  46. Username: user.Username,
  47. Email: user.Email,
  48. }, nil
  49. } else {
  50. return nil, ErrPassword
  51. }
  52. } else {
  53. log.Printf("err : %s", err)
  54. }
  55. return nil, err
  56. }
  57. func (userService UserServiceImpl) Register(ctx context.Context, vo *RegisterUserVO) (*UserInfoDTO, error) {
  58. lock := redis.GetRedisLock(vo.Email, time.Duration(5)*time.Second)
  59. err := lock.Lock()
  60. if err != nil {
  61. log.Printf("err : %s", err)
  62. return nil, ErrRegistering
  63. }
  64. defer lock.Unlock()
  65. existUser, err := userService.userDAO.SelectByEmail(vo.Email)
  66. if (err == nil && existUser == nil) || err == gorm.ErrRecordNotFound {
  67. newUser := &dao.UserEntity{
  68. Username: vo.Username,
  69. Password: vo.Password,
  70. Email: vo.Email,
  71. }
  72. err = userService.userDAO.Save(newUser)
  73. if err == nil {
  74. return &UserInfoDTO{
  75. ID: newUser.ID,
  76. Username: newUser.Username,
  77. Email: newUser.Email,
  78. }, nil
  79. }
  80. }
  81. if err == nil {
  82. err = ErrUserExisted
  83. }
  84. return nil, err
  85. }