1 Star 0 Fork 102

傻根她弟 / open-scope

forked from mofum / open-scope 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

open-scope

介绍

OpenScope是一种轻量级、易维护的数据权限的解决方案,它能处理比较复杂的权限操作逻辑。兼容操作权限Shiro等框架。

OpenScope提供了一种基于SQL的智能添加权限范围列的方案,相对原始的数据权限方案,它是轻量级的,它只有一些配置代码,同时它也是提高了代码的可维护性。另外它不需要额外的更改您的程序结构,就能轻松使您的项目支持数据权限操作。

什么是操作权限,什么是数据权限详细见WIKI 简介

1.0.0.0.RELEASE 版本功能介绍

  • 支持Mybatis- SQL 根据权限范围列动态数据行过滤(兼容PageHelper,OrderBy等其他Mybatis插件)
  • 支持多个范围类型,多个业务对象指定范围类型。
  • 兼容shiro、spring-security等操作权限框架,也可以独立存在,因为它拥有完善的认证流程。
  • 参数额外支持JSON(spring-web包)
  • 支持自定义错误异常返回,这个异常返回。

1.0.1.0.RELEASE 版本功能介绍

  • 将数据权限的粒度控制到数据列上。[-]

  • 对ORM-HIBERNATE兼容或者对ORM-JDBC(任选其一)[-]

    (注:[-] 表示待开发或者正在开发中,[√]表示已完成)

1.0.0.0.RELEASE原理:

 ORM-Mybatis过滤原理:通过对SQL智能的添加权限列来到的基于权限范围的数据过滤。

1.0.0.0.RELEASE版本的默认流程:

考虑性能的原因:

我们给了一套默认的权限配置,对查询多条数据只进行数据过滤操作,对单挑数据的操作只执行转换操作和认证操作。这对Spring-Cloud相关的微服务项目很有帮助。减少了各个模块之间相互调用的次数,提升了服务器的处理能力和响应能力。 但是如果您不考虑性能的问题,而是考虑权限认证操作的流程的完整性。你仍然可以为每一个请求开启过滤、转换,认证三个操作。

(注:可以根据业务的范围或者实际需求进行调整,ORM-Mybatis过滤是基于SQL,所以请务必要保证您的查询结果集合里存在配置的范围列字段,否则执行权限范围过滤的过程中会抛出找不到范围列的异常信息。[SQLException: Column 您配置的权限范围列 not found异常。])

组件的过滤流程:
  1. 控制层请求 >
  2. 控制层切面 >
  3. 执行范围提取器获得权限范围 >
  4. 将权限范围设置到scopeCollections中 >
  5. 进入业务切面 >
  6. 将业务切面类上的TableScope内容完善到scopeCollections中 >
  7. 进入权限拦截器 >
  8. 根据scopeCollections的内容进行智能拼装SQL
组件的认证流程
  1. 控制层请求 >
  2. 控制层切面 >
  3. 进入权限范围转换器 获得业务对象,将业务对象转换成范围对象 >
  4. 将范围对象交给权限认证器 >
  5. 认证器向您的认证服务中心提供的认证权限的接口发起请求 >
  6. 您的具体业务逻辑 >
  7. 如果认证器里没有抛出异常,则认证成功 >
  8. 如果认证器里抛出异常,则认证失败 >

软件架构

OpenScope分为多个组件

  • 权限范围认证器(IScopeAuthenticator)

    主要用于向您的认证中心发起认证消息。你可以在这里面写一些您的认证中心的发起逻辑。

  • 权限范围提取器(IScopeExtractor)

    主要用于从您的认证中心提取业务范围数据,并将其设置到List<Scope> scopeCollections中。用于权限拦截器动态拼装权限范围等内容。

  • 权限范围转换器(IScopeConverter)

    主要用于业务对象ID转换范围对象ID。

  • 错误异常处理器(ThrowableHandler)

    主要用于统一处理权限认证的错误异常类

  • ORM-权限拦截器 (Permission)

    智能的对SQL进行拦截,并为其添加权限范围过滤列。

