基于springboot+redis+bootstrap+mysql开发一套属于自己的分布式springcloud云权限架构(十)【权限架构生产者(用户管理)】

      在第九章我们完成了对角色管理的集成,本章我们将完成对用户管理的集成开发工作,首先打开我们的rbac-produce工程,接着在com/produce/sys/dao目录底下创建一个UserDao.java接口内容如下:

package com.produce.sys.dao;



import com.base.entity.QueryUser;
import com.base.entity.User;
import com.produce.common.base.dao.GenericDao;

import java.util.List;

/**
 *@author linzf
 **/
public interface UserDao extends GenericDao<User, QueryUser> {

    /**
     * 功能描述:统计组织架构底下的用户
     * @param queryUser
     * @return
     */
    int countGroupUser(QueryUser queryUser);

    /**
     * 功能描述:查询组织架构底下的用户
     * @param queryUser
     * @return
     */
    List<User> findGroupUserByPage(QueryUser queryUser);

    /**
     * 功能描述:更新用户状态为可用或者不可用
     * @param user
     * @return
     */
    int userControl(User user);

    /**
     * 功能描述:根据账号来获取用户信息
     * @param login
     * @return
     */
    User findByLogin(String login);

    /**
     * 功能描述:更新用户的最迟登陆时间
     * @param user
     * @return
     */
    int updateLogin(User user);

	
}

      接着在我们的mapper文件夹底下创建一个mybatis_user.xml文件,文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.produce.sys.dao.UserDao">
	<resultMap type="com.base.entity.User" id="UserMap">
		<id property="id" column="id"/>
		<result property="login" column="login"/>
		<result property="password" column="password"/>
		<result property="userName" column="user_name"/>
		<result property="address" column="address"/>
		<result property="job" column="job"/>
		<result property="groupId" column="group_id"/>
		<result property="birthDate" column="birth_date"/>
		<result property="city" column="city"/>
		<result property="district" column="district"/>
		<result property="province" column="province"/>
		<result property="streetAddress" column="street_address"/>
		<result property="state" column="state"/>
		<result property="type" column="type"/>
		<result property="lastLoginDate" column="last_login_date"/>
		<association property="orgGroup" javaType="com.base.entity.OrgGroup" column="group_id">
			<id property="groupId" column="group_id"/>
			<result property="existingNum" column="existing_num"/>
			<result property="groupCode" column="group_code"/>
			<result property="name" column="name"/>
			<result property="node" column="node"/>
			<result property="num" column="num"/>
			<result property="parentNode" column="parent_node"/>
		</association>
	</resultMap>

	<!-- 包含角色信息的map -->
	<resultMap type="com.base.entity.User" id="UserLoginMap">
		<id property="id" column="id"/>
		<result property="login" column="login"/>
		<result property="password" column="password"/>
		<result property="userName" column="user_name"/>
		<result property="address" column="address"/>
		<result property="job" column="job"/>
		<result property="groupId" column="group_id"/>
		<result property="birthDate" column="birth_date"/>
		<result property="city" column="city"/>
		<result property="district" column="district"/>
		<result property="province" column="province"/>
		<result property="streetAddress" column="street_address"/>
		<result property="state" column="state"/>
		<result property="type" column="type"/>
		<result property="lastLoginDate" column="last_login_date"/>
		<collection property="roles"  ofType="com.base.entity.UserRole" javaType="java.util.ArrayList">
			<result column="user_role_id" property="id" jdbcType="VARCHAR" />
			<result column="name" property="name" jdbcType="VARCHAR" />
			<result column="role_name" property="roleName" jdbcType="VARCHAR" />
		</collection>
	</resultMap>

	<!-- 更新用户状态为可用或者不可用 -->
	<update id="userControl" parameterType="com.base.entity.User">
		update user set state = #{state} where id=#{id}
	</update>

	<!-- 根据账号来获取用户信息 -->
	<select id="findByLogin" parameterType="java.lang.String" resultMap="UserLoginMap">
		select u.*,ur.id as user_role_id,ur.name,ur.role_name from user u inner join user_associate_role uar on u.id = uar.user_id inner join user_role ur on uar.role_id = ur.id where u.login = #{login}
	</select>

	<!-- 更新用户的最迟登陆时间 -->
     <update id="updateLogin" parameterType="com.base.entity.User">
		 update user set last_login_date = #{lastLoginDate} where id=#{id}
	 </update>

	<!--根据主键获取对象-->
	<select id="get" parameterType="com.base.entity.User" resultMap="UserMap">
		select u.*,og.existing_num,og.group_code,og.name,og.node,og.num,og.parent_node from user u inner join org_group og on u.group_id = og.group_id
		WHERE id=#{id}
	</select>

	<!--保存-->
	<insert id="save" parameterType="com.base.entity.User" useGeneratedKeys="true" keyProperty="id">
		INSERT INTO user(login,password,user_name,address,job,group_id,birth_date,city,district,province,street_address,state,type,last_login_date)
		VALUES(#{login},#{password},#{userName},#{address},#{job},#{orgGroup.groupId},#{birthDate},#{city},#{district},#{province},#{streetAddress},#{state},#{type},#{lastLoginDate})
	</insert>

	<!--修改-->
	<update id="update" parameterType="com.base.entity.User">
		UPDATE user SET user_name=#{userName},address=#{address},job=#{job},group_id=#{orgGroup.groupId},birth_date=#{birthDate},city=#{city},district=#{district},province=#{province},street_address=#{streetAddress}
		WHERE id=#{id}
	</update>

	<!--删除-->
	<delete id="delete" parameterType="com.base.entity.User">
		 DELETE FROM user WHERE id=#{id}
	</delete>

	<!--分页查询组织架构底下的用户-->
	<select id="findGroupUserByPage" parameterType="com.base.entity.QueryUser" resultMap="UserMap">
		select u.*,og.existing_num,og.group_code,og.name,og.node,og.num,og.parent_node from user u inner join org_group og on u.group_id = og.group_id
		WHERE 1=1
		<if test="userName!=null and userName!='' ">
			AND u.user_name like concat(#{userName},'%')
		</if>
		<if test="orgGroup!=null">
			<if test="orgGroup.parentNode!=null and orgGroup.parentNode!='' ">
                  AND og.parent_node like concat(#{orgGroup.parentNode},'%')
			</if>
			<if test="orgGroup.node!=null and orgGroup.node!='' ">
				AND og.node like concat(#{orgGroup.node},'%')
			</if>
		</if>
		<if test="sort!= null and sort!='' ">
			order by ${sort} ${order}
		</if>
		limit #{offset},#{limit}
	</select>

	<!--统计组织架构底下的用户-->
	<select id="countGroupUser" parameterType="com.base.entity.QueryUser" resultType="int">
		select count(1) from user u inner join org_group og on u.group_id = og.group_id
		WHERE 1=1
		<if test="userName!=null and userName!='' ">
			AND u.user_name like concat(#{userName},'%')
		</if>
		<if test="orgGroup!=null">
			<if test="orgGroup.parentNode!=null and orgGroup.parentNode!='' ">
				AND og.parent_node like concat(#{orgGroup.parentNode},'%')
			</if>
			<if test="orgGroup.node!=null and orgGroup.node!='' ">
				AND og.node like concat(#{orgGroup.node},'%')
			</if>
		</if>
	</select>

	<!--分页查询-->
	<select id="findByPage" parameterType="com.base.entity.QueryUser" resultMap="UserMap">
		select u.*,og.existing_num,og.group_code,og.name,og.node,og.num,og.parent_node from user u inner join org_group og on u.group_id = og.group_id
		WHERE 1=1
		<if test="login!=null and login!='' ">
		AND u.login=#{login}
		</if>
		<if test="password!=null and password!='' ">
		AND u.password=#{password}
		</if>
		<if test="userName!=null and userName!='' ">
		AND u.user_name=#{userName}
		</if>
		<if test="address!=null and address!='' ">
		AND u.address=#{address}
		</if>
		<if test="job!=null and job!='' ">
		AND u.job=#{job}
		</if>
		<if test="groupId!=null and groupId!='' ">
		AND u.group_id=#{groupId}
		</if>
		<if test="birthDate!=null and birthDate!='' ">
		AND u.birth_date=#{birthDate}
		</if>
		<if test="city!=null and city!='' ">
		AND u.city=#{city}
		</if>
		<if test="district!=null and district!='' ">
		AND u.district=#{district}
		</if>
		<if test="province!=null and province!='' ">
		AND u.province=#{province}
		</if>
		<if test="streetAddress!=null and streetAddress!='' ">
		AND u.street_address=#{streetAddress}
		</if>
		<if test="state!=null and state!='' ">
		AND u.state=#{state}
		</if>
		<if test="type!=null and type!='' ">
		AND u.type=#{type}
		</if>
		<if test="lastLoginDate!=null and lastLoginDate!='' ">
		AND u.last_login_date=#{lastLoginDate}
		</if>
		<if test="sort!= null and sort!='' ">
		order by ${sort} ${order}
		</if>
		limit #{offset},#{limit}
	</select>

	<!--统计-->
	<select id="count" parameterType="com.base.entity.QueryUser" resultType="int">
		SELECT count(*) FROM user
		WHERE 1=1
		<if test="login!=null and login!='' ">
			AND login=#{login}
		</if>
		<if test="password!=null and password!='' ">
			AND password=#{password}
		</if>
		<if test="userName!=null and userName!='' ">
			AND user_name=#{userName}
		</if>
		<if test="address!=null and address!='' ">
			AND address=#{address}
		</if>
		<if test="job!=null and job!='' ">
			AND job=#{job}
		</if>
		<if test="groupId!=null and groupId!='' ">
			AND group_id=#{groupId}
		</if>
		<if test="birthDate!=null and birthDate!='' ">
			AND birth_date=#{birthDate}
		</if>
		<if test="city!=null and city!='' ">
			AND city=#{city}
		</if>
		<if test="district!=null and district!='' ">
			AND district=#{district}
		</if>
		<if test="province!=null and province!='' ">
			AND province=#{province}
		</if>
		<if test="streetAddress!=null and streetAddress!='' ">
			AND street_address=#{streetAddress}
		</if>
		<if test="state!=null and state!='' ">
			AND state=#{state}
		</if>
		<if test="type!=null and type!='' ">
			AND type=#{type}
		</if>
		<if test="lastLoginDate!=null and lastLoginDate!='' ">
			AND last_login_date=#{lastLoginDate}
		</if>
		<if test="sort!= null and sort!='' ">
			order by ${sort} ${order}
		</if>
	</select>

	<!--查询-->
	<select id="query" parameterType="com.base.entity.QueryUser" resultMap="UserMap">
		SELECT id,login,password,user_name,address,job,group_id,birth_date,city,district,province,street_address,state,type,last_login_date FROM user
		WHERE 1=1
		<if test="login!=null and login!='' ">
			AND login=#{login}
		</if>
		<if test="password!=null and password!='' ">
			AND password=#{password}
		</if>
		<if test="userName!=null and userName!='' ">
			AND user_name=#{userName}
		</if>
		<if test="address!=null and address!='' ">
			AND address=#{address}
		</if>
		<if test="job!=null and job!='' ">
			AND job=#{job}
		</if>
		<if test="groupId!=null and groupId!='' ">
			AND group_id=#{groupId}
		</if>
		<if test="birthDate!=null and birthDate!='' ">
			AND birth_date=#{birthDate}
		</if>
		<if test="city!=null and city!='' ">
			AND city=#{city}
		</if>
		<if test="district!=null and district!='' ">
			AND district=#{district}
		</if>
		<if test="province!=null and province!='' ">
			AND province=#{province}
		</if>
		<if test="streetAddress!=null and streetAddress!='' ">
			AND street_address=#{streetAddress}
		</if>
		<if test="state!=null and state!='' ">
			AND state=#{state}
		</if>
		<if test="type!=null and type!='' ">
			AND type=#{type}
		</if>
		<if test="lastLoginDate!=null and lastLoginDate!='' ">
			AND last_login_date=#{lastLoginDate}
		</if>
		<if test="sort!= null and sort!='' ">
			order by ${sort} ${order}
		</if>
	</select>
</mapper>

      由于我们对用户进行维护的时候,同时会为用户赋予相应的角色权限,因此我们在对用户进行相应操作的时候应该对用户角色关联表进行相应的操作,因此我们需要在com/produce/sys/dao目录底下创建一个UserAssociateRoleDao.java接口内容如下:

package com.produce.sys.dao;


import com.base.entity.QueryUserAssociateRole;
import com.base.entity.User;
import com.base.entity.UserAssociateRole;
import com.produce.common.base.dao.GenericDao;

/**
 *@author linzf
 **/
public interface UserAssociateRoleDao extends GenericDao<UserAssociateRole, QueryUserAssociateRole> {

    /**
     * 功能描述:根据用户的ID来删除用户的权限数据
     * @param user
     * @return
     */
    int removeUserRole(User user);
}

      由于我们保存在数据库中的用户的密码是经过MD5的盐值加密的,因此我们这边需要有一个工具类来进行盐值的加密,因此我们在com/produce/common/util底下创建了一个user包,同时在该包底下创建了UserInfo.java工具类,内容如下:

package com.produce.common.util.user;


import org.springframework.security.crypto.codec.Hex;

import java.security.MessageDigest;

/**
 * Created by Administrator on 2017/8/7 0007.
 */
public class UserInfo {


    /**
     * 功能描述:实现对密码进行加盐值得MD5加密
     * @param password
     * @return
     */
    public static String encode(String password,String salt){
        password = password + "{"+salt +"}";
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(password.getBytes());
            return new String(new Hex().encode(bs));
        } catch (Exception e) {
            return null;
        }
    }

}
      接着在com/produce/sys/service目录底下创建一个UserService.java实现类内容如下:
package com.produce.sys.service;


import com.base.common.Page;
import com.base.entity.QueryUser;
import com.base.entity.User;
import com.base.entity.UserAssociateRole;
import com.base.entity.UserRole;
import com.produce.common.base.dao.GenericDao;
import com.produce.common.base.service.GenericService;
import com.produce.common.util.user.UserInfo;
import com.produce.sys.dao.UserAssociateRoleDao;
import com.produce.sys.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 *@author linzf
 **/
@Service("userService")
@Transactional(rollbackFor={IllegalArgumentException.class})
public class UserService extends GenericService<User, QueryUser> {
	@Autowired
	@SuppressWarnings("SpringJavaAutowiringInspection")
	private UserDao userDao;

	@Autowired
	@SuppressWarnings("SpringJavaAutowiringInspection")
	private UserAssociateRoleDao userAssociateRoleDao;

	@Override
	protected GenericDao<User, QueryUser> getDao() {
		return userDao;
	}

	/**
	 * 分页查询组织架构底下的用户
	 * @param queryUser 查询条件
	 *  */
	public Page findByGroupUserPage(QueryUser queryUser){
		List<User> list =  userDao.findGroupUserByPage(queryUser);
		int count = userDao.countGroupUser(queryUser);
		return new Page(list, count);
	}

	/**
	 * 功能描述:实现增加用户
	 * @param entity 保存对象
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean save(User entity) throws Exception {
		entity.setAddress(entity.getProvince()+entity.getCity()+entity.getDistrict()+entity.getStreetAddress());
		entity.setPassword(UserInfo.encode(entity.getPassword(),"hyll"));
		entity.setState("1");
		entity.packagingRoles(entity.getRoleArray());
		List<UserRole> userRoleList = entity.getRoles();
		boolean success = userDao.save(entity)>0;
		if(success){
			if(userRoleList.size()>0){
				for(UserRole userRole:userRoleList){
					userAssociateRoleDao.save(new UserAssociateRole(entity.getId(),userRole.getId()));
				}
			}
		}
		return success;
	}

	/**
	 * 功能描述:实现更新用户
	 * @param entity 修改对象
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean update(User entity) throws Exception {
		entity.packagingRoles(entity.getRoleArray());
		entity.setAddress(entity.getProvince()+entity.getCity()+entity.getDistrict()+entity.getStreetAddress());
		userAssociateRoleDao.removeUserRole(entity);
		if(entity.getRoles().size()>0){
			for(UserRole userRole:entity.getRoles()){
				userAssociateRoleDao.save(new UserAssociateRole(entity.getId(),userRole.getId()));
			}
		}
		return super.update(entity);
	}

	/**
	 * 功能描述:批量删除用户
	 * @param entityList
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean removeBath(List<User> entityList) throws Exception {
		for(User user:entityList){
			userAssociateRoleDao.removeUserRole(user);
		}
		return super.removeBath(entityList);
	}

	/**
	 * 功能描述:更新用户状态为可用或者不可用
	 * @param user
	 * @return
	 */
	public boolean userControl(User user){
		return userDao.userControl(user)>0;
	}

	/**
	 * 功能描述:根据账号来获取用户信息
	 * @param login
	 * @return
	 */
	public User findByLogin(String login){
		return userDao.findByLogin(login);
	}

}

      最后在我们的com/produce/sys/controller底下创建我们的UserController.java实现类内容如下:

package com.produce.sys.controller;


import com.base.entity.QueryUser;
import com.base.entity.User;
import com.base.entity.UserRole;
import com.base.util.json.JsonHelper;
import com.produce.common.base.constant.SystemStaticConst;
import com.produce.common.base.controller.GenericController;
import com.produce.common.base.service.GenericService;
import com.produce.sys.service.UserRoleService;
import com.produce.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/*
* 类描述:用户维护controller
* @auther linzf
* @create 2017/9/7 0007
*/
@RestController
@RequestMapping("/user")
public class UserController extends GenericController<User,QueryUser> {

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;

    @Override
    protected GenericService<User, QueryUser> getService() {
        return userService;
    }

    @Override
    public Map<String, Object> get(@RequestBody User entity) throws Exception {
        Map<String,Object> result = new HashMap<String, Object>();
        entity = userService.get(entity);
        if(entity==null){
            result.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
            result.put(SystemStaticConst.MSG,"获取数据失败!");
        }else{
            result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
            result.put(SystemStaticConst.MSG,"获取数据成功!");
            entity.setRoleArray(JsonHelper.list2json( Optional.ofNullable(userService.findByLogin(entity.getLogin())).filter(u->u!=null).orElse(new User()).getRoles()));
            result.put("entity",entity);
        }
        return result;
    }

    /**
     * 功能描述:更新用户状态为禁用/启用
     * @param entity
     * @return
     */
    @RequestMapping(value="/userControl",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    public Map<String,Object> userControl(@RequestBody User entity) throws Exception{
        Map<String,Object> result = new HashMap<String, Object>();
        if(userService.userControl(entity)){
            result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
            result.put(SystemStaticConst.MSG,"更新用户状态成功!");
            result.put("entity",entity);
        }else{
            result.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
            result.put(SystemStaticConst.MSG,"更新用户状态失败!");
        }
        return result;
    }

    /**
     * 功能描述:加载所有的权限数据
     * @return
     */
    @RequestMapping(value = "/loadRoles",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    public Map<String,Object> loadRoles(){
        Map<String,Object> result = new HashMap<String, Object>();
        List<UserRole> userRoleList = userRoleService.query(null);
        result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
        result.put("list",userRoleList);
        return result;
    }


}

      到此处我们完成了对用户管理的集成,接着启动我们的注册中心,链路中心同时启动我们的rbac-produce,接着直接访问我们的swagger工程地址:http://127.0.0.1:8100/swagger-ui.html#/,那么我们会看到如下的页面则表示我们的角色管理已经集成成功了。


      到此为止的GitHub项目地址:https://github.com/185594-5-27/spring-cloud-rbac/tree/master-base-produce-user

上一篇文章地址:基于springboot+redis+bootstrap+mysql开发一套属于自己的分布式springcloud云权限架构(九)【权限架构生产者(角色管理)】

下一篇文章地址:基于springboot+redis+bootstrap+mysql开发一套属于自己的分布式springcloud云权限架构(十一)【权限架构生产者(组织架构)】


QQ交流群:578746866



猜你喜欢

转载自blog.csdn.net/linzhefeng89/article/details/79347414