package com.ltkj.framework.web.service; import javax.annotation.Resource; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.ltkj.common.constant.CacheConstants; import com.ltkj.common.exception.user.CaptchaException; import com.ltkj.common.exception.user.CaptchaExpireException; import com.ltkj.common.utils.*; import com.ltkj.common.utils.sign.RsaUtils; import com.ltkj.framework.config.JwtUtils; import com.ltkj.framework.config.UserHoder; import com.ltkj.hosp.domain.TjCustomer; import com.ltkj.hosp.service.ITjCustomerService; import com.ltkj.system.service.ISysMenuService; import com.ltkj.system.service.SysParametersDisposeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; 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 com.ltkj.common.constant.Constants; import com.ltkj.common.core.domain.entity.SysUser; import com.ltkj.common.core.domain.model.LoginUser; import com.ltkj.common.core.redis.RedisCache; import com.ltkj.common.exception.ServiceException; import com.ltkj.common.exception.user.UserPasswordNotMatchException; import com.ltkj.common.utils.ip.IpUtils; import com.ltkj.framework.manager.AsyncManager; import com.ltkj.framework.manager.factory.AsyncFactory; import com.ltkj.framework.security.context.AuthenticationContextHolder; import com.ltkj.system.service.ISysUserService; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 登录校验方法 * * @author ltkj */ @Component public class SysLoginService { @Autowired private TokenService tokenService; @Resource private AuthenticationManager authenticationManager; @Autowired private RedisCache redisCache; @Autowired private ISysUserService userService; @Resource private ITjCustomerService customerService; @Resource private ISysMenuService menuService; @Autowired private SysParametersDisposeService parametersDisposeService; // 是否允许账户多终端同时登录(true允许 false不允许) @Value("${token.soloLogin}") private boolean soloLogin; /** * 登录验证 * * @param username 用户名 * @param password 密码 * @return 结果 */ public String login(String username, String password, Boolean type,String code,String uuid) { String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid; String captcha = redisCache.getCacheObject(verifyKey); redisCache.deleteObject(verifyKey); if (captcha == null) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"))); throw new CaptchaExpireException(); } if (!code.equalsIgnoreCase(captcha)) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"))); throw new CaptchaException(); } // 用户验证 Authentication authentication = null; try { //登录密码解密 UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, RsaUtils.decryptByPrivateKey(password)); //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.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); throw new UserPasswordNotMatchException(); } else { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage())); throw new ServiceException(e.getMessage()); } } finally { AuthenticationContextHolder.clearContext(); } AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"))); LoginUser loginUser = (LoginUser) authentication.getPrincipal(); recordLoginInfo(Long.valueOf(loginUser.getUserId())); // 限制账户不允许多终端登录 if (!soloLogin) { // 如果用户不允许多终端同时登录,清除缓存信息 String userIdKey = Constants.LOGIN_USERID_KEY + loginUser.getUser().getUserId(); String userKey = redisCache.getCacheObject(userIdKey); if (StringUtils.isNotEmpty(userKey)) { if (!type) { return null; } else { redisCache.deleteObject(userIdKey); redisCache.deleteObject(userKey); } } } UserHoder.setLoginUser(loginUser); // 生成token return tokenService.createToken(loginUser); } /** * 记录登录信息 * * @param userId 用户ID */ public void recordLoginInfo(Long userId) { SysUser sysUser = new SysUser(); sysUser.setUserId(userId); sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest())); sysUser.setLoginDate(DateUtils.getNowDate()); userService.updateUserProfile(sysUser); } /** * 客户登录验证 * * @param username 手机号 * @param password 密码 * @return 结果 */ public String Cuslogin(String username, String password, Boolean type,String code,String uuid) { String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid; String captcha = redisCache.getCacheObject(verifyKey); redisCache.deleteObject(verifyKey); if (captcha == null) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"))); throw new CaptchaExpireException(); } if (!code.equalsIgnoreCase(captcha)) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"))); throw new CaptchaException(); } LoginUser loginUser = loadCusByCusname(username, password); if (loginUser == null) { return "用户名或密码错误"; } // 限制账户不允许多终端登录 if (!soloLogin) { // 如果用户不允许多终端同时登录,清除缓存信息 String userIdKey = Constants.LOGIN_USERID_KEY + loginUser.getUserId(); String userKey = redisCache.getCacheObject(userIdKey); if (StringUtils.isNotEmpty(userKey)) { if (!type) { return null; } else { redisCache.deleteObject(userIdKey); redisCache.deleteObject(userKey); } } } // 生成token return tokenService.createToken(loginUser); } public LoginUser loadCusByCusname(String username, String password) { LambdaQueryWrapper wq = new LambdaQueryWrapper<>(); wq.eq(TjCustomer::getCusPhone, username); List customerList = customerService.list(wq); if (null == customerList || customerList.size() == 0) { //throw new ServiceException("登录用户:" + username + " 不存在"); throw new ServiceException("账户或密码错误,请检查!"); } for (TjCustomer tjCustomer : customerList) { try { password = RsaUtils.decryptByPrivateKey(password); boolean b = SecurityUtils.matchesPassword(password, tjCustomer.getCusPassword()); if (b) { return createLoginCus(tjCustomer); } } catch (Exception e) { throw new RuntimeException(e); } } return null; } public LoginUser createLoginCus(TjCustomer customer) { LoginUser loginCus = new LoginUser(); SysUser user1 = new SysUser(); user1.setNickName(customer.getCusName()); loginCus.setUser(user1); loginCus.setUserId("cus" + customer.getCusId()); loginCus.setPermissions(menuService.selectMenuPermsByRoleId(customer.getRole())); return loginCus; } }