package com.zhitan.framework.web.service; import cn.hutool.core.collection.CollUtil; import com.zhitan.common.config.keycloak.AuthKeycloakRequest; import com.zhitan.common.constant.CacheConstants; import com.zhitan.common.constant.Constants; import com.zhitan.common.constant.UserConstants; import com.zhitan.common.core.domain.entity.SysUser; import com.zhitan.common.core.domain.model.LoginUser; import com.zhitan.common.core.redis.RedisCache; import com.zhitan.common.exception.ServiceException; import com.zhitan.common.exception.user.*; import com.zhitan.common.utils.DateUtils; import com.zhitan.common.utils.MessageUtils; import com.zhitan.common.utils.SocialUtils; import com.zhitan.common.utils.StringUtils; import com.zhitan.common.utils.ip.IpUtils; import com.zhitan.framework.manager.AsyncManager; import com.zhitan.framework.manager.factory.AsyncFactory; import com.zhitan.framework.security.context.AuthenticationContextHolder; import com.zhitan.framework.security.single.SingleAuthenticationToken; import com.zhitan.system.domain.SysSocial; import com.zhitan.system.domain.bo.SysSocialBo; import com.zhitan.system.domain.vo.SysSocialVo; import com.zhitan.system.service.ISysConfigService; import com.zhitan.system.service.ISysSocialService; import com.zhitan.system.service.ISysUserService; import me.zhyd.oauth.model.AuthCallback; import me.zhyd.oauth.model.AuthResponse; import me.zhyd.oauth.model.AuthToken; import me.zhyd.oauth.model.AuthUser; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.List; /** * 登录校验方法 * * @author zhitan */ @Component public class SysLoginService { @Resource private TokenService tokenService; @Resource private AuthenticationManager authenticationManager; @Resource private RedisCache redisCache; @Resource private ISysUserService userService; @Resource private ISysConfigService configService; @Resource private ISysSocialService sysSocialService; @Resource private SysPermissionService permissionService; /** * 登录验证 * * @param username 用户名 * @param password 密码 * @param code 验证码 * @param uuid 唯一标识 * @return 结果 */ public String login(String username, String password, String code, String uuid) { // 验证码校验 // validateCaptcha(username, code, uuid); // 登录前置校验 loginPreCheck(username, password); // 用户验证 Authentication authentication = null; try { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password); AuthenticationContextHolder.setContext(authenticationToken); // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername authentication = authenticationManager.authenticate(authenticationToken); } catch (Exception e) { if (e instanceof BadCredentialsException) { AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); throw new UserPasswordNotMatchException(); } else { AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, Constants.LOGIN_FAIL, e.getMessage())); throw new ServiceException(e.getMessage()); } } finally { AuthenticationContextHolder.clearContext(); } AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"))); LoginUser loginUser = (LoginUser) authentication.getPrincipal(); recordLoginInfo(loginUser.getUserId()); // 生成token return tokenService.createToken(loginUser); } public String loginByCode(String code,String state) { AuthKeycloakRequest authRequest = SocialUtils.getAuthKeyloakRequest(); // AuthToken accessToken = authRequest.getAccessToken(passwordLoginBody); AuthCallback callback = new AuthCallback(); callback.setCode(code); callback.setState(state); AuthResponse res = authRequest.login(callback); AuthUser authUserData = res.getData(); // 新增KEYCLOAK用户自动创建逻辑 String authId = authUserData.getSource() + authUserData.getUuid(); List 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("0"); userService.insertUser(newUser); // 假设存在插入方法 // 创建社交绑定记录 SysSocialBo newSocial = new SysSocialBo(); newSocial.setUserId(newUser.getUserId()); newSocial.setUserName(newUser.getUserName()); newSocial.setAuthId(authId); newSocial.setSource(authUserData.getSource()); 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 = sysSocialService.selectByAuthId(authUserData.getSource() + authUserData.getUuid()); if (CollUtil.isEmpty(list)) { throw new ServiceException("你还没有绑定第三方账号,绑定后才可以登录!"); } LoginUser loginUser = new LoginUser(); loginUser.setUser(userService.selectUserById(list.get(0).getUserId())); loginUser.setUserId(list.get(0).getUserId()); loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser())); // 生成token return tokenService.createToken(loginUser); } /** * 校验验证码 * * @param username 用户名 * @param code 验证码 * @param uuid 唯一标识 * @return 结果 */ public void validateCaptcha(String username, String code, String uuid) { boolean captchaEnabled = configService.selectCaptchaEnabled(); if (captchaEnabled) { String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, ""); String captcha = redisCache.getCacheObject(verifyKey); redisCache.deleteObject(verifyKey); if (captcha == null) { AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"))); throw new CaptchaExpireException(); } if (!code.equalsIgnoreCase(captcha)) { AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"))); throw new CaptchaException(); } } } /** * 登录前置校验 * @param username 用户名 * @param password 用户密码 */ public void loginPreCheck(String username, String password) { // 用户名或密码为空 错误 if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) { AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null"))); throw new UserNotExistsException(); } // 密码如果不在指定范围内 错误 if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) { AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); throw new UserPasswordNotMatchException(); } // 用户名不在指定范围内 错误 if (username.length() < UserConstants.USERNAME_MIN_LENGTH || username.length() > UserConstants.USERNAME_MAX_LENGTH) { AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); throw new UserPasswordNotMatchException(); } // IP黑名单校验 String blackStr = configService.selectConfigByKey("sys.login.blackIPList"); if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) { AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked"))); throw new BlackListException(); } } /** * 记录登录信息 * * @param userId 用户ID */ public void recordLoginInfo(Long userId) { SysUser sysUser = new SysUser(); sysUser.setUserId(userId); sysUser.setLoginIp(IpUtils.getIpAddr()); sysUser.setLoginDate(DateUtils.getNowDate()); userService.updateUserProfile(sysUser); } /** * 登录验证 * @param username * @return 结果 */ public String loginNoCode(String username) { // 用户验证 Authentication authentication = null; try { authentication = authenticationManager .authenticate(new SingleAuthenticationToken(username)); } catch (Exception e) { if (e instanceof BadCredentialsException) { AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); throw new UserPasswordNotMatchException(); } else { AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, Constants.LOGIN_FAIL, e.getMessage())); throw new ServiceException(e.getMessage()); } } AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"))); LoginUser loginUser = (LoginUser) authentication.getPrincipal(); recordLoginInfo(loginUser.getUserId()); // 生成token return tokenService.createToken(loginUser); } }