package service import ( "context" "errors" "gim/internal/business/comm/db" "gim/internal/business/domain/user/model" "gim/internal/business/domain/user/repo" "gim/pkg/gerrors" "gim/pkg/pb" "gim/pkg/rpc" "gim/pkg/util" "strconv" "time" ) type authService struct{} var AuthService = new(authService) // SignIn 登录 func (*authService) SignIn(ctx context.Context, phoneNumber, code string, masterId, deviceId int64, pushAlia string) (bool, int64, string, int64, error) { if !Verify(phoneNumber, code) { return false, 0, "", 0, gerrors.ErrBadCode } user, err := repo.UserRepo.GetByPhoneNumber(phoneNumber, masterId) if err != nil { return false, 0, "", 0, err } var isNew = false if user == nil { user = &model.User{ PhoneNumber: phoneNumber, MasterId: masterId, CreateTime: time.Now(), UpdateTime: time.Now(), } err := repo.UserRepo.Save(user) if err != nil { return false, 0, "", 0, err } isNew = true } resp, err := rpc.GetLogicIntClient().GetDevice(ctx, &pb.GetDeviceReq{DeviceId: deviceId}) if err != nil { return false, 0, "", 0, err } // 方便测试 //token := "0" token := util.RandString(40) err = repo.AuthRepo.Set(user.Id, resp.Device.DeviceId, model.Device{ Type: resp.Device.Type, Token: token, Expire: time.Now().AddDate(0, 3, 0).Unix(), }) if err != nil { return false, 0, "", 0, err } if pushAlia != "" { userPushForJg, err := db.DbUserPushForJg.UserPushForJgGetOne(strconv.FormatInt(user.Id, 10), masterId) if err != nil { return false, 0, "", 0, err } if userPushForJg == nil { save := db.DbUserPushForJg.UserPushForJgInsert(user.Id, masterId, pushAlia) if !save { return false, 0, "", 0, errors.New("插入user_push_for_jg记录失败") } } else { update := db.DbUserPushForJg.UserPushForJgUpdate(user.Id, masterId, pushAlia) if !update { return false, 0, "", 0, errors.New("修改user_push_for_jg记录失败") } } } return isNew, user.Id, token, masterId, nil } func Verify(phoneNumber, code string) bool { // 假装他成功了 return true } // Auth 验证用户是否登录 func (*authService) Auth(ctx context.Context, userId, deviceId int64, token string) error { device, err := repo.AuthRepo.Get(userId, deviceId) if err != nil { return err } if device == nil { return gerrors.ErrUnauthorized } if device.Expire < time.Now().Unix() { return gerrors.ErrUnauthorized } if device.Token != token { return gerrors.ErrUnauthorized } return nil }