|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- package service
-
- import (
- "context"
- "egg-im/internal/business/comm/db"
- "egg-im/internal/business/domain/user/model"
- "egg-im/internal/business/domain/user/repo"
- "egg-im/pkg/gerrors"
- "egg-im/pkg/pb"
- "egg-im/pkg/rpc"
- "egg-im/pkg/util"
- "errors"
- "strconv"
- "time"
- )
-
- type authService struct{}
-
- var AuthService = new(authService)
-
- // SignIn 登录
- func (*authService) SignIn(ctx context.Context, phoneNumber, code string, deviceId int64, pushAlia, nickname, avatarUrl string) (bool, int64, string, error) {
- if !Verify(phoneNumber, code) {
- return false, 0, "", gerrors.ErrBadCode
- }
-
- user, err := repo.UserRepo.GetByPhoneNumber(phoneNumber)
- if err != nil {
- return false, 0, "", err
- }
-
- var isNew = false
- if user == nil {
- user = &model.User{
- PhoneNumber: phoneNumber,
- Nickname: nickname,
- AvatarUrl: avatarUrl,
- CreateTime: time.Now(),
- UpdateTime: time.Now(),
- }
- err := repo.UserRepo.Save(user)
- if err != nil {
- return false, 0, "", err
- }
- isNew = true
- }
-
- resp, err := rpc.GetLogicIntClient().GetDevice(ctx, &pb.GetDeviceReq{DeviceId: deviceId})
- if err != nil {
- return false, 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, "", err
- }
-
- if pushAlia != "" {
- userPushForJg, err := db.DbUserPushForJg.UserPushForJgGetOne(strconv.FormatInt(user.Id, 10))
- if err != nil {
- return false, 0, "", err
- }
- if userPushForJg == nil {
- save := db.DbUserPushForJg.UserPushForJgInsert(user.Id, pushAlia)
- if !save {
- return false, 0, "", errors.New("插入user_push_for_jg记录失败")
- }
- } else {
- update := db.DbUserPushForJg.UserPushForJgUpdate(user.Id, pushAlia)
- if !update {
- return false, 0, "", errors.New("修改user_push_for_jg记录失败")
- }
- }
- }
- return isNew, user.Id, token, 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
- }
|