package com.ycl.service.user.impl; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; 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.UpdateAdminPasswordParam; import com.ycl.entity.depart.SccgDepart; import com.ycl.entity.user.*; import com.ycl.exception.Asserts; import com.ycl.mapper.user.UmsAdminLoginLogMapper; import com.ycl.mapper.user.UmsAdminMapper; import com.ycl.mapper.user.UmsResourceMapper; import com.ycl.mapper.user.UmsRoleMapper; import com.ycl.service.depart.SccgDepartService; import com.ycl.service.redis.RedisService; import com.ycl.service.user.UmsAdminCacheService; import com.ycl.service.user.UmsDepartManageService; 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.common.PojoUtils; import com.ycl.utils.common.RandomUtils; import com.ycl.utils.redis.RedisKey; import com.ycl.vo.user.UserVO; import org.apache.commons.lang3.StringUtils; 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.util.ArrayList; import java.util.Date; import java.util.List; /** * 后台管理员管理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 SccgDepartService sccgDepartService; @Resource private UmsDepartManageService umsAdminDepartService; @Resource private RedisService redisService; @Override public UmsAdmin getAdminByUsername(String username) { UmsAdmin admin = getCacheService().getAdmin(username); if (admin != null) return admin; 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(); //TODO mac,ip,职务,用户类型 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) { return null; } //将密码进行加密操作 String encodePassword = passwordEncoder.encode(umsAdmin.getPassword()); umsAdmin.setPassword(encodePassword); baseMapper.insert(umsAdmin); //对用户名系统默认添加 umsAdmin.setNickName(RandomUtils.getUserId(umsAdmin.getId())); baseMapper.updateById(umsAdmin); return umsAdmin; } @Override public String login(String username, String password) { String token = null; //密码需要客户端加密后传递 try { AdminUserDetails userDetails = (AdminUserDetails) loadUserByUsername(username); if (!passwordEncoder.matches(password, userDetails.getPassword())) { Asserts.fail("密码不正确"); } if (!userDetails.isEnabled()) { Asserts.fail("帐号已被禁用"); } 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 resourceList = getCacheService().getResourceList(adminId); if (CollUtil.isNotEmpty(resourceList)) { return resourceList; } resourceList = umsResourceMapper.getResourceList(adminId); if (CollUtil.isNotEmpty(resourceList)) { getCacheService().setResourceList(adminId, resourceList); } return resourceList; } @Override public int updatePassword(UpdateAdminPasswordParam param) { if (StrUtil.isEmpty(param.getUsername()) || StrUtil.isEmpty(param.getOldPassword()) || StrUtil.isEmpty(param.getNewPassword())) { return -1; } 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) { List resourceList = getResourceList(admin.getId()); return new AdminUserDetails(admin, resourceList); } throw new UsernameNotFoundException("用户名或密码错误"); } @Override public UmsAdminCacheService getCacheService() { return SpringUtil.getBean(UmsAdminCacheService.class); } @Override public IPage 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.getJobTitle())) { queryWrapper.eq(UmsAdmin::getJobTitle, pageUserVO.getJobTitle()); } if (PojoUtils.Vo.isUsefulSearchParam(pageUserVO.getUserType())) { queryWrapper.eq(UmsAdmin::getUserType, pageUserVO.getUserType()); } if (StringUtils.isNotBlank(pageUserVO.getMobile())) { queryWrapper.like(UmsAdmin::getMobile, pageUserVO.getMobile()); } if (PojoUtils.Vo.isUsefulSearchParam(pageUserVO.getDepartmentId())) { queryWrapper.eq(UmsAdmin::getDepartmentId, pageUserVO.getDepartmentId()); } Page page1 = baseMapper.selectPage(page, queryWrapper); List records = page1.getRecords(); if (CollUtil.isNotEmpty(records)) { records.forEach(e -> { SccgDepart sccgDepart = sccgDepartService.getById(e.getDepartmentId()); if (null != sccgDepart) { e.setDepartName(sccgDepart.getDepartName()); } }); } return page1; } }