子包说明

  • scope-common (公用的模型定义)
  • scope-annotation(公用的注解)
  • scope-orm-mybatis(ORM框架有关的内容)
  • scope-spring-web(Spring-web相关的内容)
  • scope-autoconfigure(自动配置内容)
  • scope-boot-starter(SpringBoot相关内容)

安装方法(SpringBoot)

<!-- openScope依赖 -->
<dependency>
    <groupId>com.mofum.scope</groupId>
    <artifactId>scope-boot-starter</artifactId>
    <version>1.0.0.1.RELEASE</version>
</dependency>
            

(注:如果是SpringCloud项目,如果子项目不需要Mybatis,请移除相关的依赖)

<!-- openScope依赖(不包含orm-mybatis) -->
<dependency>
  <groupId>com.mofum.scope</groupId>
  <artifactId>scope-boot-starter</artifactId>
  <version>1.0.0.1.RELEASE</version>
  <exclusions>
    <exclusion>
      <groupId>com.mofum.scope</groupId>
      <artifactId>scope-orm-mybatis</artifactId>
    </exclusion>
    <exclusion>
      <groupId>com.mofum.scope</groupId>
      <artifactId>scope-autoconfiure</artifactId>
    </exclusion>
  </exclusions>
</dependency>

使用方法(SpringBoot版本)

以下内容详细请见:https://gitee.com/mofum/open-scope-demo

SpringBoot Application 类

@SpringBootApplication
@ComponentScan(value = {
        "com.mofum.scope.controller",//控制器
        "com.mofum.scope.service",//本地逻辑具体业务
        "com.mofum.scope.config"
})
@MapperScan("com.mofum.scope.mapper")
@EnableAutoConfiguration
@EnableAspectJAutoProxy    //开启切面控制
public class Application {

    public static void main(String[] args) {
        ApplicationContext applicationContext = SpringApplication.run(Application.class, args);

        IUserService userService = applicationContext.getBean(UserServiceImpl.class);

        userService.initTable();
    }
}

控制层(Controller)

@RestController
@RequestMapping("/user")
public class UserController extends ScopeController {

    public static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    IUserService userService;

    @RequestMapping("/add")
    public Object addUser(User user) {
        userService.addUser(user);
        return "SUCCESS";
    }

    @RequestMapping("/query")
    public Object query(UserDto userDto) {
        logger.info(userDto.toString());
        return userService.queryUser(userDto);
    }

    @RequestMapping("/scope/query")
    @QueryScope
    public Object scopeQuery(UserDto userDto) {
        logger.info(userDto.toString());
        return userService.queryUser(userDto);
    }

    @RequestMapping("/del")
    @UpdateScope(columns = {
            @ServiceColumn(value = "serviceIds")
    })
    public Object del(UserDto userDto) {
        logger.info(userDto.toString());
        return "SUCCESS";
    }
}

业务层(Service)

@Service
@TableScope(columns = {
        /**
         * @see com.mofum.scope.controller.ScopeController 中的extractorScopes()方法
         */
        @ColumnScope(type = "ScopeOne", value = "scope_one") //配置列type 是类型,scope_one是表中的列
})
public class UserServiceImpl implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public void initTable() {
        userMapper.createTable();
    }

    @Override
    public void addUser(User user) {
        if (user != null) {
            user.setId(UUID.randomUUID().toString());
        }
        userMapper.insertUser(user);
    }

    @Override
    public List<User> queryUser(UserDto user) {
        return userMapper.queryUser(user);
    }

    @Override
    public int delete(UserDto userDto) {
        return 0;
    }
}

配置业务对象转换器(ScopeConvert)【必须】

public class ScopeController implements IScopeConverter<Object, RuntimeException> {

    @Override
    public List<Scope> convert2Scope(Object o) throws RuntimeException {
        //转换业务对象为ScopeId
        List<Scope> scopes = new ArrayList<>();
        Scope scope = new Scope();
        scope.setId("1");
        scope.setType("ScopeOne"); //Type和IUserService 中的注解ColumnScope要指定同一个注解才能生效
        scopes.add(scope);
        return scopes;
    }

}

