View Javadoc
1   /**
2    * Copyright By Grandsoft Company Limited.  
3    * 2012-3-16 下午02:28:13
4    */
5   package gboat2.web.business.impl;
6   
7   import gboat2.base.core.cache.ICacheService;
8   import gboat2.base.core.dao.QuerySupport;
9   import gboat2.base.core.service.BaseService;
10  import gboat2.base.bridge.exception.DefaultGboatNestedException;
11  import gboat2.web.Constants;
12  import gboat2.web.business.IAuthorityBusiness;
13  import gboat2.web.business.IDataLevelAuthorityBusiness;
14  import gboat2.web.business.IGroupBusiness;
15  import gboat2.web.business.IOperationBusiness;
16  import gboat2.web.business.IResourceBusiness;
17  import gboat2.web.business.IRoleBusiness;
18  import gboat2.web.model.Authority;
19  import gboat2.web.model.AuthorityDataLevelResourceVO;
20  import gboat2.web.model.AuthorityOperationResourceVO;
21  import gboat2.web.model.AuthorityOperationVO;
22  import gboat2.web.model.AuthorityResourceVO;
23  import gboat2.web.model.DataLevelAuthority;
24  import gboat2.web.model.Group;
25  import gboat2.web.model.Operation;
26  import gboat2.web.model.Resource;
27  import gboat2.web.model.Role;
28  
29  import java.util.ArrayList;
30  import java.util.HashMap;
31  import java.util.List;
32  import java.util.Map;
33  
34  import org.apache.commons.lang3.StringUtils;
35  import org.springframework.beans.factory.annotation.Autowired;
36  import org.springframework.stereotype.Service;
37  import org.springframework.transaction.annotation.Transactional;
38  
39  /**
40   * 授权操作
41   * @author wangsr
42   * @modified by sunpf 2012-4-15
43   * @since jdk1.6
44   * @date 2012-3-16
45   */
46  @Transactional
47  @Service
48  public class AuthorityBusinessImpl extends BaseService implements IAuthorityBusiness {
49  
50  	@Autowired
51  	private IOperationBusiness operaBusi;
52  
53  	@Autowired
54  	private IResourceBusiness resourceBusi;
55  
56  	@Autowired
57  	private IDataLevelAuthorityBusiness dataLevelAuthorityBusi;
58  
59  	@Autowired
60  	private IGroupBusiness groupBusi;
61  
62  	@Autowired
63  	private IRoleBusiness roleBusi;
64  
65  	@Autowired
66  	private ICacheService cacheSer;
67  
68  	//private Logger logger = LoggerFactory.getLogger(AuthorityBusinessImpl.class.getName());
69  	
70  
71  	@Override
72  	public boolean setAuthority(String authForId, String resId) {
73  		/**
74  		 * 添加模块的权限:
75  		 * 1.添加模块的全部权限
76  		 * 2.添加其父模块的访问权限
77  		 * 3.添加其子模块的全部权限
78  		 */
79  		if (StringUtils.isEmpty(authForId) || StringUtils.isEmpty(resId)) {
80  			return false;
81  		}
82  		Resource res = (Resource) super.get(Resource.class, resId);
83  		this.addResourceAuthority(authForId, res);
84  		this.addResourceAuthorityForParent(authForId, res);
85  		this.addResourceAuthorityForChild(authForId, res);
86  		return true;
87  	}
88  
89  	@Override
90  	public boolean deleteAuthority(String authForId, String resId, String systemId) {
91  		if (StringUtils.isEmpty(authForId) || StringUtils.isEmpty(resId) || StringUtils.isEmpty(systemId)) {
92  			return false;
93  		}
94  		/**【第一次定制用户组权限的时候,初始化用户组的角色权限】
95  		 *当为用户组的角色第一次定制权限的时候,其实用户组角色的权限还没有分配,
96  		 *权限树之所以显示选中状态,那是其角色的权限,参见findResourceForRole方法。
97  		 *从角色的权限中为用户组的角色授权authForId格式为"groupId.roleId"
98  		 *[用户的定制同用户组中角色定制相同]
99  		 */
100 		//删除时需要考虑是否为定制,如果是定制则需要copy权限
101 		this.cascadeSetAuthAtFirstDel(authForId, resId, systemId);
102 		/** 删除授权 start */
103 		this.deleteResourceAuthority(authForId, resId);// 删除当前节点
104 		this.deleteResourceAuthorityOfChild(authForId, resId);//删除孩子节点
105 		/** 删除授权 end */
106 		return true;
107 	}
108 
109 	@Override
110 	public boolean setOperationsAuthority(String authForId, String resId, String operaId) {
111 	 	/**
112 		 * 设置操作权限分3步
113 		 * 1.添加对模块中操作的权限
114 		 * 2.如果组中有无效的此操作权限,将其置为有效
115 		 */
116 		
117 		if (StringUtils.isEmpty(authForId) || StringUtils.isEmpty(resId) || StringUtils.isEmpty(operaId)) {
118 			return false;
119 		}
120 		Resource res = (Resource) get(Resource.class, resId);
121 		//1.添加对operation的授权
122 		this.saveAuthority(authForId, resId, res.getSystemId(), operaId, "1");
123 		//2.添加角色对operation的权限,还原组内角色继承的已经失效的权限
124 		this.cascadeAuth(true, authForId, resId, operaId);
125 		return true;
126 	}
127 
128 	@Override
129 	public boolean deleteOperationAuthority(String authForId, String resId, String operaId, String systemId) {
130 		if (StringUtils.isEmpty(authForId) || StringUtils.isEmpty(resId) 
131 				|| StringUtils.isEmpty(operaId) || StringUtils.isEmpty(systemId)) {
132 			return false;
133 		}
134 
135 		// 用户组第一次定制操作权限的时候,首先复制所有的角色权限(继承),再删除要删除的权限
136 		//第一次删除的时候需要copy权限
137 		this.cascadeSetAuthAtFirstDel(authForId, resId, systemId);
138 		//删除操作权限
139 		this.deleteOpertionAuthorityBy(authForId, resId, operaId);
140 		//在删除角色或组角色操作权限的时候,需要级联设置继承权限为无效
141 		this.cascadeAuth(false, authForId, resId, operaId);
142 		return true;
143 	}
144 		
145 	@Override
146 	public boolean isAuthorityCustomize(String authForId,String systemId){
147 		String hql = "select count(authId) from Authority where authForId=:authForId and systemId=:systemId";
148 		Map<String, Object> params = new HashMap<String, Object>();
149 		params.put("authForId", authForId);
150 		params.put("systemId", systemId);
151 		List<?> result = super.baseDAO.queryListByHql(hql, params);
152 		Long sum = (Long) result.get(0);
153 		return sum.longValue() > 0;
154 	}
155 
156 	@Override
157 	public List<Authority> findAuthoritiesByAuthForId(String authForId, String systemId) {
158 		String[][] params = { { Authority.class.getName() }, { "_authForId", authForId }, { "_systemId", systemId } };
159 		return (List<Authority>) super.baseDAO.queryList(params);
160 	}
161 
162 	@Override
163 	public List<AuthorityResourceVO> findBrothersAuthorityForResource(String roleId, String resId) {
164 		List<AuthorityResourceVO> brothers = null;
165 		Resource res = (Resource) super.get(Resource.class, resId);
166 		Resource parent = (Resource) super.get(Resource.class, res.getParentId());
167 		if (parent != null) {
168 			String[][] params = { { AuthorityResourceVO.class.getName() }, { QuerySupport.PARAM_DISTINCT, "true" }, { "_authForId", roleId },
169 					{ "_parentId", parent.getResId() }, { "_resId_ne", resId }, { "_useStatus", "1" } };
170 			brothers = (List<AuthorityResourceVO>) super.baseDAO.queryList(params);
171 		}
172 		return brothers;
173 	}
174 	
175 	@Override
176 	public List<Operation> findOperationsForResource(String resId) {
177 		List<Operation> allOpera = null;
178 		allOpera = this.operaBusi.getOperationsByResourceId(resId);
179 		return allOpera;
180 	}
181 
182 	@Override
183 	public List<AuthorityOperationVO> findOperationsForRole(String resId, String roleId) {
184 		List<AuthorityOperationVO> result = null;
185 		//_operationId_notnull 支持不存在operation只对Resource的授权(operas为空,则什么也查不到,即没有操作)
186 		String[][] params = { { AuthorityOperationVO.class.getName() }, { QuerySupport.PARAM_DISTINCT, "true" }, { "_authForId", roleId },
187 				{ "_resId", resId }, { "_operationId_notnull", "true" }, { "_useStatus", "1" } };
188 		result = (List<AuthorityOperationVO>) super.baseDAO.queryList(params);
189 		return result;
190 	}
191 
192 	@Override
193 	public boolean deleteAuthorityByRoleId(String roleId) {
194 		String hql = "delete from Authority where authForId=:roleId or authForId like '%." + roleId + "'";
195 		Map<String, Object> params = new HashMap<String, Object>();
196 		params.put("roleId", roleId);
197 		super.baseDAO.deleteByQuery(hql, params);
198 		return true;
199 	}
200 
201 	@Override
202 	public List<AuthorityResourceVO> getAuthorityByStatus(String status, String systemId) {
203 		if (StringUtils.isEmpty(systemId)) {
204 			return null;
205 		}
206 		Map<String, Object> params = new HashMap<String, Object>();
207 		params.put(QuerySupport.PARAM_TABLENAME, AuthorityResourceVO.class);
208 		params.put("_authForId", status);
209 		params.put("_systemId", systemId);
210 		params.put("_useStatus", "1");
211 		List<AuthorityResourceVO> list = (List<AuthorityResourceVO>) super.query(params);
212 		return list;
213 	}
214 
215 	@Override
216 	public String findDataLevelForRoleOfGroup(String groupId, String roleId, String resId) {
217 		DataLevelAuthority auth = this.dataLevelAuthorityBusi.findDataLevelAuthority(groupId, roleId, resId);
218 		if (auth != null) {// 找到则返回定制的级别
219 			return auth.getDataLevel();
220 		} else {// 没有找到,则返回用户组默认的级别
221 			Group group = (Group) this.groupBusi.get(Group.class, groupId);
222 			return group.getDefaultDataLevel();
223 		}
224 	}
225 
226 	@Override
227 	public List<AuthorityOperationVO> findOperationsForRoleOfGroup(String groupId, String roleId, String resId) {
228 		String[][] params = { { AuthorityOperationVO.class.getName() }, { QuerySupport.PARAM_DISTINCT, "true" },
229 				{ "_authForId", groupId + "." + roleId }, { "_resId", resId }, { "_useStatus", "1" }, { "_operationId_notnull", "true" } };
230 		List<AuthorityOperationVO> operations = (List<AuthorityOperationVO>) baseDAO.queryList(params);
231 		if (null == operations || 0 == operations.size()) {
232 			//判断是否自动继承角色的权限(查看用户组中的该角色是否定制过,定制过则无需继承,因为是他定制的没有操作权限)
233 			Resource res = (Resource) super.get(Resource.class, resId);
234 			List<Authority> auth = this.findAuthoritiesByAuthForId(groupId + "." + roleId, res.getSystemId());
235 			if (auth == null || auth.size() == 0) {
236 				// TODO 如果用户定制之后为全部取消的状态,则无法判断是否定制过。此处按没有定制处理
237 				// 没有定制过,说明还是初始化的状态,则初始化改角色的所有操作权限
238 				operations = this.findOperationsForRole(resId, roleId);
239 			}
240 		}
241 		return operations;
242 	}
243 
244 	@Override
245 	public List<AuthorityResourceVO> getTopLevelAuths(String authForId, String systemId) {
246 		List<AuthorityResourceVO> auths = this.getAuthsByLevel(authForId, "0", systemId);
247 		return auths;
248 	}
249 
250 	@Override
251 	public List<AuthorityOperationResourceVO> getAuthorityOperationResource(String authForId, String systemId) {
252 		if (StringUtils.isEmpty(systemId)) {
253 			return null;
254 		}
255 		Map<String, Object> params = new HashMap<String, Object>();
256 		params.put(QuerySupport.PARAM_TABLENAME, AuthorityOperationResourceVO.class);
257 		params.put("_authForId", authForId);
258 		params.put("_systemId", systemId);
259 		params.put("_useStatus", "1");
260 		List<AuthorityOperationResourceVO> list = (List<AuthorityOperationResourceVO>) super.query(params);
261 		return list;
262 	}
263 
264 	@Override
265 	public List<AuthorityDataLevelResourceVO> getAuthorityDataLevelResource(String groupId, String roleId, String systemId) {
266 		if (StringUtils.isEmpty(systemId)) {
267 			return null;
268 		}
269 		Map<String, Object> params = new HashMap<String, Object>();
270 		params.put(QuerySupport.PARAM_TABLENAME, AuthorityDataLevelResourceVO.class);
271 		params.put("_groupId", groupId);
272 		params.put("_systemId", systemId);
273 		params.put("_roleId", roleId);
274 		List<AuthorityDataLevelResourceVO> list = (List<AuthorityDataLevelResourceVO>) super.query(params);
275 		return list;
276 	}
277 
278 	@Override
279 	public AuthorityResourceVO findResourceTreeForRoleOfSystem(String roleId, String systemId) {
280 		AuthorityResourceVO root = null;
281 		root = this.findResourceTreeForRole(roleId, "0", systemId);
282 		return root;
283 	}
284 
285 
286 	@Override
287 	public List<AuthorityResourceVO> getAuthorityResourceByStatus(String authForId, String systemId) {
288 		if (StringUtils.isEmpty(systemId)) {
289 			return null;
290 		}
291 		Map<String, Object> params = new HashMap<String, Object>();
292 		params.put(QuerySupport.PARAM_TABLENAME, AuthorityResourceVO.class);
293 		params.put("_authForId", authForId);
294 		params.put("_systemId", systemId);
295 		List<AuthorityResourceVO> list = (List<AuthorityResourceVO>) super.query(params);
296 		return list;
297 	}
298 
299 	@Override
300 	public boolean deleteAuthorityOfCustom(String authForId, String systemId) {
301 		String hql = "delete from Authority where systemId='" + systemId + "' and authForId = :authForId";
302 		Map<String, Object> params = new HashMap<String, Object>();
303 		params.put("authForId", authForId);
304 		super.baseDAO.deleteByQuery(hql, params);
305 		return true;
306 	}
307 
308 	@Override
309 	public boolean setDataLevelAuthority(String groupId, String roleId, String resId, String dataLevel) {
310 		return this.dataLevelAuthorityBusi.setDataLevelAuthority(groupId, roleId, resId, dataLevel);
311 	}
312 
313 	@Override
314 	public boolean deleteAuthorityByLikeGroupId(String groupId) {
315 		String hql = "delete from Authority where authForId like '" + groupId + ".%'";
316 		super.baseDAO.deleteByQuery(hql, null);
317 		return true;
318 	}
319 
320 	@SuppressWarnings("unchecked")
321 	@Override
322 	public List<AuthorityResourceVO> getAuthsByLevel(String authForId, String resId, String systemId) {
323 		Map<String, Object> queryParams = new HashMap<String, Object>();
324 		queryParams.put(QuerySupport.PARAM_TABLENAME, AuthorityResourceVO.class.getName());
325 		queryParams.put(QuerySupport.PARAM_DISTINCT, true);
326 		queryParams.put(QuerySupport.PARAM_ORDERBY, "dispOrder");
327 		queryParams.put("_authForId", authForId);
328 		queryParams.put("_parentId", resId);
329 		queryParams.put("_useStatus", "1");
330 		//过滤以:“##”开头的模块,这些在角色权限树中不显示
331 		queryParams.put("_block", "RES_NAME not like '##%'");
332 		//如果resId==0,则取得该角色在该系统下的所有顶级模块。(因为parentId==0,没有办法确定系统)
333 		//如果resId!=0,则resId的系统就已经确定,无需添加systemId条件
334 		if ("0".equals(resId) && systemId != null) {
335 			queryParams.put("_systemId", systemId);
336 		}
337 		List<AuthorityResourceVO> auths = (List<AuthorityResourceVO>) baseDAO.queryList(queryParams);
338 		return auths;
339 	}
340 
341 	@Override
342 	public AuthorityResourceVO findResourceTreeForRoleOfGroupOfSystem(String authForId, String systemId, boolean useCache) {
343 		AuthorityResourceVO root = null;
344 		if (useCache) {
345 			root = (AuthorityResourceVO) this.cacheSer.get(Constants.MENU_TREE_CACHE_CATALOG, authForId + "-" + systemId);
346 			if (null == root) {
347 				root = this.findResourceTreeForRoleOfGroup(authForId, "0", systemId);
348 				//只缓存完整的权限树,取得时候,截取一部分子树
349 				this.cacheSer.put(Constants.MENU_TREE_CACHE_CATALOG, authForId + "-" + systemId, root);
350 			}
351 		} else {
352 			root = this.findResourceTreeForRoleOfGroup(authForId, "0", systemId);
353 		}
354 		return root;
355 	}
356 
357 	@Override
358 	public AuthorityResourceVO findResourceTreeForRoleOfGroupForRes(String authForId, String resId, boolean useCache) {
359 		AuthorityResourceVO root = null;
360 		Resource res = null;
361 		if (StringUtils.isEmpty(resId)) {
362 			return root;
363 		}
364 		if (resId.startsWith("##")) {
365 			//此时的resId是resName
366 			res = resourceBusi.getResourceByResname(resId);
367 		} else {
368 			res = (Resource) super.get(Resource.class, resId);
369 		}
370 		AuthorityResourceVO ret = new AuthorityResourceVO();
371 		if (useCache) {
372 			root = (AuthorityResourceVO) this.cacheSer.get(Constants.MENU_TREE_CACHE_CATALOG, authForId + "-" + res.getSystemId());
373 			if (null == root) {
374 				root = this.findResourceTreeForRoleOfGroup(authForId, "0", res.getSystemId());
375 				//只缓存完整的权限树,取得时候,截取一部分子树
376 				this.cacheSer.put(Constants.MENU_TREE_CACHE_CATALOG, authForId + "-" + res.getSystemId(), root);
377 			}
378 		} else {
379 			root = this.findResourceTreeForRoleOfGroup(authForId, "0", res.getSystemId());
380 		}
381 		// 从角色树上截取子树
382 		root = this.getChildrenByResId(root, resId);
383 
384 		//对结果封装
385 		ret.setResName("root");// 附加信息,不影响树的显示
386 		ret.setResId("0");
387 		ret.setLeaf(false);
388 		List<Resource> children = new ArrayList<Resource>();
389 		children.add(root);
390 		ret.setChildren(children);
391 		return ret;
392 	}
393 
394 	@Override
395 	public List<String> findAllAuthForIdBySysIdAndRoleId(String systemId, String roleId) {
396 		List<String> ret = null;
397 		String sql = "select distinct auth_for_id from g2_t_authority where system_id='" + systemId + "' and auth_for_id like '%." + roleId + "'";
398 		ret = (List<String>) super.baseDAO.queryListBySql(sql, null);
399 		return ret;
400 	}
401 
402 	@Override
403 	public List<Resource> findAllAuthResOfParentByRoleCode(String parentCode, String roleCode) {
404 		Role role = roleBusi.findRoleByRoleCode(roleCode);
405 		Resource resource = resourceBusi.getResourceByCode(parentCode);
406 		return findChildResourceListForRole(role.getRoleId(), resource.getResId(), resource.getSystemId());
407 	}
408 
409 	@Override
410 	public List<AuthorityOperationVO> findOperationsForUser(String groupId, String roleId, String userId, String resId) {
411 		String[][] params = { { AuthorityOperationVO.class.getName() }, { QuerySupport.PARAM_DISTINCT, "true" },
412 				{ "_authForId", groupId + "." + roleId + "." + userId }, { "_resId", resId }, { "_useStatus", "1" },
413 				{ "_operationId_notnull", "true" } };
414 		List<AuthorityOperationVO> operations = (List<AuthorityOperationVO>) baseDAO.queryList(params);
415 		if (null == operations || 0 == operations.size()) {
416 			//判断是否自动继承组角色的权限(查看登录用户否定制过,定制过则无需继承,因为是他定制的没有操作权限)
417 			Resource res = (Resource) super.get(Resource.class, resId);
418 			List<Authority> auth = this.findAuthoritiesByAuthForId(groupId + "." + roleId + "." + userId, res.getSystemId());
419 			if (auth == null || auth.size() == 0) {
420 				// TODO 如果用户定制之后为全部取消的状态,则无法判断是否定制过。此处按没有定制处理
421 				// 没有定制过,说明还是初始化的状态,继承组角色
422 				operations = this.findOperationsForRoleOfGroup(groupId, roleId, resId);
423 			}
424 		}
425 		return operations;
426 	}
427 
428 	@Override
429 	public List<AuthorityResourceVO> findResourceOfSystemByAuthForId(String authForId, String systemId) {
430 		if (StringUtils.isBlank(authForId) || StringUtils.isBlank(systemId)) {
431 			throw new NullPointerException("authForId or systemId is not null!");
432 		} else {
433 			String[] ids = authForId.split("\\.");
434 			int len = ids.length;
435 			switch(len){
436 				case 1 : return this.findResourceForRole(authForId, systemId);//角色权限
437 				case 2 : return this.findResourceForGroupRole(authForId, systemId);//组角色权限
438 				case 3 : return this.findResourceForGroupRoleUser(authForId, systemId);//登录用户权限
439 				default : throw new DefaultGboatNestedException("authForId=【" + authForId + "】格式错误,应该为:groupId.roleId.userId。");
440 			}
441 		}
442 	}
443 	
444 	
445 	@Override
446 	public boolean setDataLevelAuthority(String groupId, String roleId, String userId, String resId, String dataLevel) {
447 		boolean ret = this.dataLevelAuthorityBusi.setDataLevelAuthority(groupId, roleId, userId, resId, dataLevel);
448 		return ret;
449 	};
450 	
451 
452 	/**
453 	 * 取得角色的所有权限
454 	 * @author wangsr
455 	 * @param roleId 角色id
456 	 * @param systemId 系统id
457 	 * @return 所有权限list
458 	 */
459 	private List<AuthorityResourceVO> findResourceForRole(String roleId, String systemId) {
460 		List<AuthorityResourceVO> ret = this.getResourceForRoleOfSystem(roleId, systemId);
461 		return ret;
462 	};
463 
464 	/**
465 	 * 取得组角色权限
466 	 * @author wangsr
467 	 * @param groupRoleId 组角色id
468 	 * @param systemId 系统id
469 	 * @return 权限list
470 	 */
471 	private List<AuthorityResourceVO> findResourceForGroupRole(String groupRoleId, String systemId) {
472 		//对于组角色指定的权限authForId为“groupId.roleId”
473 		List<AuthorityResourceVO> result = null;
474 		// 读取组角色权限
475 		result = this.getResourceForRoleOfSystem(groupRoleId, systemId);
476 
477 		/*
478 		 *如果是用户组的角色权限,即groupId.roleId:如果还还没有定制过权限,则result为空(组角色的定制的标志,groupId.roleId是否存在)
479 		 *但是,显示的时候,他应该拥有角色的所有权限,所以,查出角色的权限用于权限树的回填。
480 		 *需要注意的是,此时数据库中并没有存储用户组角色的权限。
481 		 *只有定制后,才会将角色的权限拷贝到用户组的角色中(第一次定制的时候,即第一次调用deleteAuthority方法的时候)
482 		 */
483 		if (result == null || result.size() == 0) {//没有定制过,或定制为空
484 			// 查询出角色的权限
485 			String[] splited = groupRoleId.split("\\.");
486 			String roleId = splited[1];
487 			result = this.getResourceForRoleOfSystem(roleId, systemId);
488 			if (result != null && result.size() > 0) {
489 				// 如果权限是继承的,则标识一下,以便使用
490 				for (AuthorityResourceVO auRe : result) {
491 					auRe.setInheritFlag("true");
492 					auRe.setInheritFrom("role");
493 				}
494 			}
495 		}
496 		return result;
497 	};
498 
499 	/**
500 	 * 取得登录用户权限
501 	 * @author wangsr
502 	 * @param groupRoleUserId 组角色用户id
503 	 * @param systemId 系统id
504 	 * @return 权限list
505 	 */
506 	private List<AuthorityResourceVO> findResourceForGroupRoleUser(String groupRoleUserId, String systemId) {
507 		//对于组角色用户指定的权限authForId为“groupId.roleId.userId”
508 		List<AuthorityResourceVO> result = null;
509 		// 登录用户的权限
510 		result = this.getResourceForRoleOfSystem(groupRoleUserId, systemId);
511 		if (null == result || result.size() == 0) {//没有定制过,从组角色继承
512 			String[] ids = groupRoleUserId.split("\\.");
513 			String groupRoleId = ids[0] + "." + ids[1];
514 			result = this.findResourceForGroupRole(groupRoleId, systemId);
515 			if (result != null && result.size() > 0) {
516 				// 如果权限是继承的,则标识一下,以便使用
517 				for (AuthorityResourceVO auRe : result) {
518 					String inheritFlag = auRe.getInheritFlag();
519 					if (!"true".equals(inheritFlag)) {
520 						auRe.setInheritFlag("true");
521 						auRe.setInheritFrom("group");
522 					}
523 				}
524 			}
525 		}
526 		return result;
527 	}
528 	
529 	/**
530 	 * @author wangsr
531 	 * @param root
532 	 * @param resId
533 	 * @return
534 	 */
535 	private AuthorityResourceVO getChildrenByResId(AuthorityResourceVO root, String resId) {
536 		AuthorityResourceVO ret = null;
537 		if (resId.equals(root.getResId())) {
538 			ret = root;//递归结束的条件
539 		} else {
540 			List<Resource> list = root.getChildren();
541 			if (list != null && list.size() > 0) {
542 				for (Resource r : list) {
543 					ret = this.getChildrenByResId((AuthorityResourceVO) r, resId);
544 					if (null != ret && resId.equals(ret.getResId())) {
545 						break;
546 					}
547 				}
548 			}
549 		}
550 		return ret;
551 	}
552 
553 	/**
554 	 * 取得用户组角色权限树的一部分,如果resId==0是,取得全部的用户组角色权限树模块
555 	 * @author wangsr
556 	 * @param authForId 角色Id
557 	 * @param resId 模块Id
558 	 * @return 用户组的模块树
559 	 */
560 	private AuthorityResourceVO findResourceTreeForRoleOfGroup(String authForId, String resId, String systemId) {
561 		AuthorityResourceVO root = null;
562 		// 用户组角色的权限(authForId = groupId.roleId),如果没有查到,则继承角色的权限
563 		root = this.findResourceTreeForRole(authForId, resId, systemId);
564 		// 用户没有定制权限,则继承角色的权限
565 		if (null != root && 0 == root.getChildren().size() && authForId.indexOf(".") != -1) {
566 			// 查询出角色的权限
567 			String[] splited = authForId.split("\\.");
568 			String roleId = splited[1];
569 			root = this.findResourceTreeForRole(roleId, resId, systemId);
570 		}
571 		return root;
572 	}
573 
574 	/**
575 	 * 取得角色模块树的一部分(即:原角色模块树的一个节点),如果resId==0时,取得全部的角色权限树模块树
576 	 * resId == 0的角色树<br>
577 	 * |--a<br>
578 	 * |--b<br>
579 	 *   &nbsp;&nbsp;|--b1<br>
580 	 *   &nbsp;&nbsp;|--b2<br>
581 	 * |--c<br>
582 	 * resId == b,则角色树的子树,形如:<br>
583 	 * |--b<br>
584 	 *   &nbsp;&nbsp;|--b1<br>
585 	 *   &nbsp;&nbsp;|--b2<br>
586 	 * @author wangsr
587 	 * @param authForId 角色Id
588 	 * @param resId 模块Id
589 	 * @return 角色模块树
590 	 */
591 	private AuthorityResourceVO findResourceTreeForRole(String authForId, String resId, String systemId) {
592 		AuthorityResourceVO root = new AuthorityResourceVO();
593 		root.setResName("root");// 附加信息,不影响树的显示
594 		root.setResId("0");
595 		root.setLeaf(false);
596 
597 		List<Resource> list = findChildResourceListForRole(authForId, resId, systemId);
598 
599 		// 如果是角色权限树的子树,则应该包含当前模块;resName以##开头的模块除外.
600 		if (!"0".equals(resId)) {
601 			Resource curr = (Resource) this.resourceBusi.get(Resource.class, resId);
602 			String resName = curr.getResName() + "";
603 			//resName以##开头的模块除外.
604 			if (!resName.startsWith("##")) {
605 				if (curr != null) {
606 					//当前模块的子树
607 					List<Resource> sub = new ArrayList<Resource>();
608 					// 将当前节点的子节点插入
609 					curr.setChildren(list);
610 					curr.setLeaf(this.isLeaf(curr));
611 
612 					// 将当前节点作为唯一的一个节点插入,因为子树前台要显示当前子节点
613 					sub.add(curr);
614 					root.setChildren(sub);
615 				}
616 			}
617 		} else {
618 			root.setChildren(list);
619 		}
620 		return root;
621 	}
622 	
623 	
624 	/**
625 	 * 判断模块是否叶子节点
626 	 * @author wangsr
627 	 * @param res 模块
628 	 * @return 是否是叶子节点
629 	 */
630 	private boolean isLeaf(Resource res) {
631 		return null == res.getChildren() || res.getChildren().size() == 0;
632 	}
633 
634 	/**
635 	 * 递归查询模块的子节点
636 	 * @author wangsr
637 	 * @param res 模块
638 	 * @param roleId 角色Id
639 	 * @return 子节点
640 	 */
641 	private List<Resource> getChildrenRecursively(Resource res, String roleId) {
642 		List<AuthorityResourceVO> children = this.getResourceForRole(roleId, res.getResId());
643 		List<Resource> list = new ArrayList<Resource>();
644 		for (AuthorityResourceVO child : children) {
645 			child.setChildren(this.getChildrenRecursively(child, roleId));
646 			child.setLeaf(this.isLeaf(child));
647 
648 			// 将AuthorityResource转化成Resource,用于展示,因为前者是后者的子类
649 			// Resource tmp = child;
650 			list.add(child);
651 		}
652 		return list;
653 	}
654 
655 	/**
656 	 * 取得角色某个模块的子模块
657 	 * @author wangsr
658 	 * @param roleId 角色id
659 	 * @param parentResId 父模块id
660 	 * @return 权限
661 	 */
662 	private List<AuthorityResourceVO> getResourceForRole(String roleId, String parentResId) {
663 		//过滤resName的节点
664 		String[][] params = { { AuthorityResourceVO.class.getName() }, { QuerySupport.PARAM_DISTINCT, "true" }, { "_authForId", roleId },
665 				{ "_parentId", parentResId }, { "_useStatus", "1" }, { "_block", "RES_NAME not like '##%'" },
666 				{ QuerySupport.PARAM_ORDERBY, "dispOrder" } };
667 		return (List<AuthorityResourceVO>) baseDAO.queryList(params);
668 	}
669 
670 	/**
671 	 * 取得当前resID的所有直接子节点
672 	 * @param authForId 角色Id
673 	 * @param resId 模块Id
674 	 * @param systemId 系统Id
675 	 * @return
676 	 */
677 	private List<Resource> findChildResourceListForRole(String authForId, String resId, String systemId) {
678 		// 取得当前resID的所有直接子节点
679 		List<AuthorityResourceVO> tops = this.getAuthsByLevel(authForId, resId, systemId);
680 
681 		// 如果是子模块,当tops为空时,表示他还没有定制过权限,则需要继承角色的权限
682 		if ((!"0".equals(resId)) && (tops == null || tops.size() == 0) && (authForId.indexOf(".") != -1)) {
683 			// 查询出角色的权限
684 			String[] splited = authForId.split("\\.");
685 			authForId = splited[1];
686 			tops = this.getAuthsByLevel(authForId, resId, systemId);
687 		}
688 
689 		// 将List<AuthorityResourceVO> 转化为 List<Resource>
690 		List<Resource> list = new ArrayList<Resource>();
691 		for (AuthorityResourceVO authRes : tops) {
692 			authRes.setChildren(this.getChildrenRecursively(authRes, authForId));
693 			authRes.setLeaf(this.isLeaf(authRes));
694 			list.add(authRes);
695 		}
696 		return list;
697 	}
698 	
699 	/**
700 	 * 根据authForId和systemId取得模块权限
701 	 * @author wangsr
702 	 * @param authForId authForId
703 	 * @param systemId systemId
704 	 * @return 权限
705 	 */
706 	private List<AuthorityResourceVO> getResourceForRoleOfSystem(String authForId, String systemId) {
707 		List<AuthorityResourceVO> result = null;
708 		String[][] params = { { AuthorityResourceVO.class.getName() }, { QuerySupport.PARAM_DISTINCT, "true" }, { "_authForId", authForId },
709 				{ "_useStatus", "1" }, { QuerySupport.PARAM_ORDERBY, "dispOrder" }, { "_systemId", systemId } };
710 		result = (List<AuthorityResourceVO>) super.baseDAO.queryList(params);
711 		return result;
712 	}
713 	
714 	
715   /***********************************模块权限管理私有方法 start *********************************** */
716 	
717 	/**
718 	 * 设置当前模块权限
719 	 * @param authForId 角色Id
720 	 * @param res 模块
721 	 * @return 添加成功与否
722 	 */
723 	private boolean addResourceAuthority(String authForId, Resource res) {
724 		// 查看当前模块是否被授权(组角色或登录用户的情况)
725 		if (!this.isAuthorityExist(authForId, res.getResId())) {
726 			// 获得当前模块的操作
727 			List<Operation> operations = null;
728 			operations = this.operaBusi.getOperationsByResourceId(res.getResId());
729 			// 模块存在操作,添加每个操作的权限
730 			for (Operation operation : operations) {
731 				this.saveAuthority(authForId, res.getResId(), res.getSystemId(), operation.getOperationId(), "1");
732 			}
733 			//添加模块进入权限
734 			this.saveAuthority(authForId, res.getResId(), res.getSystemId(), "", "1");
735 
736 			//添加角色或用户组权限时,恢复组内角色和用户继承的已经失效的权限(在删除权限的时候,使其失效的useStatus:0)
737 			this.cascadeAuth(true, authForId, res.getResId(), null);
738 		}
739 		return true;
740 	}
741 	
742 	
743 	/**
744 	 * 在第一次设置权限的时候(del),级联授权
745 	 * @author wangsr
746 	 * @param authForId authForId
747 	 * @param resId 模块id
748 	 * @param systemId 系统id
749 	 * @return 成功与否
750 	 */
751 	private boolean cascadeSetAuthAtFirstDel(String authForId, String resId, String systemId) {
752 		
753 		String[] ids = authForId.split("\\.");
754 		String gId = ids[0];
755 		String rId = "";
756 		String uId = "";
757 		int len = ids.length;
758 		switch(len){
759 			case 1 : return true; 
760 			case 2 : rId = ids[1];uId = "";break;//groupId.roleId形式,需恢复用户定制的权限【以groupId.roleId开头】
761 			case 3 : rId = ids[1];uId = ids[2];break;//roleId形式,需恢复组角色和用户定制的权限【以roleId结尾或roleId在中间的“XX.roleId.XX”】
762 			default : throw new DefaultGboatNestedException("authForId=【" + authForId + "】格式错误,应该为:groupId.roleId.userId。");
763 		}
764 		
765 		// 注意:此时不用考虑useStatus,auths是查看该用户组是否否定制过角色权限
766 		List<Authority> auths = this.findAuthoritiesByAuthForId(authForId, systemId);
767 		// 用户组或用户还没有定制角色
768 		if (auths == null || auths.size() == 0) {
769 			this.copyAuthorityFormRoleTo(rId, gId,uId, systemId);
770 		} 
771 		
772 		return true;
773 	}
774 	
775 	
776 	/**
777 	 * 拷贝权限到组角色或者用户(userId不为空则拷贝到用户)
778 	 * @param roleId-- 角色Id
779 	 * @param groupId-- 用户组Id
780 	 * @param userId-- 用户Id
781 	 * @param systemId-- 系统Id
782 	 * @return
783 	 */
784 	private boolean copyAuthorityFormRoleTo(String roleId, String groupId, String userId, String systemId){
785 		String authForId = "";
786 		List<Authority> auths = null; 
787 		if(StringUtils.isNotEmpty(userId)){//将组角色或角色的权限默认复制给登录用户(先看组角色有没有,没有再看角色)
788 			authForId = groupId + "." + roleId;
789 			auths = this.findAuthoritiesByAuthForId(authForId, systemId);//组角色的权限
790 			if (null == auths || auths.size() == 0) {//组角色尚未定制,查看角色的权限
791 				authForId = roleId;
792 				auths = this.findAuthoritiesByAuthForId(authForId, systemId);
793 			}
794 			if (null == auths || auths.size() == 0) {
795 				return true;
796 			}
797 			authForId = groupId + "." + roleId + "." + userId;
798 			
799 		}else{//将角色的权限默认复制给用户组的指定角色
800 			auths = this.findAuthoritiesByAuthForId(roleId, systemId);
801 			if (null == auths || auths.size() == 0) {
802 				return true;
803 			}
804 			authForId = groupId + "." + roleId;
805 		}
806 		for (Authority authority : auths) {
807 			this.saveAuthority(authForId, authority.getResId(), systemId, authority.getOperaId(), "1");// operaId可能为空
808 		}
809 		
810 		return true;
811 	}
812 
813 	/**
814 	 * @param authForId 角色Id
815 	 * @param res 模块
816 	 * @return 添加成功与否
817 	 */
818 	private boolean addResourceAuthorityForParent(String authForId, Resource res) {
819 		//循环处理父模块
820 		Resource parent = (Resource) this.resourceBusi.get(Resource.class, res.getParentId());
821 		while(parent != null){
822 			if (!this.isAuthorityExist(authForId, parent.getResId())) {//如果父模块不存在
823 				this.saveAuthority(authForId, parent.getResId(), res.getSystemId(), "", "1");//添加模块进入权限
824 			}
825 			parent = (Resource) this.resourceBusi.get(Resource.class, parent.getParentId());
826 		}
827 		return true;
828 	}
829 
830 	/**
831 	 * @param authForId 角色Id
832 	 * @param res 模块
833 	 * @return 添加成功与否
834 	 */
835 	private boolean addResourceAuthorityForChild(String authForId, Resource res) {
836 		List<Resource> children = this.resourceBusi.getChildrenByParentId(res.getResId());
837 		for (Resource child : children) {
838 			addResourceAuthority(authForId, child);
839 			addResourceAuthorityForChild(authForId, child);
840 		}
841 		return true;
842 	}
843 	
844 	/**
845 	 * 删除所有的还在节点权限
846 	 * @param authForId
847 	 * @param resId
848 	 * @return
849 	 */
850 	private boolean deleteResourceAuthorityOfChild(String authForId, String resId) {
851 		List<Resource> children = this.resourceBusi.getChildrenByParentId(resId);
852 		for (Resource child : children) {
853 			this.deleteResourceAuthority(authForId, child.getResId());// 删除子节点
854 			// 递归调用自己,删除自己的子节点
855 			deleteResourceAuthorityOfChild(authForId, child.getResId());
856 		}
857 		return true;
858 	}
859 
860 	/**
861 	 * 删除模块的权限 同时删除该模块所有子模块的权限
862 	 * @param authForId 角色Id
863 	 * @param resId 模块Id
864 	 * @return 删除成功与否
865 	 */
866 	private boolean deleteResourceAuthority(String authForId, String resId) {
867 		String hql = "delete from Authority where resId=:resId and authForId=:authForId";
868 		Map<String, Object> params = new HashMap<String, Object>();
869 		params.put("resId", resId);
870 		params.put("authForId", authForId);
871 		super.baseDAO.deleteByQuery(hql, params);
872 		//如果删除的是角色的权限,则将用户组中定制的该角色相应的权限设置为无效
873 		this.cascadeAuth(false, authForId, resId, null);
874 		return true;
875 	}
876 	
877 	/*****************************模块权限管理私有方法 end ***************************** */
878 	
879 	
880 	/*****************************公用权限管理私有方法 start ***************************** */
881 	
882 	/**
883 	 * 级联设置权限
884 	 * @author wangsr
885 	 * @param authForId authForId
886 	 * @param authStatus true 设置权限为可用,false设置权限为不可用
887 	 * @param operId 为空时级联恢复模块的权限, 不为空时级联恢复某个操作
888 	 * @param resId res
889 	 * @return 成功与否
890 	 */
891 	private boolean cascadeAuth(boolean authStatus, String authForId, String resId,String operaId) {
892 		String[] ids = authForId.split("\\.");
893 		int len = ids.length;
894 		String authForIdLike = "";
895 		switch(len){
896 			case 3 : return true; 
897 			case 2 : authForIdLike = authForId + ".%";break;//groupId.roleId形式,需恢复用户定制的权限【以groupId.roleId开头】
898 			case 1 : authForIdLike = "%." + authForId + "%";break;//roleId形式,需恢复组角色和用户定制的权限【以roleId结尾或roleId在中间的“XX.roleId.XX”】
899 			default : throw new DefaultGboatNestedException("authForId=【" + authForId + "】格式错误,应该为:groupId.roleId.userId。");
900 		}
901 		this.setAuthorityStatus(authStatus, authForIdLike, resId, operaId);
902 		return true;
903 	}
904 	
905 	
906 	/**
907 	 * 设置权限记录的状态
908 	 * @param useStatus false无效,true有效
909 	 * @param authForIdLike authForId的匹配形式
910 	 * @param resId  模块Id
911 	 * @return 查询集合
912 	 */
913 	private void setAuthorityStatus(boolean authStatus,String authForIdLike,String resId,String operaId){
914 		String useStatusFrom = "1";
915 		String useStatusTo = "0";
916 		if(authStatus){
917 			useStatusFrom = "0";
918 			useStatusTo = "1";
919 		} 
920 		
921 		String hql = "update Authority set useStatus=:useStatusTo where authForId like:authForIdLike and resId=:resId and useStatus=:useStatusFrom";
922 		Map<String, Object> params = new HashMap<String, Object>();
923 		params.put("authForIdLike", authForIdLike);
924 		params.put("resId", resId);
925 		params.put("useStatusFrom", useStatusFrom);
926 		params.put("useStatusTo", useStatusTo);
927 		
928 		if(StringUtils.isNotEmpty(operaId)){//如果operaId不为空则设置操作权限
929 			hql += " and operaId=:operaId"; 
930 			params.put("operaId", operaId);
931 		}
932 		this.baseDAO.updateByQuery(hql, params);
933 	}
934 	
935 	/**
936 	 * 判断角色是否被授予这个模块的权限
937 	 * @param authForId 角色Id
938 	 * @param resId 模块Id
939 	 * @return 是否授权
940 	 */
941 	private boolean isAuthorityExist(String authForId, String resId) {
942 		String hql = "select count(*) from Authority where authForId=:authForId and resId=:resId";
943 		Map<String, Object> params = new HashMap<String, Object>();
944 		params.put("authForId", authForId);
945 		params.put("resId", resId);
946 		params.put("useStatus", "1");
947 		List<?> result = super.baseDAO.queryListByHql(hql, params);
948 		Long sum = (Long) result.get(0);
949 		return sum.longValue() > 0;
950 	}
951 	
952 	/**
953 	 * 保存权限记录
954 	 * @param authForId 
955 	 * @param resId
956 	 * @param systemId
957 	 * @param operaId
958 	 * @param useStatus
959 	 * @return true 插入了记录  false未插入记录
960 	 */
961 	private boolean saveAuthority(String authForId,String resId,String systemId,String operaId,String useStatus){
962 		if(StringUtils.isNotEmpty(authForId) && StringUtils.isNotEmpty(resId) &&
963 				StringUtils.isNotEmpty(systemId)  && StringUtils.isNotEmpty(useStatus) ){
964 			Authority auth = new Authority();
965 			auth.setOperaId(operaId);
966 			auth.setAuthForId(authForId);
967 			auth.setResId(resId);
968 			auth.setUseStatus(useStatus);
969 			auth.setSystemId(systemId);
970 			this.save(auth);
971 			return true;
972 		}
973 		return false;
974 	}
975 	
976 	private boolean deleteOpertionAuthorityBy(String authForId,String resId,String operaId){
977 		String hql = "delete from Authority where operaId=:operaId and authForId=:authForId and resId=:resId";
978 		Map<String, Object> params = new HashMap<String, Object>();
979 		params.put("authForId", authForId);
980 		params.put("resId", resId);
981 		params.put("operaId", operaId);
982 		baseDAO.deleteByQuery(hql, params);
983 		return true;
984 	}
985 	
986 	/*****************************公用权限管理私有方法 end ***************************** */
987 }