Henghe Warehouse – role management, enabling or disabling roles, assigning permissions to roles

Role management

Article directory

  • role management
  • 1. Query roles by page
    • 1.1 Entity class
      • 1.1.1 Pagination entity class
      • 1.1.2 Role entity class
    • 1.2 Paging business implementation
      • 1.2.1 Mapper
      • 1.2.2 Service
      • 1.2.3 Controller
      • 1.2.4 Renderings
  • 2. Add roles
    • 2.1 Mapper
    • 2.2 Service
    • 2.3 Controller
    • 2.4 Renderings
  • 3. Enable or disable roles
    • 2.1 Mapper
    • 2.2 Service
    • 2.3 Controller
    • 2.4 Renderings
  • 4. Delete the role
    • 4.1 Mapper
    • 4.2 Service
    • 4.3 Controller
    • 4.4 Renderings
  • 5. Assign permissions to roles
    • 5.1 Entity class
      • 5.1.1 Permission entity class
    • 5.2 Query all permission menu trees
      • 5.2.1 Mapper
      • 5.2.2 Service
      • 5.2.3 Controller
      • 5.2.4 Renderings
    • 5.3 Echoing the permissions of the current role
      • 5.3.1 Mapper
      • 5.3.2 Service
      • 5.3.3 Controller
      • 5.3.4 Renderings
    • 5.4 Assign permissions to roles
      • 5.4.1 Entity class
      • 5.4.2 Mapper
      • 5.4.3 Service
      • 5.4.4 Controller
      • 5.4.5 Renderings

1. Query roles by page

image-20230813213748270

1.1 Entity class

1.1.1 Pagination entity class

/**
 *Paging information entity class:
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Page {<!-- -->

    //Current page number
    private Integer pageNum;

    //Display the number of rows per page
    private Integer pageSize;

    //Total number of rows
    private Integer totalNum;

    //total pages
    private Integer pageCount;

    //limit function parameter - starting line of each page
    private Integer limitIndex;

    //List<?> collection that stores the data queried on the current page
    private List<?> resultList;

    //Calculate the total number of pages
    public Integer getPageCount() {<!-- -->
        return (totalNum%pageSize==0) ? totalNum/pageSize : totalNum/pageSize + 1;
    }

    //Calculate the limit function parameter - the starting line of each page
    public Integer getLimitIndex() {<!-- -->
        return pageSize * (pageNum-1);
    }

1.1.2 Role entity class

/**
 * Entity class of role table
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Role implements Serializable {<!-- -->

    private int roleId;//role id

    private String roleName;//role name

    private String roleDesc;//role description

    private String roleCode;//role identification

    private String roleState;//role status

    private int createBy;//User ID to create the role

    //Date format for json conversion
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date createTime; //Creation time

    private int updateBy;//Modify the user id of the role

    private Date updateTime;//modification time

    private String getCode;//Additional attributes--the username of the user who created the role
}

1.2 Paging business implementation

1.2.1 Mapper

//Method to query the number of character rows
    public Integer findRoleRowCount(@Param("role") Role role);
// Method to query roles in pages
    public List<Role> findRolePage(@Param("page")Page page,@Param("role")Role role);
 <!--Query the total number of records-->
    <select id="findRoleRowCount" resultType="java.lang.Integer">
        select count(*)
        from role r
        <where>
            <if test="role.roleName !=null and role.roleName!='' ">
                 r.role_name like concat('%', #{role.roleName}, '%')
            </if>
            <if test="role.roleCode !=null and role.roleCode!='' ">
                and r.role_code like concat('%', #{role.roleCode}, '%')
            </if>
            <if test="role.roleState !=null and role.roleState!='' ">
                and r.role_state = #{role.roleState}
            </if>
        </where>
    </select>
    <!--Paging query data-->
    <select id="findRolePage" resultType="com.pn.entity.Role">
        select t1.*, t2.user_code getCode
        from role t1, user_info t2
        <where>
            t1.create_by = t2.user_id
            <if test="role.roleName != null and role.roleName != ''">
                and t1.role_name like concat('%', #{role.roleName}, '%')
            </if>
            <if test="role.roleCode != null and role.roleCode != ''">
                and t1.role_code like concat('%', #{role.roleCode}, '%')
            </if>
            <if test="role.roleState != null and role.roleState != ''">
                and t1.role_state = #{role.roleState}
            </if>
            order by t1.create_time desc
            limit #{page.limitIndex}, #{page.pageSize}
        </where>
    </select>

1.2.2 Service

 @Override
    public Page queryRolePage(Page page, Role role) {<!-- -->
        Integer roleRowCount = roleMapper.findRoleRowCount(role);
//Set the total number
        page.setTotalNum(roleRowCount);
// Where to start setting
        page.setLimitIndex(page.getLimitIndex());
//Set the total number of pages
        page.setPageCount(page.getPageCount());
// Query data by page
        List<Role> rolePage = roleMapper.findRolePage(page, role);
        page.setResultList(rolePage);
        return page;
    }

1.2.3 Controller

 //Query roles by paging
    @RequestMapping("/role-page-list")
    public Result roleListPage(Page page, Role role) {<!-- -->
        return Result.ok(roleService.queryRolePage(page,role));
    }

1.2.4 Renderings

image-20230813223151165

image-20230813225628756

2. Add role

Consider whether the new role exists

Query whether a role already exists based on role name or role code

image-20230813225808309

2.1 Mapper

//How to query roles based on role name or role code
    public Role findRoleByNameOrCode(@Param("roleName")String roleName,@Param("roleCode")String roleCode);

//Method to add roles
    public int insertRole(@Param("role")Role role);
<select id="findRoleByNameOrCode" resultType="com.pn.entity.Role">
    select *
    from role
    where role_name = #{roleName}
       or role_code = #{roleCode}
</select>
<insert id="insertRole">
    insert into role
        (role_name, role_code, role_desc, role_state, create_by, create_time)
    values (#{role.roleName}, #{role.roleCode}, #{role.roleDesc}, 0, #{role.createBy}, now())
</insert>

2.2 Service

 @CacheEvict(key = "'all:role'")//Remember to clear the role information in a Redis cache
    @Override
    public Result saveRole(Role role) {<!-- -->
        Role roleByNameOrCode = roleMapper.findRoleByNameOrCode(role.getRoleName(), role.getRoleCode());
        if (roleByNameOrCode != null){<!-- -->
            return Result.err(Result.CODE_ERR_BUSINESS, "Failed to add role! The role already exists");
        }
        int success = roleMapper.insertRole(role);

        return success > 0 ? Result.ok("Add successfully") : Result.err(Result.CODE_ERR_BUSINESS, "Failed to add role");
    }

2.3 Controller

//Add role
@RequestMapping("/role-add")
public Result addRole(@RequestBody Role role, @RequestHeader("Token") String token) {<!-- -->
    CurrentUser currentUser = tokenUtils.getCurrentUser(token);
    role.setCreateBy(currentUser.getUserId());
    
    return roleService.saveRole(role);
}

2.4 Renderings

image-20230813235236381

image-20230813235250175

image-20230814000716601

3. Enable or disable roles

2.1 Mapper

//Method to modify role status based on role id
    public int setRoleStateByRid(@Param("roleId")Integer roleId,@Param("roleState")String roleState);
<update id="setRoleStateByRid">
    update role
    set role_state=#{roleState}
    where role_id = #{roleId}
</update>

2.2 Service

 @CacheEvict(key = "'all:role'")//Remember to clear the role information in a Redis cache
    @Override
    public Result setRoleStateByRid(Role role) {<!-- -->
        int success = roleMapper.setRoleStateByRid(role.getRoleId(), role.getRoleState());
        return success > 0 ? Result.ok("Status modification successful") : Result.err(Result.CODE_ERR_BUSINESS, "Status modification failed");
    }

2.3 Controller

 //Enable or disable the role's url interface
    @RequestMapping("/role-state-update")
    public Result updateRoleState(@RequestBody Role role){<!-- -->
        return roleService.setRoleStateByRid(role);
    }

2.4 Renderings

image-20230814153925915

image-20230814153946449

Added that after disabling “Out of Library”, the “Out of Library” role cannot be seen when assigning roles to users.

image-20230814154059299

4. Delete role

When deleting, you can only delete it individually

Also remember to delete the content in the role-user relationship table

Remember to delete the content in the role permissions table

4.1 Mapper

//How to delete a role based on role id
    public int removeRoleById(@Param("roleId") Integer roleId);
<delete id="removeRoleById">
    delete
    from role
    where role_id = #{roleId}
</delete>
//Delete the corresponding relationship in the user_role table based on the role id
    public int deleteRoleUserRelation(@Param("roleId") Integer roleId);
<delete id="deleteRoleUserRelation">
    delete
    from user_role
    where role_id = #{roleId}
</delete>
//Delete the corresponding relationship in the user_role table based on the role id
public int deleteRoleAuthRelation(@Param("roleId") Integer roleId);
<delete id="deleteRoleAuthRelation">
    delete
    from role_auth
    where role_id = #{roleId}
</delete>

4.2 Service

 @CacheEvict(key = "'all:role'")//Remember to clear the role information in a Redis cache
    @Override
    public Result deleteRoleById(Integer roleId) {<!-- -->
        int successRole = roleMapper.removeRoleById(roleId);
        if (successRole>0){<!-- -->
// Delete the corresponding content in the user role relationship
             roleMapper.deleteRoleUserRelation(roleId);
//Delete role permission relationship
            authMapper.deleteRoleAuthRelation(roleId);
        }
        return Result.ok("Deletion successful");
    }

4.3 Controller

//Delete the url interface of the role
@RequestMapping("/role-delete/{roleId}")
public Result deleteRole(@PathVariable("roleId") Integer roleId){<!-- -->
 return roleService.deleteRoleById(roleId);
}

4.4 Renderings

Delete the role “Purchasing”, the ID is 11

image-20230814161143302

There is no role_id 11 in the user_role table

image-20230814161338020

There is no data with role_id 11 in the role_auth table

image-20230814161444932

5. Assign permissions to roles

5.1 Entity class

The first is to query all permissions menu trees

/auth/auth-tree Query all permission menu trees

The second is to query the permissions of a certain user (permission echo)

/role/role-auth?roidId=17 Query the permissions of a role based on roleId

5.1.1 Permission entity class

/**
 * Entity class of auth_info table:
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Auth {<!-- -->

   private int authId; //Permission (menu) id

   private Integer parentId;//parent permission (menu) id

   private String authName; //Permission (menu) name

   private String authDesc; //Permission (menu) description

   private int authGrade; //Permission (menu) level

   private String authType; //Permission (menu) type

   private String authUrl;//URL interface for permission (menu) access

   private String authCode; //Permission (menu) identification

   private int authOrder;//Priority of permissions (menu)

   private String authState; //Permission (menu) status (1. Enabled, 0. Disabled)

   private int createBy;//User ID for creating permissions (menu)

   private Date createTime;//Creation time of permission (menu)

   private int updateBy;//Modify the user ID of permissions (menu)

   private Date updateTime;//Modification time of permissions (menu)

   //Added List<Auth> collection attribute -- used to store sub-level permissions (menu) of the current permissions (menu)
   private List<Auth> childAuth;
}

image-20230814215154273

5.2 Query all permission menu trees

5.2.1 Mapper

How to query all permission menus

//How to query all permission menus
    public List<Auth> findAllAuth();

Values of auth_type 1 module , 2 list , 3 button

 <select id="findAllAuth" resultType="com.pn.entity.Auth">
        select *
        from auth_info
        where auth_state = 1and auth_type !='3'
    </select>

5.2.2 Service

How to query all permission menus

 @Cacheable("'all:authTree'")
    @Override
    public List<Auth> allAuthTree() {<!-- -->
// Query all permission menus
        List<Auth> allAuth = authMapper.findAllAuth();
// Convert all permission menus into menu trees
        return allAuthToAuthTree(allAuth, 0);
    }

    // Convert all menu List<Auth> into menu tree List<Auth>
//The first time, the pid is 0
    private List<Auth> allAuthToAuthTree( List<Auth> allAuthList,Integer pid){<!-- -->
        List<Auth> firstLevelAuthList = new ArrayList<>();

// Query all n-level menus (for example, first-level menu)
        for (Auth auth:allAuthList){<!-- -->
// pid=0, indicating that it is the first level menu
           if ( auth.getParentId().equals(pid)){<!-- -->
               firstLevelAuthList.add(auth);
           }
        }
// Get the (n + 1) level menu of each n level menu
        for (Auth firstAuth: firstLevelAuthList){<!-- -->
//Recurse, get (n + 1) level menu
            List<Auth> secondLevelAuthList = allAuthToAuthTree(allAuthList,firstAuth.getAuthId());
            firstAuth.setChildAuth(secondLevelAuthList);
        }

        return firstLevelAuthList;
    }

5.2.3 Controller

How to query all permission menus

@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {<!-- -->
    @Autowired
    private AuthService authService;

    @RequestMapping("/auth-tree")
    public Result loadAllAuthTree(){<!-- -->
        return Result.ok(authService.allAuthTree());
    }
}

5.2.4 Renderings

image-20230814222132934

5.3 Echoing permissions of the current role

/role/role-auth?roidId=17 Query all permission IDs assigned to the role based on roleId

5.3.1 Mapper

//Method to query all assigned permission menus based on role id
    public List<Integer> findAuthIdByRid(@Param("roleId") Integer roleId);
 <select id="findAuthIdByRid" resultType="java.lang.Integer">
                select auth_info.auth_id
                from role_auth,
                     auth_info
                where role_auth.auth_id = auth_info.auth_id
                  and role_auth.role_id = #{roleId}
                  and auth_info.auth_state=1
                  and auth_info.auth_type != 3
    </select>

5.3.2 Service

 @Override
    public List<Integer> findAuthByRid(Integer roleId) {<!-- -->
        return authMapper.findAuthIdByRid(roleId);
    }

5.3.3 Controller

 @Autowired
    private AuthService authService;

    @RequestMapping("/role-auth")
    public Result roleAuth(Integer roleId){<!-- -->
        return Result.ok( authService.findAuthByRid(roleId));

5.3.4 Renderings

image-20230814225732526

5.4 Assign permissions to roles

5.4.1 Entity class

/**
 * Dto class that receives data passed by the front end of assigning permissions (menu) to roles:
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class AssignAuthDto {<!-- -->

    //Receive request parameter roleId -- role id
    private Integer roleId;

    //Receive the request parameter authIds -- the IDs of all permissions (menu) assigned to the role
    private List<Integer> authIds;
}

5.4.2 Mapper

//Delete the corresponding relationship in the user_role table based on the role id
public int deleteRoleAuthRelation(@Param("roleId") Integer roleId);
<delete id="deleteRoleAuthRelation">
    delete
    from role_auth
    where role_id = #{roleId}
</delete>
//Method to add role permission relationship
    public int insertRoleAuth(@Param("roleId") Integer roleId,@Param("authId") Integer authId);
<insert id="insertRoleAuth">
    insert into role_auth
     values (null ,#{roleId},#{authId})
</insert>

5.4.3 Service

 @Transactional
    @Override
    public void saveRoleAuth(AssignAuthDto assignAuthDto) {<!-- -->
//Delete the previous correspondence between roles and permissions
        authMapper.deleteRoleAuthRelation(assignAuthDto.getRoleId());
//Add role permission relationship
        List<Integer> authIds = assignAuthDto.getAuthIds();
        for (Integer authId : authIds){<!-- -->
            authMapper.insertRoleAuth(assignAuthDto.getRoleId(),authId);
        }

    }

5.4.4 Controller

@RequestMapping("/auth-grant")
public Result grantAuth(@RequestBody AssignAuthDto assignAuthDto){<!-- -->
       roleService.saveRoleAuth(assignAuthDto);
       return Result.ok("Permissions assigned successfully");
}

5.4.5 Renderings

image-20230814233035355