SysUserServiceImpl.java 8.24 KB
package com.bsth.service.sys.impl;

import com.bsth.common.ResponseCode;
import com.bsth.controller.sys.util.RSAUtils;
import com.bsth.email.entity.EmailBean;
import com.bsth.entity.sys.Role;
import com.bsth.entity.sys.SysUser;
import com.bsth.repository.sys.RoleRepository;
import com.bsth.repository.sys.SysUserRepository;
import com.bsth.security.util.SecurityUtils;
import com.bsth.service.impl.BaseServiceImpl;
import com.bsth.service.sys.RoleService;
import com.bsth.service.sys.SysUserService;
import com.bsth.util.IpUtils;
import com.bsth.util.MailUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUser, Integer> implements SysUserService{

	@Autowired
	SysUserRepository sysUserRepository;

	@Autowired
	RoleService roleService;

	// 发送邮件
	@Autowired
	private MailUtils mailUtils;

	@Autowired
	RoleRepository roleRepository;


	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Override
	public SysUser findByUserName(String name) {
		return sysUserRepository.findByUserName(name);
	}
	
	@Override
	public Map<String, Object> save(SysUser t) {
		// 
		if(t.getPassword() == null || t.getPassword().trim().equals("")){
			SysUser user = sysUserRepository.findById(t.getId()).get();
			t.setPassword(user.getPassword());
		}else{
			t.setPassword(new BCryptPasswordEncoder(4).encode(t.getPassword()));
		}
		return super.save(t);
	}

	@Override
	public int changeEnabled(int id, int enabled) {
		sysUserRepository.changeEnabled(id,enabled);
		return 0;
	}

	@Override
	public int changePWD(int id,String newPWD) {
		return sysUserRepository.changePWD(id,new BCryptPasswordEncoder(4).encode(newPWD));
	}

    @Override
    public boolean validPWDExpired(String userName) {
        SysUser sysUser = this.sysUserRepository.findByUserName(userName);
        if (sysUser == null) {
            throw new RuntimeException("用户[" + userName + "]不存在!");
        }
        if (sysUser.getPwdValidPeriod() == null || sysUser.getLastPwdDate() == null) {
            // 如果没有设定密码过期时间,判定为不过期
            return true;
        }
        DateTime now = new DateTime();
        DateTime lastPwdDate = new DateTime(sysUser.getLastPwdDate());
        Integer now_period_days = Days.daysBetween(lastPwdDate, now).getDays();
        Integer expiredTipDays = 3; // 密码过期提前提示天数
        if (now_period_days < (sysUser.getPwdValidPeriod() - expiredTipDays)) {
            return true;
        } else if (now_period_days >= (sysUser.getPwdValidPeriod() - expiredTipDays) &&
                now_period_days < sysUser.getPwdValidPeriod()) {
            // 快过期前提示
            throw new RuntimeException("当前用户密码还有[" + (sysUser.getPwdValidPeriod() - now_period_days) + "]天过期!");
        } else {
            throw new RuntimeException("当前用户密码已过期!");
        }

    }

    @Override
	public Map<String, Object> register(SysUser u) {
		Map<String, Object> rs = new HashMap();
		boolean isLegality = false;
		Iterator<Role> itRole = u.getRoles().iterator();
		Role ro = new Role();
		while(itRole.hasNext()){//判断是否有下一个
			ro = itRole.next();
			if(roleService.checkOperationLegality(ro.getId())){
				isLegality = true;
			} else {
				rs.put("status", ResponseCode.ERROR);
				rs.put("msg", "用户权限不够,请联系管理员!");
				return rs;
			}
		}
		if(isLegality){
			try{
				//解密RSA
				try{
					u.setUserName(RSAUtils.decryptBase64(u.getUserName()));
					u.setPassword(RSAUtils.decryptBase64(u.getPassword()));
				}catch (RuntimeException e) {
					rs.put("msg", "网络延迟,解密失败,请重新添加!");
				}
				//检查用户名是否存在
				if(findByUserName(u.getUserName()) != null){
					rs.put("status", ResponseCode.ERROR);
					rs.put("msg", "用户名" + u.getUserName() + "已存在!");
				}
				else{
					u.setPassword(new BCryptPasswordEncoder(4).encode(u.getPassword()));
					rs = super.save(u);
				}
			}catch (Exception e){
				logger.error("", e);
				rs.put("status", ResponseCode.ERROR);
				rs.put("msg", e.getMessage());
			}
		}else {
			rs.put("status", ResponseCode.ERROR);
			rs.put("msg", "用户权限不够,请联系管理员!");
		}
		return rs;
	}

	@Override
	public List<SysUser> findAll_distinct() {
		Map<String, Object> map = roleService.findSubordinate();
		Object object = roleService.findSubordinate().get("list");
		List<SysUser> rsList = new ArrayList<>();

		// 有权限查看的角色
//		List<Role> roleList = JSONArray.parseArray(map.get("list").toString(), Role.class);

		try{
			Gson gson = new Gson();
			// 有权限查看的角色
			List<Role> roleList = gson.fromJson(map.get("list").toString(), new TypeToken<List<Role>>(){}.getType());

			if(roleList.size() != 0 && !roleList.isEmpty()){
				// 遍历有权限查看的角色
				Map<Integer,Role> roleMap = new HashMap<>();
				for (Role role: roleList) {
					roleMap.put(role.getId(),role);
				}

				List<SysUser> list = new ArrayList<>();
				list = sysUserRepository.findAll_distinct();
				for (SysUser sysUsers:list) {

					Iterator<Role> itUser = sysUsers.getRoles().iterator();
					Role roleUser = new Role();
					while(itUser.hasNext()){//判断是否有下一个
						roleUser = itUser.next();
					}
					// 添加权限内的用户
					if(roleMap.get(roleUser.getId()) != null){
						rsList.add(sysUsers);
					}
				}
			}
		} catch (Exception e){
			logger.error("error", e);
		}
		return rsList;
	}

	@Override
	@Transactional
	public Map<String, Object> resetPassword(Integer id, Integer pwdValidPeriod){
		Map<String, Object> rs = new HashMap();
		try{
			// 获取当前用户
			SysUser user = SecurityUtils.getCurrentUser();
			Iterator<Role> itRole = user.getRoles().iterator();
			Role ro = new Role();
			boolean Legality = false;
			while(itRole.hasNext()){//判断是否有下一个
				ro = itRole.next();
				if(ro.getLevel() == 1)
					Legality = true;
			}
			if(Legality){
				String pwd = PwdGenerator.randomPassword(16);
				user = sysUserRepository.findById(id).get();
				user.setPwdValidPeriod(pwdValidPeriod);
				sysUserRepository.save(user);
				sysUserRepository.changePWD(id, new BCryptPasswordEncoder(4).encode(pwd));
				//发送邮件
				EmailBean mail = new EmailBean();
				mail.setSubject(IpUtils.getLocalIpAddress() +":密码重置");
				mail.setContent(pwd);
				mailUtils.sendMail(mail);
				logger.info("setLD-sendMail:邮件发送成功!");
				rs.put("status", ResponseCode.SUCCESS);
				rs.put("msg", "密码重置成功!");
			}else {
				rs.put("status", ResponseCode.ERROR);
				rs.put("msg", "您不是管理员无权限重置其他用户密码");
			}
		}catch (Exception e){
			logger.error("", e);
			rs.put("status", ResponseCode.ERROR);
			rs.put("msg", e.getMessage());
		}
		return rs;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void recordLoginDate(String userName) {
		sysUserRepository.recordLoginDate(userName);
	}

	@Override
	public Map<String, Object> createUser(SysUser u) {
		Map<String, Object> rs = new HashMap();
		try {
			Role role=roleService.findById(136);
			if(role==null){
				rs.put("status", ResponseCode.ERROR);
				rs.put("msg", "用户权限不够,请联系管理员!");
				return rs;
			}
			Set<Role> roleSet=new HashSet<>();
			roleSet.add(role);
			u.setRoles(roleSet);
			u.setUserName(u.getUserName());
			u.setPassword("Bsth#1234");
			u.setCreateDate(new Date());
			u.setUpdateDate(new Date());
			u.setLastPwdDate(new Date());
			u.setPwdValidPeriod(9999);
			u.setAgencies("嘉定公交");
			u.setEnabled(true);
			u.setPassword(new BCryptPasswordEncoder(4).encode(u.getPassword()));
			rs = super.save(u);
			logger.info("首次登陆创建用户:"+u.getUserName());
		} catch (Exception e) {
			logger.error("", e);
			rs.put("status", ResponseCode.ERROR);
			rs.put("msg", e.getMessage());
		}
		return rs;
	}

}