赞
踩
之前有写过一篇小记,当时的用户权限管理十分简陋,只通过判断角色名来进行权限控制.属于0.5版本的权限管理.现在,在用户权限管理模块中,除了之前的用户表,角色表,权限表,日志表4大主表外(还有关联表),又增加了url资源表和行为表.为此,之前的low版本的权限管理不可用了,需要一个新的细粒度的权限过滤.
- public class URLRoleFilter implements Filter {
-
- private String redirectPage;
- private String unCheckURL;
-
- @Override
- public void destroy() {
-
- }
-
- @Override
- public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
- throws IOException, ServletException {
- HttpServletRequest request = (HttpServletRequest) req;
- HttpServletResponse response = (HttpServletResponse)resp;
- String servletPath = request.getServletPath();
- String requestMethod = request.getMethod();
- String requestType = request.getHeader("X-Requested-With");
- List<String> unCheckList = Arrays.asList(unCheckURL.split(","));
- if(null!=unCheckList && unCheckList.contains(servletPath)) {
- chain.doFilter(request, response);
- return;
- }
-
- UserLoginInfoModel userLogin = SessionUtil.getUserLogin(request);
- String roleId = userLogin.getRoleId()==null?"":userLogin.getRoleId();
-
- //当前用户无任何角色,且不是注销操作时,跳转无权限页面
- if(StringX.isEmpty(roleId)) {//&& !servletPath.contains("/security/signOut.do")
- if(!StringX.isEmpty(requestType) && "XMLHttpRequest".equals(requestType)) {//ajax请求
- JSONObject result = new JSONObject();
- result.accumulate("success", false);
- result.accumulate("errUrl", request.getContextPath() + redirectPage);
- try {
- response.getWriter().print(result.toString());
- } catch (IOException e) {
- ARE.getLog().error(e);
- }
- }
- else if("POST".equals(requestMethod)) {
- response.setStatus(302);//临时定向响应码
- response.setHeader("Location", request.getContextPath() + redirectPage);//代表转向的地址
- }
- else {
- response.sendRedirect(request.getContextPath() + redirectPage);
- }
- return;
- }
-
- if(!UrlAndActionManager.getInstence().match(servletPath, userLogin)) {//权限匹配不通过
- if(!StringX.isEmpty(requestType) && "XMLHttpRequest".equals(requestType)) {//ajax请求
- JSONObject result = new JSONObject();
- result.accumulate("success", false);
- result.accumulate("errUrl", request.getContextPath() + redirectPage);
- try {
- response.getWriter().print(result.toString());
- } catch (IOException e) {
- ARE.getLog().error(e);
- }
- }
- else if("POST".equals(requestMethod)) {
- response.setStatus(302);//临时定向响应码
- response.setHeader("Location", request.getContextPath() + redirectPage);//代表转向的地址
- }
- else {
- response.sendRedirect(request.getContextPath() + redirectPage);
- }
- return;
-
- }
-
- chain.doFilter(request, response);
- }
-
- @Override
- public void init(FilterConfig cfg) throws ServletException {
- ServletContext context = cfg.getServletContext();
- redirectPage = context.getInitParameter("noRolePage");
- unCheckURL = context.getInitParameter("unCheckURL");
-
- }
-
- }
- public class InitUrlAndActionManagerServlet extends HttpServlet {
-
- private static final long serialVersionUID = 1L;
-
- public void init(ServletConfig config) throws ServletException {
- ARE.getLog().info("资源权限管理器初始化开始");
- UrlAndActionManager.getInstence();
- ARE.getLog().info("资源权限管理器初始化完成");
- }
- }
- public class UrlAndActionManager extends Thread{
-
- private ReadWriteLock lock; //读写锁
- private boolean updateFlag; //管理类map是否正在更新 标志位
- private Map<String,String> urlMap; //存放url表数据
- private Map<String,String> actionMap; //存放行为表数据
- private UrlDao urlDao; //url表操作类
- private ActionDao actionDao; //行为表操作类
- private boolean dbChangeFlag; //数据库信息是否改变 标志位
-
- private static class UrlAndActionManagerHolder{
- private static final UrlAndActionManager INSTANCE = new UrlAndActionManager();
- }
-
- private UrlAndActionManager(){
- lock = new ReentrantReadWriteLock(false);
- updateFlag = false;
- urlMap = new HashMap<String,String>();
- actionMap = new HashMap<String,String>();
- urlDao = new UrlDao();
- actionDao = new ActionDao();
- dbChangeFlag = false;
-
- init();
- }
-
- public static UrlAndActionManager getInstence() {
- return UrlAndActionManagerHolder.INSTANCE;
- }
-
- private void init(){
- lock.writeLock().lock();
- urlDao.loadUrls(urlMap);
- actionDao.loadActions(actionMap);
-
- ARE.getLog().info("urlMap :");
- Set set1 = urlMap.keySet();
- for (Object object : set1) {
- ARE.getLog().info(object + " : " + urlMap.get(object));
- }
- ARE.getLog().info("actionMap :");
- Set set2 = actionMap.keySet();
- for (Object object : set2) {
- ARE.getLog().info(object + " : " + actionMap.get(object));
- }
-
- lock.writeLock().unlock();
- this.setName("定期监视资源表更新情况线程");
- this.start();
- }
-
- //用户权限匹配
- public boolean match(String postUrl, UserLoginInfoModel userLogin) {
- boolean result = false;
- if(null == userLogin) {
- return result;
- }
- String privileges = userLogin.getPrivilegeId();
- if(StringX.isEmpty(privileges)) {
- privileges = ",,";
- }
- else {
- privileges = "," + privileges + ",";
- }
-
- ARE.getLog().debug("postUrl : " + postUrl);
- ARE.getLog().debug("userId : " + userLogin.getUserId());
- ARE.getLog().debug("privileges : " + privileges);
- if(updateFlag) {//当前正在更新map时,从数据库获取权限进行比较
- ARE.getLog().debug("从数据库中匹配权限");
- String permission = null;
- permission = urlDao.findPermissionByUrlId(postUrl);
- if(null == permission) {
- permission = actionDao.findPermissionByActionId(postUrl);
- if((null != permission && privileges.contains(","+permission+",")) || "".equals(permission)) {
- result = true;
- }
- }
- else {
- if(null != permission && privileges.contains(","+permission+",")) {
- result = true;
- }
- }
- }
- else {//当前不在更新map时,从map中获取权限进行比较
- ARE.getLog().debug("从内存中匹配权限");
- lock.readLock().lock();
- String url = null;
- url = urlMap.get(postUrl);
- if(null == url) {//请求为 请求行为资源
- String action = null;
- action = actionMap.get(postUrl);
- if(null == action) {
- result = false;
- }
- else {
- if("".equals(action)) {
- result = true;
- }
- else if(privileges.contains(","+action+",")) {
- result = true;
- }
- else {
- result = false;
- }
- }
- }
- else {//请求为 请求url资源
- if("".equals(url)) {
- result = true;
- }
- else if(privileges.contains(","+url+",")) {
- result = true;
- }
- else {
- result = false;
- }
- }
- lock.readLock().unlock();
- }
- return result;
- }
-
- @Override
- public void run() {
- while(true) {
- try {
- Thread.sleep(1000*60*5);//每隔5分钟执行一次
- } catch (InterruptedException e) {
- ARE.getLog().debug(e);
- }
- ARE.getLog().info(this.getName() + " - 开始检测资源权限是否更新");
- lock.writeLock().lock();
- if(!updateFlag) {
- updateFlag = true;
- urlDao.loadPermissionUpdateDatas(urlMap);
- actionDao.loadPermissionUpdateDatas(actionMap);
- updateFlag = false;
- }
- lock.writeLock().unlock();
- ARE.getLog().info(this.getName() + " - 完成检测资源权限是否更新");
- }
- }
-
- public void dbChange() {
- dbChangeFlag = true;
- }
- }
- public class ActionDao {
-
- public List<String> getActionIds() {
- Connection conn = null;
- PreparedStatement statement = null;
-
- try {
- conn = ARE.getDBConnection("craw");
- List<String> result = new ArrayList<>();
- String sql = "select actionId from security_manage_action";
- statement = conn.prepareStatement(sql);
- ResultSet resultSet = statement.executeQuery();
- if(null != resultSet) {
- while(resultSet.next()) {
- String actionId = resultSet.getString("actionId");
- result.add(actionId);
- }
- }
- resultSet.close();
-
- return result;
- } catch(SQLException e) {
- ARE.getLog().error(e);
- return null;
- } finally {
- try {
- if(null != statement) {
- statement.close();
- statement = null;
- }
- if(null != conn) {
- conn.close();
- conn = null;
- }
- } catch(SQLException e) {
- ARE.getLog().error(e);
- }
- }
- }
-
- public void initAtionRecords(List<String> loads) {
- Connection conn = null;
- PreparedStatement statement = null;
- PreparedStatement statement2 = null;
-
- try {
- conn = ARE.getDBConnection("craw");
- conn.setAutoCommit(false);
-
- if(null == loads || 0 == loads.size()) {//加载到项目中配置的url数组为空,将数据库中数据删除
- String sqlAllDel = "delete from security_manage_action";
- statement = conn.prepareStatement(sqlAllDel);
- statement.executeQuery();
- conn.commit();
- return;
- }
-
- List<String> olds = getActionIds();
- if(null != olds) {
- List<String> contains = new ArrayList<>();
- for (String string : olds) {
- if(loads.contains(string)) {
- contains.add(string);
- }
- }
- loads.removeAll(contains); //数据库中没有,项目中存在的路由
- olds.removeAll(contains); //数据库中有,项目中不存在的路由
- String sqlAdd = "INSERT security_manage_action(actionId,actionName,permission,updateVersion) VALUES(?,'','',1)";
- String sqlDel = "DELETE FROM security_manage_action where actionId=?";
- if(loads.size() > 0) {
- statement = conn.prepareStatement(sqlAdd);
- for (String actionId : loads) {
- statement.setString(1, actionId);
- statement.addBatch();
- }
- }
- if(olds.size() > 0) {
- statement2 = conn.prepareStatement(sqlDel);
- for (String actionId : olds) {
- statement2.setString(1, actionId);
- statement2.addBatch();
- }
- }
-
- if(loads.size() > 0 || olds.size() > 0) {
- if(null != statement) {
- statement.executeBatch();
- }
- if(null != statement2) {
- statement2.executeBatch();
- }
- conn.commit();
- }
- }
- } catch(SQLException e) {
- try {
- conn.rollback();
- } catch (SQLException e1) {
- ARE.getLog().error(e1);
- }
- ARE.getLog().error(e);
- } finally {
- try {
- if(null != statement2) {
- statement2.close();
- statement2 = null;
- }
- if(null != statement) {
- statement.close();
- statement = null;
- }
- if(null != conn) {
- conn.setAutoCommit(true);
- conn.close();
- conn = null;
- }
- } catch(SQLException e) {
- ARE.getLog().error(e);
- }
- }
-
- }
-
- public boolean loadActions(Map<String,String> actionMap) {
- boolean result = true;
- Connection conn = null;
- PreparedStatement statement = null;
-
- try {
- conn = ARE.getDBConnection("craw");
- String sql = "select actionId,permission from security_manage_action";
- statement = conn.prepareStatement(sql);
- ResultSet resultSet = statement.executeQuery();
- if(null == resultSet) {
- result = false;
- }
- else {
- while(resultSet.next()) {
- actionMap.put(resultSet.getString("actionId"),resultSet.getString("permission"));
- }
- resultSet.close();
- }
- } catch (SQLException e) {
- result = false;
- ARE.getLog().error(e);
-
- } finally {
- try {
- if(null != statement) {
- statement.close();
- statement = null;
- }
- if(null != conn) {
- conn.close();
- conn = null;
- }
- } catch(SQLException e) {
- ARE.getLog().error(e);
- }
- }
- return result;
- }
-
- public boolean loadPermissionUpdateDatas(Map<String,String> actionMap) {
- boolean result = true;
- Connection conn = null;
- PreparedStatement statement = null;
- PreparedStatement statement2 = null;
-
- try {
- conn = ARE.getDBConnection("craw");
- conn.setAutoCommit(false);
- //查找所有更新permission的数据
- String sql = "select actionId,permission,updateVersion from security_manage_action where isUpdate='Y'";
- statement = conn.prepareStatement(sql);
- ResultSet resultSet = statement.executeQuery();
-
- //将isUpdate置为N
- String sql2 = "update security_manage_action set isUpdate='N',updateVersion=updateVersion+1 where actionId=? and updateVersion=? and isUpdate='Y'";
- int count = 0;
- statement2 = conn.prepareStatement(sql2);
- if(null == resultSet) {
- result = false;
- }
- else {
- while(resultSet.next()) {
- count++;
- actionMap.put(resultSet.getString("actionId"),resultSet.getString("permission"));
- statement2.setString(1, resultSet.getString("actionId"));
- statement2.setInt(2, resultSet.getInt("updateVersion"));
- statement2.addBatch();
- }
- resultSet.close();
- }
- if(count > 0) {
- statement2.executeUpdate();
- }
-
- conn.commit();
- } catch (SQLException e) {
- if(null != conn) {
- try {
- conn.rollback();
- } catch (SQLException e1) {
- ARE.getLog().error(e1);;
- }
- }
- result = false;
- ARE.getLog().error(e);
-
- } finally {
- try {
- if(null != statement2) {
- statement2.close();
- statement2 = null;
- }
- if(null != statement) {
- statement.close();
- statement = null;
- }
- if(null != conn) {
- conn.setAutoCommit(true);
- conn.close();
- conn = null;
- }
- } catch(SQLException e) {
- ARE.getLog().error(e);
- }
- }
- return result;
- }
-
- public String findPermissionByActionId(String actionId) {
- String result = null;
- Connection conn = null;
- PreparedStatement statement = null;
-
- try {
- conn = ARE.getDBConnection("craw");
- String sql = "select permission from security_manage_action where actionId=?";
- statement = conn.prepareStatement(sql);
- statement.setString(1, actionId);
- ResultSet resultSet = statement.executeQuery();
- if(null != resultSet) {
- resultSet.last();
- int count = resultSet.getRow();
- if(count > 0) {
- result = resultSet.getString("permission");
- }
- resultSet.close();
- }
-
- if(null == result) {
- result = "";
- }
- } catch(SQLException e) {
- ARE.getLog().error(e);
- } finally {
- try {
- if(null != statement) {
- statement.close();
- statement = null;
- }
- if(null != conn) {
- conn.close();
- conn = null;
- }
- } catch(SQLException e) {
- ARE.getLog().error(e);
- }
- }
- return result;
- }
-
- }
- public class GetAllJspServlet extends HttpServlet {
-
- private static final long serialVersionUID = 1L;
-
- public void init(ServletConfig config) throws ServletException {
- ARE.getLog().info("GetAllJspServlet start");
- ServletContext context = config.getServletContext();
- ARE.getLog().info("GetAllJspServlet start");
- String[] dirs = {"craw","security","frame/page","parse"};//要扫描的文件目录
- List<String> loads = new ArrayList<>();//存储jsp相对路径
-
- for (int i = 0; i < dirs.length; i++) {
- File file = new File(context.getRealPath("/") + dirs[i]);
- String fatherPath = file.getAbsolutePath();
- ARE.getLog().info("dir : " + fatherPath);
- File[] files = file.listFiles();
- if(null != files && files.length > 0) {
- for (int j = 0; j < files.length; j++) {
- String filePath = "/" + dirs[i] + files[j].getPath().replace(fatherPath, "");
- if(filePath.endsWith(".jsp")) {
- ARE.getLog().info(filePath);
- loads.add(filePath);
- }
- }
- }
- }
-
- new UrlDao().initUrlRecords(loads);
- ARE.getLog().info("GetAllJspServlet end");
- }
- }
- public class GetAllRequestMappingServlet extends HttpServlet {
-
- private static final long serialVersionUID = 1L;
-
- public void init(ServletConfig config) throws ServletException {
- ARE.getLog().info("GetAllRequestMappingServlet start");
- // 查找所以springMVC配置的url
- ServletContext context = config.getServletContext();
- WebApplicationContext webApp = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
-
- RequestMappingHandlerMapping rmhp = webApp.getBean(RequestMappingHandlerMapping.class);
- Map<RequestMappingInfo, HandlerMethod> map = rmhp.getHandlerMethods();
- List<String> loads = new ArrayList<>();
- for (Iterator<RequestMappingInfo> iterator = map.keySet().iterator(); iterator.hasNext();) {
- RequestMappingInfo info = iterator.next();
- String url = info.getPatternsCondition().toString();
- if (url.length() >= 2) {
- url = url.substring(1, url.length() - 1);
- loads.add(url);
- ARE.getLog().info(url);
- }
- }
-
- // 查找web.xml中配置的url
- try {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- DocumentBuilder builder = factory.newDocumentBuilder();
-
- File file = new File(context.getRealPath("/")+"WEB-INF/web.xml");
- Document doc = (Document) builder.parse(file);
- NodeList nodeList = doc.getElementsByTagName("url-pattern");
- for (int i = 0; i < nodeList.getLength(); i++) {
- Element tyes = (Element)nodeList.item(i);
- Text textNode = (Text) tyes.getFirstChild();
- String text = textNode.getData().trim();
- if(!"null".equals(text) && !text.contains("*")){
- ARE.getLog().info(text);
- if(!loads.contains(text)) {
- loads.add(text);
- }
- }
- }
- } catch (Exception e) {
- ARE.getLog().error(e);
- }
- ARE.getLog().info("GetAllRequestMappingServlet init db");
- new ActionDao().initAtionRecords(loads);
- ARE.getLog().info("GetAllRequestMappingServlet end");
- }
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。