package com.yupi.springbootinit.service.impl; import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.bean.BeanUtil; import com.yupi.springbootinit.common.ErrorCode; import com.yupi.springbootinit.exception.BusinessException; import com.yupi.springbootinit.model.dto.user.SystemUsersDTO; import com.yupi.springbootinit.model.entity.SystemUsers; import com.yupi.springbootinit.model.enums.CommonStatusEnum; import com.yupi.springbootinit.model.enums.LoginSceneEnum; import com.yupi.springbootinit.model.vo.user.SystemUsersVO; import com.yupi.springbootinit.service.SystemUsersService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor public class LoginService { private final SystemUsersService usersService; public SystemUsersVO login(LoginSceneEnum scene, SystemUsersDTO dto) { SystemUsers user = validateUser(dto); // 校验用户名、密码、状态、租户过期 checkRole(scene, user.getId()); // 按场景做角色校验 Long second = usersService.getTenantExpiredTime(dto.getTenantId()); // Sa-Token 登录 StpUtil.login(user.getId(), scene.getSaMode()); StpUtil.renewTimeout(second); SystemUsersVO vo = new SystemUsersVO(); BeanUtil.copyProperties(user, vo); vo.setTokenName(StpUtil.getTokenName()); vo.setTokenValue(StpUtil.getTokenValue()); return vo; } private SystemUsers validateUser(SystemUsersDTO dto) { SystemUsers user = usersService.getUserByUserName(dto.getUsername(), dto.getTenantId()); if (user == null) throw new BusinessException(ErrorCode.USERNAME_OR_PASSWORD_ERROR); if (!usersService.isPasswordMatch(dto.getPassword(), user.getPassword())) throw new BusinessException(ErrorCode.USERNAME_OR_PASSWORD_ERROR); if (CommonStatusEnum.isDisable(Integer.valueOf(user.getStatus()))) throw new BusinessException(ErrorCode.USER_DISABLE); if (usersService.isExpired(dto.getTenantId())) throw new BusinessException(ErrorCode.PACKAGE_EXPIRED); return user; } private void checkRole(LoginSceneEnum scene, Long userId) { Boolean pass = switch (scene) { case HOST -> usersService.checkCrawlRole(userId); case BIG_BROTHER -> usersService.checkbigBrotherlRole(userId); case AI_CHAT -> usersService.checkAiCHatLoginRole(userId); }; if (!pass) throw new BusinessException(ErrorCode.LOGIN_NOW_ALLOWED); } }