All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.zznote.basecommon.service.impl.TUserServiceImpl Maven / Gradle / Ivy

The newest version!
package com.zznote.basecommon.service.impl;


import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
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.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zznote.basecommon.common.constant.CacheConstants;
import com.zznote.basecommon.common.constant.Constants;
import com.zznote.basecommon.common.constant.UserConstants;
import com.zznote.basecommon.common.enums.DeviceType;
import com.zznote.basecommon.common.exception.ServiceException;
import com.zznote.basecommon.common.exception.UserException;
import com.zznote.basecommon.common.page.PageInfo;
import com.zznote.basecommon.common.page.PageQuery;
import com.zznote.basecommon.common.util.LoginHelper;
import com.zznote.basecommon.common.util.ServletUtils;
import com.zznote.basecommon.common.util.UserStatus;
import com.zznote.basecommon.common.util.cache.RedisUtils;
import com.zznote.basecommon.dao.TDeptDao;
import com.zznote.basecommon.dao.TUserDao;
import com.zznote.basecommon.dto.LoginUser;
import com.zznote.basecommon.dto.RoleDTO;
import com.zznote.basecommon.entity.system.*;
import com.zznote.basecommon.service.*;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service("tUserService")
public class TUserServiceImpl extends ServiceImpl implements TUserService {
    private final TPermissionService permissionService;
    private final TLogininforService logininforService;
    private final TUserRoleService userRoleService;
    private final TDeptDao deptMapper;
    private final TUserPostService userPostService;

    @Override
    public PageInfo selectPageUserList(TUser user, PageQuery pageQuery) {
        Page page = baseMapper.selectPageUserList(pageQuery.build(), this.buildQueryWrapper(user));
        return PageInfo.build(page);
    }

    /**
     * 用户登陆
     * @param username
     * @param password
     * @return
     */
    @Override
    public String login(String username, String password) {
        LoginUser userInfo = getUserInfo(username);
        // 获取用户登录错误次数(可自定义限制策略 例如: key + username + ip)
        String cache = RedisUtils.getCacheObject(CacheConstants.LOGIN_ERROR + username);
        Integer errorNumber = null;
        if (StringUtils.isNotBlank(cache)) {
            errorNumber = Integer.valueOf(cache);
        }
        // 锁定时间内登录 则踢出
        if (ObjectUtil.isNotNull(errorNumber) && errorNumber.equals(CacheConstants.LOGIN_ERROR_NUMBER)) {
            recordLogininfor(username, Constants.LOGIN_FAIL, "账户锁定中");
            throw new UserException("账号锁定中");
        }
        if (!BCrypt.checkpw(password, userInfo.getPassword())) {
            // 是否第一次
            errorNumber = ObjectUtil.isNull(errorNumber) ? 1 : errorNumber + 1;
            // 达到规定错误次数 则锁定登录
            if (errorNumber.equals(CacheConstants.LOGIN_ERROR_NUMBER)) {
                recordLogininfor(username, Constants.LOGIN_FAIL, "登陆失败,账户锁定中,锁定时间:" + CacheConstants.LOGIN_ERROR_LIMIT_TIME + "分钟");
                throw new UserException("登陆错误锁定中");
            } else {
                // 未达到规定错误次数 则递增
                RedisUtils.setCacheObject(CacheConstants.LOGIN_ERROR + username, errorNumber);
                recordLogininfor(username, Constants.LOGIN_FAIL, "登陆失败,失败次数:" + errorNumber + "次");
                throw new UserException("用户密码错误");
            }
        }
        // 登录成功 清空错误次数
        RedisUtils.deleteObject(CacheConstants.LOGIN_ERROR + username);
        // 获取登录token
        LoginHelper.loginByDevice(userInfo, DeviceType.PC);
        recordLogininfor(username, Constants.LOGIN_SUCCESS, "登陆成功");
        return StpUtil.getTokenValue();
    }

    @Override
    public LoginUser getUserInfo(String username) {
        TUser sysUser = baseMapper.selectByUserName(username);
        if (ObjectUtil.isNull(sysUser)) {
            throw new UserException("用户不存在");
        }
        if (UserStatus.DELETED.getCode().equals(sysUser.getDelFlag())) {
            throw new UserException("用户已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(sysUser.getStatus())) {
            throw new UserException("用户账号已被停用");
        }
        // 此处可根据登录用户的数据不同 自行创建 loginUser
        return buildLoginUser(sysUser);
    }

    /**
     * 构建登录用户
     */
    private LoginUser buildLoginUser(TUser user) {
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getUserId());
        loginUser.setDeptId(user.getDeptId());
        loginUser.setUsername(user.getUserName());
        loginUser.setPassword(user.getPassword());
        loginUser.setUserType(user.getUserType());
        loginUser.setMenuPermission(permissionService.getMenuPermission(user.getUserId()));
        loginUser.setRolePermission(permissionService.getRolePermission(user.getUserId()));
        loginUser.setDeptName(user.getDept().getDeptName());
        List roles = BeanUtil.copyToList(user.getRoles(), RoleDTO.class);
        loginUser.setRoles(roles);
        return loginUser;
    }

