golang-im聊天
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.
 
 
 
 

87 lines
1.7 KiB

  1. package service
  2. import (
  3. "context"
  4. "gim/internal/business/domain/user/model"
  5. "gim/internal/business/domain/user/repo"
  6. "gim/pkg/gerrors"
  7. "gim/pkg/pb"
  8. "gim/pkg/rpc"
  9. "time"
  10. )
  11. type authService struct{}
  12. var AuthService = new(authService)
  13. // SignIn 登录
  14. func (*authService) SignIn(ctx context.Context, phoneNumber, code string, deviceId int64) (bool, int64, string, error) {
  15. if !Verify(phoneNumber, code) {
  16. return false, 0, "", gerrors.ErrBadCode
  17. }
  18. user, err := repo.UserRepo.GetByPhoneNumber(phoneNumber)
  19. if err != nil {
  20. return false, 0, "", err
  21. }
  22. var isNew = false
  23. if user == nil {
  24. user = &model.User{
  25. PhoneNumber: phoneNumber,
  26. CreateTime: time.Now(),
  27. UpdateTime: time.Now(),
  28. }
  29. err := repo.UserRepo.Save(user)
  30. if err != nil {
  31. return false, 0, "", err
  32. }
  33. isNew = true
  34. }
  35. resp, err := rpc.GetLogicIntClient().GetDevice(ctx, &pb.GetDeviceReq{DeviceId: deviceId})
  36. if err != nil {
  37. return false, 0, "", err
  38. }
  39. // 方便测试
  40. token := "0"
  41. //token := util.RandString(40)
  42. err = repo.AuthRepo.Set(user.Id, resp.Device.DeviceId, model.Device{
  43. Type: resp.Device.Type,
  44. Token: token,
  45. Expire: time.Now().AddDate(0, 3, 0).Unix(),
  46. })
  47. if err != nil {
  48. return false, 0, "", err
  49. }
  50. return isNew, user.Id, token, nil
  51. }
  52. func Verify(phoneNumber, code string) bool {
  53. // 假装他成功了
  54. return true
  55. }
  56. // Auth 验证用户是否登录
  57. func (*authService) Auth(ctx context.Context, userId, deviceId int64, token string) error {
  58. device, err := repo.AuthRepo.Get(userId, deviceId)
  59. if err != nil {
  60. return err
  61. }
  62. if device == nil {
  63. return gerrors.ErrUnauthorized
  64. }
  65. if device.Expire < time.Now().Unix() {
  66. return gerrors.ErrUnauthorized
  67. }
  68. if device.Token != token {
  69. return gerrors.ErrUnauthorized
  70. }
  71. return nil
  72. }