golang-im聊天
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

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