配置SQL范围提取器(ScopeExtractor)【必须】

public class ScopeController implements IScopeExtractor<Object, RuntimeException> {

    
    @Override
    public List<? extends Scope> extractorScopes(Object o) throws RuntimeException {

        //提取权限数据范围

        //假设只有SCOPE_ONE只有权限范围1

        List<Scope> scopes = new ArrayList<>();
        Scope scope = new Scope();
        scope.setId("1");
        scope.setType("ScopeOne"); //Type和IUserService 中的注解ColumnScope要指定同一个注解才能生效
        scopes.add(scope);

        return scopes;
    }

}

配置认证器(ScopeAuthenticator)【必须】

public class ScopeController implements IScopeAuthenticator<List<Scope>, RuntimeException>{


    @Override
    public boolean testAccess(List<Scope> scopes) throws RuntimeException {

        //取用户ID
        String userId = getRequest().getParameter("userId");

        //取请求URL

        String url = getRequest().getRequestURI();


        boolean accessFlag = false;
        //验证权限逻辑
        for (Scope scope : scopes) {

            if (scope.getId().equals("2")) {
                return true;
            }

        }

        if (!accessFlag) {
            throw new RuntimeException("Operation failed!Cause no permission!(action :" + url + ")");
        }

        return accessFlag;
    }


    public HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    public HttpServletResponse getResponse() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        return response;
    }

}

配置权限拦截器(Config PermissionInterceptor )【必须】

@Configuration
public class MybatisScopeAutoConfiguration {

    @Autowired
    private List<SqlSessionFactory> sqlSessionFactoryList;

    public MybatisScopeAutoConfiguration() {
    }

    @PostConstruct
    public void addTestInterceptor() {
        PermissionInterceptor interceptor = new PermissionInterceptor();
        Iterator var3 = this.sqlSessionFactoryList.iterator();

        while (var3.hasNext()) {
            SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) var3.next();
            sqlSessionFactory.getConfiguration().addInterceptor(interceptor);
        }

    }
}

配置业务切面 (Config Scan Service Aspect)【必须】

@Component
@Aspect
public class ServiceAspectJ extends AbstractColumnAspectJ {

    //配置业务切面
    @Override
    @Pointcut("execution(* com.mofum.scope.service..*.*(..))")
    public void config() {

    }
}

配置控制切面 (Config Scan Service Aspect)【必须】

@Component
@Aspect
public class ControllerAspectJ extends AbstractControllerAspectJ {

    private ThrowableHandler throwableHandler;

    //配置控制切面
    @Override
    @Pointcut("execution(* com.mofum.scope.controller..*.*(..))")
    public void config() {

    }

    @Override
    public ThrowableHandler getThrowableHandler() {
        if(throwableHandler == null){
            throwableHandler = new ControllerThrowableHandler();
        }

        return throwableHandler;
    }

    @Override
    public void setThrowableHandler(ThrowableHandler throwableHandler) {
        this.throwableHandler = throwableHandler;
    }
}

配置异常处理器 (Config ErrorHandler) 【非必须】

public class ControllerThrowableHandler implements ThrowableHandler {

    @Override
    public void handler(Throwable throwable) throws Throwable {

        if (throwable != null) {
            getResponse().setCharacterEncoding("UTF-8");
            getResponse().getWriter().println(throwable.getMessage());
            throwable.printStackTrace();
        }

    }

    public HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    public HttpServletResponse getResponse() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        return response;
    }

}
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under com.mofum.scope.common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

OpenScope是一种轻量级、易维护的“数据权限”的解决方案,它能处理比较复杂的“数据权限”操作逻辑。兼容Shiro等操作权限框架。 展开 收起
Java
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Java
1
https://gitee.com/godson_2003/open-scope.git
git@gitee.com:godson_2003/open-scope.git
godson_2003
open-scope
open-scope
master

搜索帮助