package com.ltkj.framework.web.service; import javax.annotation.Resource; import cn.hutool.core.date.DateUnit; import cn.hutool.core.date.DateUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.ltkj.common.constant.CacheConstants; import com.ltkj.common.core.domain.entity.SysDept; import com.ltkj.common.exception.CustomException; import com.ltkj.common.exception.user.CaptchaException; import com.ltkj.common.exception.user.CaptchaExpireException; import com.ltkj.common.exception.user.SecretKeyException; 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.DictHosp; import com.ltkj.hosp.domain.TjCustomer; import com.ltkj.hosp.service.IDictHospService; import com.ltkj.hosp.service.ITjCustomerService; import com.ltkj.system.service.*; 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 org.springframework.util.DigestUtils; import java.util.Date; 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; @Resource private IDictHospService hospService; @Autowired private ISysDeptService deptService; @Autowired private SysParametersDisposeService parametersDisposeService; @Autowired private ISysConfigService configService; // 是否允许账户多终端同时登录(true允许 false不允许) @Value("${token.soloLogin}") private boolean soloLogin; @Value("${token.secret_key}") private String secret; @Value("${token.secret_key_login}") private boolean secretKeyLogin; /** * 登录验证 * * @param username 用户名 * @param password 密码 * @return 结果 */ public String login(String username, String password, Boolean type,String code,String uuid) { String aSwitch = configService.selectConfigByKey("captcha_switch"); if(null !=aSwitch && aSwitch.equalsIgnoreCase("Y")){ 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 { //登录密码解密 String s = RsaUtils.decryptByPrivateKey(password); // String s = password; if(username.equals("10001")){ s=username+s; } UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,s); 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 (secretKeyLogin) { Long userId =loginUser.getUser().getUserId(); SysUser user = userService.getById(userId); if(null !=user && null !=user.getDeptId()){ SysDept sysDept = deptService.getById(user.getDeptId()); if (null != sysDept) { DictHosp dictHosp = hospService.getById(sysDept.getHospId()); if(null !=dictHosp){ loginUser.setHospName(dictHosp.getHospAreaName()); if(!SecurityUtils.isAdmin(user.getUserId())){ if(dictHosp.getSecretKey() != null && dictHosp.getExpirationTime() != null){ if (!SecurityUtils.matchesMallMerchantSecretKey(secret,dictHosp.getHospAreaId(),dictHosp.getHospAreaName(), dictHosp.getExpirationTime(),dictHosp.getSecretKey()) || new Date().after(DateUtil.endOfDay(dictHosp.getExpirationTime()))) { throw new SecretKeyException("商家已过期请续费使用"); } long between = DateUtil.between(new Date(), DateUtil.endOfDay(dictHosp.getExpirationTime()), DateUnit.DAY); if(between<=30){ loginUser.setMessage("还有 "+between+" 天到期 请注意续费! 以免影响正常使用!"); }else { loginUser.setMessage(null); } }else { throw new SecretKeyException("请缴费使用"); } } } } }else { throw new CustomException("请绑定商家"); } } // 限制账户不允许多终端登录 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 sfzh, String password, Boolean type,String code,String uuid) { String aSwitch = configService.selectConfigByKey("captcha_switch"); if(null !=aSwitch && aSwitch.equalsIgnoreCase("Y")){ 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,sfzh, password); if (loginUser == null) { return null; } // 限制账户不允许多终端登录 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 sfzh, String password) { LambdaQueryWrapper wq = new LambdaQueryWrapper<>(); wq.eq(TjCustomer::getCusPhone, username); wq.eq(TjCustomer::getCusIdcard, sfzh); List customerList = customerService.list(wq); if (null == customerList || customerList.isEmpty()) { //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); // } password = DigestUtils.md5DigestAsHex(password.getBytes()); if (password.equals(tjCustomer.getCusPassword())){ 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; } }