package com.ycl.service.user.impl; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateTime; import cn.hutool.core.util.PageUtil; import cn.hutool.core.util.StrUtil; import com.alibaba.druid.sql.PagerUtils; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.ycl.bo.AdminUserDetails; import com.ycl.dto.UmsAdminParam; import com.ycl.dto.user.UmsUserDto1; import com.ycl.dto.UpdateAdminPasswordParam; import com.ycl.entity.depart.UmsDepart; import com.ycl.entity.user.*; import com.ycl.exception.ApiException; import com.ycl.exception.Asserts; import com.ycl.mapper.user.*; import com.ycl.service.depart.UmsDepartService; import com.ycl.service.redis.RedisService; import com.ycl.service.user.UmsAdminCacheService; import com.ycl.service.user.UmsAdminRoleRelationService; import com.ycl.service.user.UmsAdminService; import com.ycl.utils.JwtTokenUtil; import com.ycl.utils.SpringUtil; import com.ycl.utils.common.LiveTimeMillisecond; import com.ycl.utils.common.MacUtils; import com.ycl.utils.redis.RedisKey; import com.ycl.vo.user.UserVO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.util.*; import java.util.function.Consumer; import java.util.stream.Collectors; /** * 后台管理员管理Service实现类 * Created by macro on 2018/4/26. */ @Service public class UmsAdminServiceImpl extends ServiceImpl implements UmsAdminService { private static final Logger LOGGER = LoggerFactory.getLogger(UmsAdminServiceImpl.class); @Autowired private JwtTokenUtil jwtTokenUtil; @Autowired private PasswordEncoder passwordEncoder; @Resource private UmsAdminLoginLogMapper umsAdminLoginLogMapper; @Resource private UmsAdminRoleRelationService umsAdminRoleRelationService; @Resource private UmsRoleMapper umsRoleMapper; @Resource private UmsResourceMapper umsResourceMapper; @Resource private UmsDepartService departService; @Resource private RedisService redisService; @Resource private UmsDepartManageMapper umsDepartManageMapper; @Resource UmsRoleMenuRelationMapper umsRoleMenuRelationMapper; @Resource AdminMenuRelationMapper adminMenuRelationMapper; @Resource UmsMenuMapper umsMenuMapper; @Override public UmsAdmin getAdminByUsername(String username) { // UmsAdmin admin = getCacheService().getAdmin(username); // if (admin != null) return admin; UmsAdmin admin = null; QueryWrapper wrapper = new QueryWrapper<>(); wrapper.lambda().eq(UmsAdmin::getUsername, username); List adminList = list(wrapper); if (adminList != null && adminList.size() > 0) { admin = adminList.get(0); getCacheService().setAdmin(admin); return admin; } return null; } @Override @Transactional(rollbackFor = Exception.class) public UmsAdmin register(UmsAdminParam umsAdminParam) { UmsAdmin umsAdmin = new UmsAdmin(); BeanUtils.copyProperties(umsAdminParam, umsAdmin); umsAdmin.setCreateTime(new Date()); umsAdmin.setStatus(1); // umsAdmin.setMacAddress(MacUtils.getMac()); //查询是否有相同用户名的用户 QueryWrapper wrapper = new QueryWrapper<>(); wrapper.lambda().eq(UmsAdmin::getUsername, umsAdmin.getUsername()); if (umsAdmin.getId() != null) { wrapper.lambda().ne(UmsAdmin::getId, umsAdmin.getId()); } List umsAdminList = list(wrapper); if (umsAdminList.size() > 0) { return null; } //将密码进行加密操作 String encodePassword = passwordEncoder.encode(umsAdmin.getPassword()); if (umsAdmin.getId() == null && !umsAdmin.getPassword().matches("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{8,16}$")) { Asserts.fail("密码长度8到16位且密码中的字符必须包含字母(大写或者小写)和必须包含数字,不能包含空格"); } if (umsAdmin.getUsername().equals(umsAdmin.getPassword())) { Asserts.fail("密码不能和登录名完全一致"); } umsAdmin.setPassword(encodePassword); if (umsAdminParam.getDays() != null) { Date date = new Date(); Calendar calendar = new GregorianCalendar(); calendar.setTime(date); // 把日期往后增加一天,整数 往后推,负数往前移动 calendar.add(Calendar.DATE, umsAdminParam.getDays()); // 这个时间就是日期往后推一天的结果 date = calendar.getTime(); umsAdmin.setExpirationDate(date); } else { umsAdmin.setExpirationDate(new Date(2090,1,1)); } if (umsAdmin.getId() != null) { baseMapper.updateById(umsAdmin); } else { baseMapper.insert(umsAdmin); } LambdaQueryWrapper deleteWrapper = new QueryWrapper().lambda() .eq(UmsAdminRoleRelation::getAdminId, umsAdmin.getId()); umsAdminRoleRelationService.remove(deleteWrapper); //添加角色授权 List ids = umsAdminParam.getRoleIds(); if (!ids.isEmpty()) { List roleIds = new ArrayList<>(); for (Long id : ids) { UmsAdminRoleRelation urr = new UmsAdminRoleRelation(); urr.setAdminId(umsAdmin.getId()); urr.setRoleId(id); roleIds.add(urr); } umsAdminRoleRelationService.saveBatch(roleIds); } umsDepartManageMapper.deletedByDepartId(umsAdmin.getId()); //添加部门 UmsDepartManage departManage = new UmsDepartManage(); departManage.setUserId(umsAdmin.getId()); departManage.setDepartId(umsAdminParam.getDepartmentId()); departManage.setCreateTime(new Date()); departManage.setUpdateTime(new Date()); umsDepartManageMapper.insert(departManage); // baseMapper.updateById(umsAdmin); return umsAdmin; } @Override public void importExcl(UmsAdminParam umsAdminParam) { UmsAdmin umsAdmin = new UmsAdmin(); BeanUtils.copyProperties(umsAdminParam, umsAdmin); umsAdmin.setCreateTime(new Date()); umsAdmin.setStatus(1); umsAdmin.setMacAddress(MacUtils.getMac()); //查询是否有相同用户名的用户 QueryWrapper wrapper = new QueryWrapper<>(); wrapper.lambda().eq(UmsAdmin::getUsername, umsAdmin.getUsername()); List umsAdminList = list(wrapper); if (umsAdminList.size() > 0) { throw new RuntimeException("用户已存在"); } //将密码进行加密操作 String encodePassword = passwordEncoder.encode(umsAdmin.getPassword()); if (!umsAdmin.getPassword().matches("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{8,16}$")) { Asserts.fail("密码长度8到16位且密码中的字符必须包含字母(大写或者小写)和必须包含数字,不能包含空格"); } if (umsAdmin.getUsername().equals(umsAdmin.getPassword())) { Asserts.fail("密码不能和登录名完全一致"); } umsAdmin.setPassword(encodePassword); baseMapper.insert(umsAdmin); //添加角色授权 List ids = umsAdminParam.getRoleIds(); if (!ids.isEmpty()) { List roleIds = new ArrayList<>(); for (Long id : ids) { UmsAdminRoleRelation urr = new UmsAdminRoleRelation(); urr.setAdminId(umsAdmin.getId()); urr.setRoleId(id); roleIds.add(urr); } umsAdminRoleRelationService.saveBatch(roleIds); } //绑定菜单于用户 if (!ids.isEmpty()) { ArrayList umsRoleMenuRelations = new ArrayList<>(); for (Long id : ids) { umsRoleMenuRelations.addAll(umsRoleMenuRelationMapper .selectList(new LambdaQueryWrapper() .eq(UmsRoleMenuRelation::getRoleId, id))); } umsRoleMenuRelations .stream() .map(item -> item.getMenuId()) .collect(Collectors.toList()) .stream() .distinct() .collect(Collectors.toList()) .stream() .forEach(item -> { AdminMenuRelation adminMenuRelation = new AdminMenuRelation(); adminMenuRelation.setAdminId(umsAdmin.getId()); adminMenuRelation.setMenuId(item); adminMenuRelationMapper.insert(adminMenuRelation); }); } //对用户名系统默认添加 //umsAdmin.setNickName(RandomUtils.getUserId(umsAdmin.getId())); //添加部门 UmsDepartManage departManage = new UmsDepartManage(); departManage.setUserId(umsAdmin.getId()); departManage.setDepartId(umsAdminParam.getDepartmentId()); departManage.setCreateTime(new Date()); departManage.setUpdateTime(new Date()); umsDepartManageMapper.insert(departManage); baseMapper.updateById(umsAdmin); } @Override public String login(String username, String password) { String token = null; //密码需要客户端加密后传递 try { AdminUserDetails userDetails = (AdminUserDetails) loadUserByUsername(username); UmsAdmin admin = userDetails.getUmsAdmin(); LocalDateTime nowTime = LocalDateTime.now(); nowTime = nowTime.plusMinutes(-15); if (admin.getPasswordErrorNum() != null && admin.getPasswordErrorNum() >= 5 && admin.getPasswordErrorLastTime().isAfter(nowTime)) { admin.setPasswordErrorLastTime(LocalDateTime.now()); updateById(admin); Asserts.fail("登录失败超过5次,此账号被锁定,请15分钟后再试。"); } if (!passwordEncoder.matches(password, userDetails.getPassword())) { if (admin.getPasswordErrorNum() == null) { admin.setPasswordErrorNum(1); } else { admin.setPasswordErrorNum(admin.getPasswordErrorNum() + 1); } admin.setPasswordErrorLastTime(LocalDateTime.now()); updateById(admin); Asserts.fail("密码不正确"); } if (!userDetails.isEnabled()) { Asserts.fail("帐号已被禁用"); } admin.setPasswordErrorNum(0); updateById(admin); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); //根据用户id,用户姓名 token = jwtTokenUtil.generateToken(userDetails.getUserId(), userDetails.getUsername()); redisService.set(RedisKey.PLATFORM_TOKEN_KEY.concat(username), token, LiveTimeMillisecond.s7200.time); // updateLoginTimeByUsername(username); //insertLoginLog(username); } catch (AuthenticationException e) { LOGGER.warn("登录异常:{}", e.getMessage()); } return token; } @Override public String getOAuthToken(String username) { String token = null; //密码需要客户端加密后传递 try { AdminUserDetails userDetails = (AdminUserDetails) loadUserByUsername(username); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); //根据用户id,用户姓名 token = jwtTokenUtil.generateToken(userDetails.getUserId(), userDetails.getUsername()); redisService.set(RedisKey.PLATFORM_TOKEN_KEY.concat(username), token, LiveTimeMillisecond.s7200.time); // updateLoginTimeByUsername(username); //insertLoginLog(username); } catch (AuthenticationException e) { LOGGER.warn("登录异常:{}", e.getMessage()); } return token; } /** * 添加登录记录 * * @param username 用户名 */ private void insertLoginLog(String username) { UmsAdmin admin = getAdminByUsername(username); if (admin == null) return; UmsAdminLoginLog loginLog = new UmsAdminLoginLog(); loginLog.setAdminId(admin.getId()); loginLog.setCreateTime(new Date()); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); loginLog.setIp(request.getRemoteAddr()); umsAdminLoginLogMapper.insert(loginLog); } /** * 根据用户名修改登录时间 */ private void updateLoginTimeByUsername(String username) { UmsAdmin record = new UmsAdmin(); record.setLoginTime(new Date()); QueryWrapper wrapper = new QueryWrapper<>(); wrapper.lambda().eq(UmsAdmin::getUsername, username); update(record, wrapper); } @Override public String refreshToken(String oldToken) { return jwtTokenUtil.refreshHeadToken(oldToken); } @Override public Page list(String keyword, Integer pageSize, Integer pageNum) { Page page = new Page<>(pageNum, pageSize); QueryWrapper wrapper = new QueryWrapper<>(); LambdaQueryWrapper lambda = wrapper.lambda(); if (StrUtil.isNotEmpty(keyword)) { lambda.like(UmsAdmin::getUsername, keyword); lambda.or().like(UmsAdmin::getNickName, keyword); } return page(page, wrapper); } @Override @Transactional(rollbackFor = Exception.class) public boolean update(Long id, UmsAdmin admin) { admin.setId(id); UmsAdmin rawAdmin = getById(id); if (rawAdmin.getPassword().equals(admin.getPassword())) { //与原加密密码相同的不需要修改 admin.setPassword(null); } else { //与原加密密码不同的需要加密修改 if (StrUtil.isEmpty(admin.getPassword())) { admin.setPassword(null); } else { admin.setPassword(passwordEncoder.encode(admin.getPassword())); } } boolean success = updateById(admin); getCacheService().delAdmin(id); return success; } @Override public boolean delete(Long id) { getCacheService().delAdmin(id); boolean success = removeById(id); getCacheService().delResourceList(id); return success; } @Override public int updateRole(Long adminId, List roleIds) { int count = roleIds == null ? 0 : roleIds.size(); //先删除原来的关系 QueryWrapper wrapper = new QueryWrapper<>(); wrapper.lambda().eq(UmsAdminRoleRelation::getAdminId, adminId); umsAdminRoleRelationService.remove(wrapper); //建立新关系 if (!CollectionUtils.isEmpty(roleIds)) { List list = new ArrayList<>(); for (Long roleId : roleIds) { UmsAdminRoleRelation roleRelation = new UmsAdminRoleRelation(); roleRelation.setAdminId(adminId); roleRelation.setRoleId(roleId); list.add(roleRelation); } umsAdminRoleRelationService.saveBatch(list); } getCacheService().delResourceList(adminId); return count; } @Override public List getRoleList(Long adminId) { return umsRoleMapper.getRoleList(adminId); } @Override public List getResourceList(Long adminId) { List umsMenuList = getCacheService().getResourceList(adminId); if (CollUtil.isNotEmpty(umsMenuList)) { return umsMenuList; } umsMenuList = umsMenuMapper.getMenuList(adminId); getCacheService().setResourceList(adminId, umsMenuList); return umsMenuList; } @Override public int updatePassword(UpdateAdminPasswordParam param) { if (StrUtil.isNotEmpty(param.getUsername()) && StrUtil.isNotEmpty(param.getOldPassword()) && StrUtil.isNotEmpty(param.getNewPassword()) && !param.getNewPassword().matches("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{8,16}$")) { return -1; } if (param.getUsername().equals(param.getNewPassword())) { return -4; } QueryWrapper wrapper = new QueryWrapper<>(); wrapper.lambda().eq(UmsAdmin::getUsername, param.getUsername()); List adminList = list(wrapper); if (CollUtil.isEmpty(adminList)) { return -2; } UmsAdmin umsAdmin = adminList.get(0); if (!passwordEncoder.matches(param.getOldPassword(), umsAdmin.getPassword())) { return -3; } umsAdmin.setPassword(passwordEncoder.encode(param.getNewPassword())); updateById(umsAdmin); getCacheService().delAdmin(umsAdmin.getId()); return 1; } @Override public UserDetails loadUserByUsername(String username) { //获取用户信息 UmsAdmin admin = getAdminByUsername(username); if (admin != null) { if (admin.getExpirationDate() != null) { if (!admin.getExpirationDate().after(new Date())) { Asserts.fail("账号已过期请联系管理员"); } } List resourceList = getResourceList(admin.getId()); return new AdminUserDetails(admin, resourceList); } throw new UsernameNotFoundException("用户不存在"); } @Override public UmsAdminCacheService getCacheService() { return SpringUtil.getBean(UmsAdminCacheService.class); } @Override public Page pageUser(UserVO.PageUserVO pageUserVO) { int pageSize = pageUserVO.getPageSize(); int current = pageUserVO.getCurrent(); Page page = new Page<>(current, pageSize); /* LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); if (StringUtils.isNotBlank(pageUserVO.getKeyword())) { queryWrapper.like(UmsAdmin::getUsername, pageUserVO.getKeyword()) .or().like(UmsAdmin::getNickName, pageUserVO.getKeyword()) .or().like(UmsAdmin::getMobile, pageUserVO.getKeyword()); } if (StringUtils.isNotBlank(pageUserVO.getJobTitle())) { queryWrapper.eq(UmsAdmin::getJobTitle, pageUserVO.getJobTitle()); } if (PojoUtils.Vo.isUsefulSearchParam(pageUserVO.getUserType())) { queryWrapper.eq(UmsAdmin::getUserType, pageUserVO.getUserType()); }*/ UmsAdmin umsAdmin = new UmsAdmin(); if (pageUserVO.getUserType() != null) { umsAdmin.setUserType(pageUserVO.getUserType()); } if (pageUserVO.getKeyword() != null && !("".equals(pageUserVO.getKeyword()))) { umsAdmin.setKeyword(pageUserVO.getKeyword()); } if (pageUserVO.getJobTitle() != null && !("".equals(pageUserVO.getJobTitle()))) { umsAdmin.setJobTitle(pageUserVO.getJobTitle()); } PageUtil.setFirstPageNo(1); int offset = PageUtil.getStart(current, pageSize); List list = baseMapper.selectCondList(umsAdmin, offset, pageSize); Long total = baseMapper.selectCondTotal(umsAdmin); page.setRecords(list); page.setTotal(total); return page; } @Override public List userExp() { List umsAdmins = baseMapper.selectToExp(); List res = umsAdmins.stream() .map(item -> { UmsUserDto1 res1 = new UmsUserDto1(); res1.setId(item.getId()); res1.setUsername(item.getUsername()); res1.setNickName(item.getNickName()); res1.setMobile(item.getMobile()); StringBuffer roleStrBuffer = new StringBuffer(); List roles = item.getRoles(); roles.forEach(new Consumer() { @Override public void accept(UmsRole o) { roleStrBuffer.append(o.getName()); roleStrBuffer.append(","); } }); roleStrBuffer.deleteCharAt(roleStrBuffer.length() - 1); res1.setRoles(roleStrBuffer.toString()); StringBuffer departStrBuffer = new StringBuffer(); List departs = item.getDepart(); departs.forEach(new Consumer() { @Override public void accept(UmsDepart o) { departStrBuffer.append(o.getDepartName()); departStrBuffer.append(","); } }); departStrBuffer.deleteCharAt(departStrBuffer.length() - 1); res1.setDepart(departStrBuffer.toString()); res1.setJobTitle(item.getJobTitle()); Date createTime = item.getCreateTime(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if (createTime != null) { res1.setCreateTime(sdf.format(createTime)); } Integer status = item.getStatus(); if (status.equals(1)) { res1.setStatus("启用"); } else { res1.setStatus("禁用"); } return res1; }).collect(Collectors.toList()); return res; } @Override public boolean deleteBatch(List ids) { boolean success = removeByIds(ids); getCacheService().delBatchAdmin(ids); return success; } @Override public boolean updateStatusBatch(List ids, Integer status) { List users = new ArrayList<>(); for (Long id : ids) { UmsAdmin umsAdmin = UmsAdmin.builder(). id(id).status(status).build(); users.add(umsAdmin); } updateBatchById(users, users.size()); getCacheService().delBatchAdmin(ids); return true; } @Override public List getDepartUser(Long departId) { QueryWrapper wrapper = new QueryWrapper<>(); wrapper.lambda().eq(UmsDepartManage::getDepartId, departId); List list = umsDepartManageMapper.selectList(wrapper); List userIds = list.stream().map(UmsDepartManage::getUserId).collect(Collectors.toList()); QueryWrapper wrapperUser = new QueryWrapper<>(); wrapperUser.in("id", userIds); List adminList = baseMapper.selectList(wrapperUser); return adminList; } @Override public String getTargetTo(String ids, String sendType) { String str = null; String[] arr = ids.split(","); QueryWrapper wrapperUser = new QueryWrapper<>(); wrapperUser.in("id", arr); List adminList = baseMapper.selectList(wrapperUser); if (adminList == null || adminList.isEmpty()) { throw new ApiException("未查询到用户"); } if ("02".equals(sendType)) { str = adminList.stream().map(UmsAdmin::getEmail).collect(Collectors.joining(",")); } else { str = adminList.stream().map(UmsAdmin::getMobile).collect(Collectors.joining(",")); } return str; } @Override public UmsAdmin getByOpenid(String openid) { LambdaQueryWrapper wrapper = new LambdaQueryWrapper().eq(UmsAdmin::getOpenid, openid).last("limit 1"); return baseMapper.selectOne(wrapper); } }