hi-server/internal/logic/public/user/unbindDeviceLogic.go
shanshanzhong 6c8f22adc8
Some checks failed
Build docker and publish / build (20.15.1) (push) Failing after 7m49s
fix gitea workflow path and runner label
2026-03-04 04:28:54 -08:00

82 lines
2.6 KiB
Go

package user
import (
"context"
"fmt"
"github.com/perfect-panel/server/internal/config"
"github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/constant"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
"gorm.io/gorm"
)
type UnbindDeviceLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// Unbind Device
func NewUnbindDeviceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UnbindDeviceLogic {
return &UnbindDeviceLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *UnbindDeviceLogic) UnbindDevice(req *types.UnbindDeviceRequest) error {
userInfo, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
if !ok {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
}
device, err := l.svcCtx.UserModel.FindOneDevice(l.ctx, req.Id)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DeviceNotExist), "find device")
}
if device.UserId != userInfo.Id {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "device not belong to user")
}
currentSessionID, _ := l.ctx.Value(constant.CtxKeySessionID).(string)
return l.logoutUnbind(userInfo, device, currentSessionID)
}
func (l *UnbindDeviceLogic) logoutUnbind(userInfo *user.User, device *user.Device, currentSessionID string) error {
err := l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
exitHelper := newFamilyExitHelper(l.ctx, l.svcCtx)
return exitHelper.removeUserFromActiveFamily(tx, userInfo.Id, true)
})
if err != nil {
return err
}
l.svcCtx.DeviceManager.KickDevice(device.UserId, device.Identifier)
if currentSessionID != "" {
sessionIdCacheKey := fmt.Sprintf("%v:%v", config.SessionIdKey, currentSessionID)
_ = l.svcCtx.Redis.Del(l.ctx, sessionIdCacheKey).Err()
sessionsKey := fmt.Sprintf("%s%v", config.UserSessionsKeyPrefix, userInfo.Id)
_ = l.svcCtx.Redis.ZRem(l.ctx, sessionsKey, currentSessionID).Err()
}
deviceCacheKey := fmt.Sprintf("%v:%v", config.DeviceCacheKeyKey, device.Identifier)
if sessionId, redisErr := l.svcCtx.Redis.Get(l.ctx, deviceCacheKey).Result(); redisErr == nil && sessionId == currentSessionID {
_ = l.svcCtx.Redis.Del(l.ctx, deviceCacheKey).Err()
}
if clearErr := l.svcCtx.UserModel.ClearUserCache(l.ctx, userInfo); clearErr != nil {
l.Errorw("clear user cache failed", logger.Field("user_id", userInfo.Id), logger.Field("error", clearErr.Error()))
}
return nil
}