    /**
     * 记录登录信息
     */
    public void recordLogininfor(String username, String status, String message) {
        TLogininfor logininfor = new TLogininfor();
        logininfor.setUserName(username);
        logininfor.setIpaddr(ServletUtils.getClientIP());
        logininfor.setMsg(message);
        // 日志状态
        if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
            logininfor.setStatus(Constants.LOGIN_SUCCESS_STATUS);
        } else if (Constants.LOGIN_FAIL.equals(status)) {
            logininfor.setStatus(Constants.LOGIN_FAIL_STATUS);
        }
        logininforService.saveLogininfor(logininfor);
    }

    @Override
    public PageInfo selectAllocatedList(TUser user, PageQuery pageQuery) {
        QueryWrapper wrapper = Wrappers.query();
        wrapper.eq("u.del_flag", UserConstants.USER_NORMAL)
                .eq(ObjectUtil.isNotNull(user.getRoleId()), "r.role_id", user.getRoleId())
                .like(StringUtils.isNotBlank(user.getUserName()), "u.user_name", user.getUserName())
                .eq(StringUtils.isNotBlank(user.getStatus()), "u.status", user.getStatus())
                .like(StringUtils.isNotBlank(user.getPhonenumber()), "u.phonenumber", user.getPhonenumber());
        Page page = baseMapper.selectAllocatedList(pageQuery.build(), wrapper);
        return PageInfo.build(page);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public PageInfo selectUnallocatedList(TUser user, PageQuery pageQuery) {
        List userIds = userRoleService.selectUserIdsByRoleId(user.getRoleId());
        QueryWrapper wrapper = Wrappers.query();
        wrapper.eq("u.del_flag", UserConstants.USER_NORMAL)
                .and(w -> w.ne("r.role_id", user.getRoleId()).or().isNull("r.role_id"))
                .notIn("u.user_id", userIds)
                .like(StringUtils.isNotBlank(user.getUserName()), "u.user_name", user.getUserName())
                .like(StringUtils.isNotBlank(user.getPhonenumber()), "u.phonenumber", user.getPhonenumber());
        Page page = baseMapper.selectUnallocatedList(pageQuery.build(), wrapper);
        return PageInfo.build(page);
    }


    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List selectUserList(TUser user) {
        return baseMapper.selectUserList(this.buildQueryWrapper(user));
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public TUser selectUserByUserName(String userName) {
        return baseMapper.selectUserByUserName(userName);
    }


    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public TUser selectUserById(Long userId) {
        return baseMapper.selectUserById(userId);
    }


    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!LoginHelper.isAdmin()) {
            TUser user = new TUser();
            user.setUserId(userId);
            List users = this.selectUserList(user);
            if (CollUtil.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据!");
            }
        }
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName) {
        boolean exist = lambdaQuery().eq(TUser::getUserName,userName).count() > 0;
        if (exist) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(TUser user) {
        boolean exist = lambdaQuery().eq(TUser::getPhonenumber,user.getPhonenumber()).count() > 0;
        if (exist) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(TUser user) {
        boolean exist = lambdaQuery().eq(TUser::getEmail,user.getEmail()).count() > 0;
        if (exist) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(TUser user) {
        // 新增用户信息
        int rows = baseMapper.insert(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(TUser user) {
        if (ObjectUtil.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(TUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleService.remove(new LambdaQueryWrapper().eq(TUserRole::getUserId, userId));
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostService.remove(new LambdaQueryWrapper().eq(TUserPost::getUserId, userId));
        // 新增用户与岗位管理
        insertUserPost(user);
        return updateById(user);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new TUser(userId));
            checkUserDataScope(userId);
        }
        List ids = Arrays.asList(userIds);
        // 删除用户与角色关联
        userRoleService.remove(new LambdaQueryWrapper().in(TUserRole::getUserId, ids));
        // 删除用户与岗位表
        userPostService.remove(new LambdaQueryWrapper().in(TUserPost::getUserId, ids));
        return removeByIds(ids);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleService.remove(new LambdaQueryWrapper()
                .eq(TUserRole::getUserId, userId));
        insertUserRole(userId, roleIds);
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(TUser user) {
        Long[] posts = user.getPostIds();
        if (ObjectUtil.isNotNull(posts)) {
            // 新增用户与岗位管理
            List list = new ArrayList();
            for (Long postId : posts) {
                TUserPost up = new TUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0) {
                userPostService.saveBatch(list);
            }
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(TUser user) {
        Long[] roles = user.getRoleIds();
        if (ObjectUtil.isNotNull(roles)) {
            // 新增用户与角色管理
            List list = new ArrayList();
            for (Long roleId : roles) {
                TUserRole ur = new TUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleService.saveBatch(list);
            }
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (ObjectUtil.isNotNull(roleIds)) {
            // 新增用户与角色管理
            List list = new ArrayList();
            for (Long roleId : roleIds) {
                TUserRole ur = new TUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleService.saveBatch(list);
            }
        }
    }

    private Wrapper buildQueryWrapper(TUser user) {
        Map params = user.getParams();
        QueryWrapper wrapper = Wrappers.query();
        wrapper.eq("u.del_flag", UserConstants.USER_NORMAL)
                .eq(ObjectUtil.isNotNull(user.getUserId()), "u.user_id", user.getUserId())
                .like(StringUtils.isNotBlank(user.getUserName()), "u.user_name", user.getUserName())
                .eq(StringUtils.isNotBlank(user.getStatus()), "u.status", user.getStatus())
                .like(StringUtils.isNotBlank(user.getPhonenumber()), "u.phonenumber", user.getPhonenumber())
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        "u.create_time", params.get("beginTime"), params.get("endTime"))
                .and(ObjectUtil.isNotNull(user.getDeptId()), w -> {
                    List deptList = deptMapper.selectList(new LambdaQueryWrapper()
                            .select(TDept::getDeptId)
                            .apply("find_in_set({0},ancestors) <> 0", user.getDeptId()));
                    List ids = deptList.stream().map(TDept::getDeptId).collect(Collectors.toList());
                    ids.add(user.getDeptId());
                    w.in("u.dept_id", ids);
                });
        return wrapper;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy