Commit 54b4049e by levphon

新e盾权限组件

0 parents
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-ne-shield</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>glsx-ne-shield-auth-client</artifactId>
<dependencies>
<!-- feign -->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-feign</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-jwt</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-mybatis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-common</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.auth.api;
import cn.com.glsx.auth.model.MenuPermission;
import cn.com.glsx.auth.model.SyntheticUser;
import com.glsx.plat.core.web.R;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.List;
import java.util.Set;
/**
* @author payu
*/
@FeignClient(name = "glsx-ne-shield-usercenter", contextId = "authcenter", path = "/usercenter/auth/")
public interface AuthFeignClient {
/**
* 嗅探token是否有效(走feign不走网关,走网关网关直接验证了,当需要判断token状态是否有效,可能会使用此接口)
*
* @return
*/
@GetMapping(value = "/sniff", consumes = MediaType.APPLICATION_JSON_VALUE)
R<Boolean> sniff();
/**
* 获取当前登录用户对应资源等权限
*
* @return
*/
@GetMapping(value = "/getAuthUser", consumes = MediaType.APPLICATION_JSON_VALUE)
R<SyntheticUser> getAuthUser();
/**
* 获取当前登录用户角色数据权限内的部门id
*
* @return
*/
@GetMapping(value = "/getAuthDeptIds", consumes = MediaType.APPLICATION_JSON_VALUE)
R<Set<Long>> getAuthDeptIds();
/**
* 获取当前登录用户角色数据权限内的用户id
*
* @return
*/
@GetMapping(value = "/getAuthUserIds", consumes = MediaType.APPLICATION_JSON_VALUE)
R<Set<Long>> getAuthUserIds();
/**
* 获取当前登录用户角色授权的功能菜单
*
* @return
*/
@GetMapping(value = "/getPermMenus", consumes = MediaType.APPLICATION_JSON_VALUE)
R<List<MenuPermission>> getPermMenus();
}
package cn.com.glsx.auth.interceptor;
import cn.com.glsx.auth.api.AuthFeignClient;
import cn.com.glsx.auth.model.FunctionPermissions;
import cn.com.glsx.auth.model.MenuPermission;
import cn.com.glsx.auth.model.SyntheticUser;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.glsx.plat.core.web.R;
import com.glsx.plat.exception.SystemMessage;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* 功能菜单权限
*
* @author: taoyr
**/
@Slf4j
@Component
public class WebFunctionPermissionInterceptor implements HandlerInterceptor {
@Autowired
private AuthFeignClient authFeignClient;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
FunctionPermissions permissionRequired = ((HandlerMethod) handler).getMethodAnnotation(FunctionPermissions.class);
if (permissionRequired == null) {
return true;
}
SyntheticUser currentUser = ShieldContextHolder.getUser();
if (currentUser == null) {
return true;
}
String uri = request.getRequestURI();
log.info("RequestURI:" + uri);
List<MenuPermission> menuPermissionList = Lists.newArrayList();
R<List<MenuPermission>> r = authFeignClient.getPermMenus();
if (r.isSuccess()) {
Object obj = r.getData();
if (obj instanceof JSONArray) {
menuPermissionList = JSON.parseArray(((JSONArray) obj).toJSONString(), MenuPermission.class);
} else if (obj instanceof ArrayList) {
menuPermissionList = (List<MenuPermission>) obj;
}
}
boolean isPermit = menuPermissionList.stream().map(MenuPermission::getInterfaceUrl).collect(Collectors.toList()).contains(uri);
if (!isPermit) {
needPermission(response);
return false;
}
}
return true;
}
private void needPermission(HttpServletResponse response) throws Exception {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
try (PrintWriter writer = response.getWriter()) {
writer.write(JSON.toJSONString(R.error(
SystemMessage.OPERATE_PERMISSION_DENIED.getCode(),
SystemMessage.OPERATE_PERMISSION_DENIED.getMsg())
));
writer.flush();
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
package cn.com.glsx.auth.interceptor;
import cn.com.glsx.auth.api.AuthFeignClient;
import cn.com.glsx.auth.model.SyntheticUser;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import com.alibaba.fastjson.JSON;
import com.glsx.plat.core.web.R;
import com.glsx.plat.exception.SystemMessage;
import com.glsx.plat.jwt.base.ComJwtUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
* 授权验证拦截器
*
* @author payu
*/
@Slf4j
@Component
public class WebRequestAuthorizeInterceptor implements HandlerInterceptor {
@Value("${spring.application.name}")
private String application;
@Autowired
private AuthFeignClient authFeignClient;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
ShieldContextHolder.setUser(null);
ShieldContextHolder.removeUser();
SyntheticUser user = null;
R<SyntheticUser> r = authFeignClient.getAuthUser();
if (r.isSuccess()) {
user = r.getData(SyntheticUser.class);
}
if (user != null) {
ShieldContextHolder.setUser(user);
return true;
}
//需要登录
needLogin(response);
return false;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
ShieldContextHolder.setUser(null);
ShieldContextHolder.removeUser();
}
/**
* 检查token来源
*
* @param jwtUser
* @return
*/
private boolean checkAccessClient(ComJwtUser jwtUser) {
if (jwtUser == null) {
return false;
}
return application.equals(jwtUser.getApplication());
}
private void needLogin(HttpServletResponse response) throws Exception {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
try (PrintWriter writer = response.getWriter()) {
writer.write(JSON.toJSONString(R.error(SystemMessage.NOT_LOGIN.getCode(), SystemMessage.NOT_LOGIN.getMsg())));
writer.flush();
}
}
}
package cn.com.glsx.auth.listener;
import cn.com.glsx.auth.interceptor.DataPermissionInterceptor;
import cn.com.glsx.auth.interceptor.DataPermitLinkInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 此类为了控制mybatis Interceptor执行的顺序,Interceptor调用顺序为后加入的先执行
*/
@Slf4j
@Order
@Component
public class DataCommandLineRunner implements CommandLineRunner {
@Autowired
private List<SqlSessionFactory> sqlSessionFactoryList;
@Override
public void run(String... args) throws Exception {
log.info("CommandLineRunner DataPermissionInterceptor init...");
//先加的后执行
for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
sqlSessionFactory.getConfiguration().addInterceptor(new DataPermitLinkInterceptor());
sqlSessionFactory.getConfiguration().addInterceptor(new DataPermissionInterceptor());
List<Interceptor> interceptorList = sqlSessionFactory.getConfiguration().getInterceptors();
interceptorList.forEach(interceptor -> {
log.info(interceptor.getClass().getSimpleName());
});
}
}
}
package cn.com.glsx.auth.listener;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ApplicationContextEvent;
public class SqlSessionEvent extends ApplicationContextEvent {
/**
* Create a new ContextStartedEvent.
*
* @param source the {@code ApplicationContext} that the event is raised for
* (must not be {@code null})
*/
public SqlSessionEvent(ApplicationContext source) {
super(source);
}
}
package cn.com.glsx.auth.listener;
import cn.com.glsx.auth.interceptor.DataPermissionInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import java.util.List;
@Slf4j
//@Component
public class SqlSessionListener implements ApplicationListener<SqlSessionEvent> {
@Autowired
private List<SqlSessionFactory> sqlSessionFactoryList;
@Override
public void onApplicationEvent(SqlSessionEvent event) {
log.info("SqlSessionListener DataPermissionInterceptor init...");
//先加的后执行
for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
sqlSessionFactory.getConfiguration().addInterceptor(new DataPermissionInterceptor());
}
}
}
package cn.com.glsx.auth.model;
import lombok.Data;
@Data
public class Department {
private Long deptId;
private String departmentName;
private Long tenantId;
}
package cn.com.glsx.auth.model;
import lombok.Getter;
/**
* @author: taoyr
**/
@Getter
public enum FunctionPermissionType {
USER_QUERY(1, "usercenter:user:query", "查询用户"),
USER_ADD(2, "usercenter:user:add", "新增用户"),
USER_EDIT(3, "usercenter:user:edit", "编辑用户"),
USER_DELETE(4, "usercenter:user:delete", "删除用户"),
ROLE_QUERY(1, "usercenter:role:query", "查询角色"),
ROLE_ADD(2, "usercenter:role:add", "新增角色"),
ROLE_EDIT(3, "usercenter:role:edit", "编辑角色"),
ROLE_DELETE(4, "usercenter:role:delete", "删除角色"),
MENU_QUERY(1, "usercenter:menu:query", "查询菜单"),
MENU_ADD(2, "usercenter:menu:add", "新增菜单"),
MENU_EDIT(3, "usercenter:menu:edit", "编辑菜单"),
MENU_DELETE(4, "usercenter:menu:delete", "删除菜单"),
ORG_QUERY(1, "usercenter:org:query", "查询组织"),
ORG_ADD(2, "usercenter:org:add", "新增组织"),
ORG_EDIT(3, "usercenter:org:edit", "编辑组织"),
ORG_DELETE(4, "usercenter:org:delete", "删除组织"),
DEVICE_QUERY(1, "ordercenter:device:query", "查询设备"),
DEVICE_ADD(2, "ordercenter:device:add", "新增设备"),
DEVICE_EDIT(3, "ordercenter:device:edit", "编辑设备"),
DEVICE_DELETE(4, "ordercenter:device:delete", "删除设备"),
;
FunctionPermissionType(int code, String name, String desc) {
this.code = code;
this.name = name;
this.desc = desc;
}
/**
* 权限编号
*/
private int code;
/**
* 权限名
*/
private String name;
/**
* 权限描述
*/
private String desc;
public FunctionPermissionType getByCode(int code) {
FunctionPermissionType[] values = FunctionPermissionType.values();
for (FunctionPermissionType value : values) {
if (code == value.code) {
return value;
}
}
return null;
}
}
package cn.com.glsx.auth.model;
import java.lang.annotation.*;
/**
* 需要功能权限
*
* @author: taoyr
**/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface FunctionPermissions {
FunctionPermissionType permissionType();
}
package cn.com.glsx.auth.model;
import lombok.Data;
import java.io.Serializable;
/**
* @author: taoyr
**/
@Data
public class Menu implements Serializable {
private Long menuId;
/**
* 菜单名
*/
private String menuName;
/**
* 前端路由
*/
private String frontRoute;
/**
* 后端路由
*/
private String afterRoute;
private String permissionTag;
/**
* 类型 1目录,2菜单,3按钮
*/
private Integer type;
/**
* 父菜单id
*/
private Long parentId;
/**
* 排序
*/
private Integer orderNum;
/**
* 状态 0=不显示 1=显示
*/
private Integer enableStatus;
}
package cn.com.glsx.auth.model;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* @author: taoyr
**/
@Data
@Accessors(chain = true)
public class MenuPermission {
private String permissionTag;
private String interfaceUrl;
}
package cn.com.glsx.auth.model;
import lombok.Data;
import java.util.List;
@Data
public class Role {
private Long tenantId;
private Long roleId;
private String roleName;
/**
* 0=共享,1=系统管理员,2=指定租户
*/
private Integer roleVisibility;
/**
* 角色权限类型 0=本人 1=本人及下属 2=本部门 3=本部门及下级部门 4=全部
*/
private Integer rolePermissionType;
private List<MenuPermission> menuPermissionList;
}
package cn.com.glsx.auth.model;
import lombok.Data;
import java.util.List;
import java.util.Set;
@Data
public class SyntheticUser {
private Long userId;
/**
* 用户账号
*/
private String account;
/**
* 用户名称
*/
private String username;
/**
* 是否管理员
*/
private Boolean isSupperAdmin;
/**
* 用户组
*/
// private UserGroup userGroup;
/**
* 用户所属租户
*/
private Tenant tenant;
/**
* 用户所属部门
*/
private Department department;
/**
* 用户角色
*/
private List<Role> roles;
/**
* 数据创建人租户id
*/
private Set<Long> visibleTenantIds;
/**
* 数据创建人部门id
*/
private Set<Long> visibleDeptIds;
/**
* 数据创建人id
*/
private Set<Long> visibleCreatorIds;
}
package cn.com.glsx.auth.model;
import lombok.Data;
@Data
public class Tenant {
private Long tenantId;
private String tenantName;
}
package cn.com.glsx.auth.model;
import lombok.Data;
@Data
public class UserGroup {
private Long tenantId;
private Long groupId;
private String userGroupName;
}
package cn.com.glsx.auth.utils;
import lombok.NoArgsConstructor;
@NoArgsConstructor
public class OriginSqlHolder {
private static final ThreadLocal<String> SQL_THREAD_LOCAL = new ThreadLocal<>();
public static void setSql(String sql) {
SQL_THREAD_LOCAL.set(sql);
}
public static String getSql() {
String sql = SQL_THREAD_LOCAL.get();
return sql;
}
public static void removeSql() {
SQL_THREAD_LOCAL.remove();
}
}
package cn.com.glsx.auth.utils;
import cn.com.glsx.auth.model.Department;
import cn.com.glsx.auth.model.Role;
import cn.com.glsx.auth.model.SyntheticUser;
import cn.com.glsx.auth.model.Tenant;
import lombok.NoArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.util.Assert;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author payu
*/
@NoArgsConstructor
public class ShieldContextHolder {
public static final Long ADMIN_ROLE_ID = 1L;
private static final ThreadLocal<SyntheticUser> USER_THREAD_LOCAL = new ThreadLocal<>();
// 获取当前用户
public static SyntheticUser getUser() {
SyntheticUser user = USER_THREAD_LOCAL.get();
Assert.notNull(user, "获取当前用户信息失败");
return user;
}
// 设置当前用户
public static void setUser(SyntheticUser user) {
USER_THREAD_LOCAL.set(user);
}
// 移除当前用户
public static void removeUser() {
USER_THREAD_LOCAL.remove();
}
public static boolean isSuperAdmin() {
return getUser().getIsSupperAdmin();
}
public static Long getUserId() {
return getUser().getUserId();
}
public static String getAccount() {
return getUser().getAccount();
}
public static String getUsername() {
return getUser().getUsername();
}
// public static UserGroup getUserGroup() {
// SyntheticUser user = getUser();
// return user.getUserGroup();
// }
public static Tenant getTenant() {
SyntheticUser user = getUser();
Tenant tenant = user.getTenant();
Assert.notNull(tenant, "获取当前用户租户信息失败");
return tenant;
}
public static Department getDepartment() {
SyntheticUser user = getUser();
Department dept = user.getDepartment();
Assert.notNull(dept, "获取当前用户部门信息失败");
return dept;
}
public static Long getTenantId() {
return getTenant().getTenantId();
}
public static Long getDepartmentId() {
return getDepartment().getDeptId();
}
public static List<Long> getRoleIds() {
List<Role> roleList = getUser().getRoles();
if (CollectionUtils.isNotEmpty(roleList)) {
return roleList.stream().map(Role::getRoleId).collect(Collectors.toList());
}
return new ArrayList<>();
}
/**
* 获取当前用户角色数据权限可见的租户id
*
* @return
*/
public static Set<Long> getVisibleTenantIds() {
return getUser().getVisibleTenantIds();
}
/**
* 获取当前用户角色数据权限可见的部门id
*
* @return
*/
public static Set<Long> getVisibleDeptIds() {
return getUser().getVisibleDeptIds();
}
/**
* 获取当前用户角色数据权限可见的创建人id
*
* @return
*/
public static Set<Long> getVisibleCreatorIds() {
return getUser().getVisibleCreatorIds();
}
public static Role getRole() {
Role role = getUser().getRoles().get(0);
Assert.notNull(role, "获取当前用户角色信息失败");
return role;
}
public static Long getRoleId() {
return getRole().getRoleId();
}
public static Integer getRoleVisibility() {
return getRole().getRoleVisibility();
}
public static Integer getRolePermissionType() {
return getRole().getRolePermissionType();
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!