package logic import ( "context" "database/sql" "errors" "github.com/zero-ppanel/zero-ppanel/apps/rpc/core/core" "github.com/zero-ppanel/zero-ppanel/apps/rpc/core/internal/repo" "github.com/zero-ppanel/zero-ppanel/apps/rpc/core/internal/svc" "github.com/zero-ppanel/zero-ppanel/pkg/xerr" "github.com/zeromicro/go-zero/core/logx" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) type DeviceLoginLogic struct { ctx context.Context svcCtx *svc.ServiceContext logx.Logger } func NewDeviceLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeviceLoginLogic { return &DeviceLoginLogic{ ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx), } } // DeviceLogin 设备登录:查设备 → 不存在则注册 → 返回用户信息 func (l *DeviceLoginLogic) DeviceLogin(in *core.DeviceLoginReq) (*core.DeviceLoginResp, error) { // 1. 查询设备 device, err := l.svcCtx.DeviceRepo.FindDeviceByIdentifier(l.ctx, in.Identifier) if err != nil && !errors.Is(err, sql.ErrNoRows) { l.Errorf("FindDeviceByIdentifier error: %v", err) return nil, status.Error(codes.Code(xerr.DatabaseQueryError), "查询设备失败") } var userID int64 var isNewUser bool var isAdmin bool if errors.Is(err, sql.ErrNoRows) || device == nil { // 2. 设备不存在,创建用户+设备 userID, err = l.svcCtx.DeviceRepo.CreateUserWithDevice(l.ctx, repo.CreateUserWithDeviceParams{ Identifier: in.Identifier, UserAgent: in.UserAgent, IP: in.Ip, ShortCode: in.ShortCode, }) if err != nil { l.Errorf("CreateUserWithDevice error: %v", err) return nil, status.Error(codes.Code(xerr.DatabaseInsertError), "创建用户设备失败") } isNewUser = true // 记录注册日志 _ = l.svcCtx.DeviceRepo.InsertLoginLog(l.ctx, repo.LoginLogParams{ UserID: userID, Method: "device", IP: in.Ip, UserAgent: in.UserAgent, Success: true, }) } else { // 3. 设备存在,检查是否启用 if !device.Enabled { return nil, status.Error(codes.Code(xerr.DeviceNotEnabled), "设备已禁用") } userID = device.UserID // 查用户信息 user, err := l.svcCtx.DeviceRepo.FindUserByID(l.ctx, userID) if err != nil { l.Errorf("FindUserByID error: %v", err) return nil, status.Error(codes.Code(xerr.DatabaseQueryError), "查询用户失败") } if !user.Enable { return nil, status.Error(codes.Code(xerr.UserDisabled), "用户已禁用") } isAdmin = user.IsAdmin } // 4. 记录登录日志 _ = l.svcCtx.DeviceRepo.InsertLoginLog(l.ctx, repo.LoginLogParams{ UserID: userID, Method: "device", IP: in.Ip, UserAgent: in.UserAgent, Success: true, }) return &core.DeviceLoginResp{ UserId: userID, IsAdmin: isAdmin, IsDisabled: false, IsNewUser: isNewUser, }, nil }