baoshiwei
2025-03-21 18e919bde3d925ee76fe29c7a6621c2716b1e4e4
ruoyi-admin/src/main/java/org/dromara/web/service/impl/SocialAuthStrategy.java
@@ -7,24 +7,30 @@
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import org.dromara.common.core.constant.SystemConstants;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.domain.model.PasswordLoginBody;
import org.dromara.common.core.domain.model.SocialLoginBody;
import org.dromara.common.core.enums.UserStatus;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.exception.user.UserException;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.social.config.properties.SocialProperties;
import org.dromara.common.social.keycloak.AuthKeycloakRequest;
import org.dromara.common.social.utils.SocialUtils;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.system.domain.SysClient;
import org.dromara.system.domain.SysSocial;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.bo.SysSocialBo;
import org.dromara.system.domain.bo.SysUserBo;
import org.dromara.system.domain.vo.SysClientVo;
import org.dromara.system.domain.vo.SysSocialVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.mapper.SysUserMapper;
@@ -59,16 +65,35 @@
     * @param client   客户端信息
     */
    @Override
    public LoginVo login(String body, SysClient client) {
        SocialLoginBody loginBody = JsonUtils.parseObject(body, SocialLoginBody.class);
        ValidatorUtils.validate(loginBody);
        AuthResponse<AuthUser> response = SocialUtils.loginAuth(
    public LoginVo login(String body, SysClientVo client) {
        // 如果bodyp字符串中包含login_type字段,则将body转为password登录
        AuthUser authUserData = null;
        String tenantId = null;
        if (body.contains("login_type")) {
            PasswordLoginBody passwordLoginBody = JsonUtils.parseObject(body, PasswordLoginBody.class);
            tenantId = passwordLoginBody.getTenantId();
            ValidatorUtils.validate(passwordLoginBody);
            AuthKeycloakRequest authRequest = SocialUtils.getAuthKeyloakRequest("keycloak", socialProperties);
            AuthToken accessToken = authRequest.getAccessToken(passwordLoginBody);
            authUserData = authRequest.getUserInfo(accessToken);
        } else {
            SocialLoginBody loginBody = JsonUtils.parseObject(body, SocialLoginBody.class);
            tenantId =loginBody.getTenantId();
                ValidatorUtils.validate(loginBody);
            AuthResponse<AuthUser> response = SocialUtils.loginAuth(
                loginBody.getSource(), loginBody.getSocialCode(),
                loginBody.getSocialState(), socialProperties);
        if (!response.ok()) {
            throw new ServiceException(response.getMsg());
            if (!response.ok()) {
                throw new ServiceException(response.getMsg());
            }
            authUserData = response.getData();
        }
        AuthUser authUserData = response.getData();
        if ("GITEE".equals(authUserData.getSource())) {
            // 如用户使用 gitee 登录顺手 star 给作者一点支持 拒绝白嫖
            HttpUtil.createRequest(Method.PUT, "https://gitee.com/api/v5/user/starred/dromara/RuoYi-Vue-Plus")
@@ -78,21 +103,68 @@
                    .formStr(MapUtil.of("access_token", authUserData.getToken().getAccessToken()))
                    .executeAsync();
        }
        if ("KEYCLOAK".equals(authUserData.getSource())) {
            // 新增KEYCLOAK用户自动创建逻辑
            String authId = authUserData.getSource() + authUserData.getUuid();
            List<SysSocialVo> list = sysSocialService.selectByAuthId(authId);
            if (CollUtil.isEmpty(list)) {
                // 自动创建新用户
                SysUser newUser = new SysUser();
                newUser.setUserName(authUserData.getUsername());
                newUser.setEmail(authUserData.getEmail());
                newUser.setNickName(authUserData.getNickname());
                newUser.setPassword("Initial123@"); // 初始密码需符合安全策略
                newUser.setStatus(SystemConstants.NORMAL);
                userMapper.insert(newUser); // 假设存在插入方法
                // 创建社交绑定记录
                SysSocialBo newSocial = new SysSocialBo();
                newSocial.setUserId(newUser.getUserId());
                newSocial.setUserName(newUser.getUserName());
                newSocial.setAuthId(authId);
                newSocial.setSource(authUserData.getSource());
                newSocial.setTenantId(newUser.getTenantId());
                newSocial.setOpenId(authUserData.getUuid());
                newSocial.setAccessToken(authUserData.getToken().getAccessToken());
                newSocial.setRefreshToken(authUserData.getToken().getRefreshToken());
                newSocial.setIdToken(authUserData.getToken().getIdToken());
                sysSocialService.insertByBo(newSocial); // 需确保服务有新增方法
                // 重新查询确保数据可用
                list = sysSocialService.selectByAuthId(authId);
            } else {
                // 更新社交绑定记录
                SysSocialBo socialBo = new SysSocialBo();
                socialBo.setId(list.get(0).getId());
                socialBo.setAccessToken(authUserData.getToken().getAccessToken());
                socialBo.setRefreshToken(authUserData.getToken().getRefreshToken());
                socialBo.setIdToken(authUserData.getToken().getIdToken());
                sysSocialService.updateByBo(socialBo);
            }
        }
        List<SysSocialVo> list = sysSocialService.selectByAuthId(authUserData.getSource() + authUserData.getUuid());
        if (CollUtil.isEmpty(list)) {
            throw new ServiceException("你还没有绑定第三方账号,绑定后才可以登录!");
        }
        Optional<SysSocialVo> opt = list.stream().filter(x -> x.getTenantId().equals(loginBody.getTenantId())).findAny();
        if (opt.isEmpty()) {
            throw new ServiceException("对不起,你没有权限登录当前租户!");
        SysSocialVo social;
        if (TenantHelper.isEnable()) {
            String finalTenantId = tenantId;
            Optional<SysSocialVo> opt = StreamUtils.findAny(list, x -> x.getTenantId().equals(finalTenantId));
            if (opt.isEmpty()) {
                throw new ServiceException("对不起,你没有权限登录当前租户!");
            }
            social = opt.get();
        } else {
            social = list.get(0);
        }
        SysSocialVo social = opt.get();
        // 查找用户
        SysUserVo user = loadUser(social.getTenantId(), social.getUserId());
        // 此处可根据登录用户的数据不同 自行创建 loginUser 属性不够用继承扩展就行了
        LoginUser loginUser = loginService.buildLoginUser(user);
        LoginUser loginUser = TenantHelper.dynamic(social.getTenantId(), () -> {
            SysUserVo user = loadUser(social.getUserId());
            // 此处可根据登录用户的数据不同 自行创建 loginUser 属性不够用继承扩展就行了
            return loginService.buildLoginUser(user);
        });
        loginUser.setClientKey(client.getClientKey());
        loginUser.setDeviceType(client.getDeviceType());
        SaLoginModel model = new SaLoginModel();
@@ -112,22 +184,16 @@
        return loginVo;
    }
    private SysUserVo loadUser(String tenantId, Long userId) {
        SysUser user = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .select(SysUser::getUserName, SysUser::getStatus)
                .eq(TenantHelper.isEnable(), SysUser::getTenantId, tenantId)
                .eq(SysUser::getUserId, userId));
    private SysUserVo loadUser(Long userId) {
        SysUserVo user = userMapper.selectVoById(userId);
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户:{} 不存在.", "");
            throw new UserException("user.not.exists", "");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
        } else if (SystemConstants.DISABLE.equals(user.getStatus())) {
            log.info("登录用户:{} 已被停用.", "");
            throw new UserException("user.blocked", "");
        }
        if (TenantHelper.isEnable()) {
            return userMapper.selectTenantUserByUserName(user.getUserName(), tenantId);
        }
        return userMapper.selectUserByUserName(user.getUserName());
        return user;
    }
}