Skip to content

Commit

Permalink
调整用户权限,增加manager权限
Browse files Browse the repository at this point in the history
  • Loading branch information
hengyunabc committed Aug 15, 2015
1 parent 6b90e54 commit 81ae775
Show file tree
Hide file tree
Showing 8 changed files with 137 additions and 39 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -196,8 +196,7 @@ public Object listResolvedConfig(@PathVariable int profileId) {
@RequestMapping(value = "/configs/all", method = RequestMethod.GET)
@Timed
public ResponseEntity<RestResult> list() {
// 只有admin才有查看全部Config的权限
PermissionHelper.checkAdmin();
// 这里的权限检查在shiro-web配置文件里
// 获取所有的Config,再获取它们的Profile,再获取Project,最终合到一起
List<Map<String, Object>> resultList = Lists.newLinkedList();
List<Config> allConfigs = configService.list();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ public class CrashController {
@RequestMapping(value = "/crash/token", method = RequestMethod.GET)
@Timed
public ResponseEntity<RestResult> token() {
PermissionHelper.checkAdmin();

String token = RandomStringUtils.randomAlphanumeric(16);
crashTokenCache.put(token, new Object());
return RestResult.success().withResult("token", token).build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,10 @@ public class DependencyController {
@Autowired
ProjectService projectService;

@RequestMapping(value = "/dependencies", method = RequestMethod.GET)
@RequestMapping(value = "/dependencies/all", method = RequestMethod.GET)
@Timed
public Object list() {
// 只有admin权限才可以查看所有的依赖
PermissionHelper.checkAdmin();
// 这里的权限检查在shiro-web配置文件里
List<Dependency> dependencies = dependencyService.list();
return RestResult.success().withResult("dependencies", dependencies).build();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package io.github.xdiamond.web.shiro;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;

/**
* ajax request/accept json return JSON, not ajax request will redirect to unauthorizedUrl.
*
* @author hengyunabc
*
*/
public class CustomPermissionsAuthorizationFilter extends AuthorizationFilter {

String unauthorizedJSONString =
"{\"success\":false,\"error\":{\"message\":\"unauthorized! need login\"}}";

String forbiddenJSONString =
"{\"success\":false,\"error\":{\"message\":\"forbidden! no permission.\"}}";

@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response)
throws IOException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;

Subject subject = getSubject(request, response);

if (subject.getPrincipal() == null) {
if (AjaxUtils.isAjaxRequest(httpRequest) || AjaxUtils.isAcceptJSON(httpRequest)) {
WebUtil.wrietJSONResponse(httpResponse, unauthorizedJSONString,
HttpServletResponse.SC_UNAUTHORIZED);
} else {
saveRequestAndRedirectToLogin(request, response);
}
} else {
if (AjaxUtils.isAjaxRequest(httpRequest) || AjaxUtils.isAcceptJSON(httpRequest)) {
WebUtil.wrietJSONResponse(httpResponse, forbiddenJSONString,
HttpServletResponse.SC_FORBIDDEN);
} else {
String unauthorizedUrl = getUnauthorizedUrl();
if (StringUtils.hasText(unauthorizedUrl)) {
WebUtils.issueRedirect(request, response, unauthorizedUrl);
} else {
WebUtils.toHttp(response).sendError(401);
}
}
}
return false;
}

@Override
public boolean isAccessAllowed(ServletRequest request, ServletResponse response,
Object mappedValue) throws IOException {

Subject subject = getSubject(request, response);
String[] permissionsArray = (String[]) mappedValue;

if (permissionsArray == null || permissionsArray.length == 0) {
// no roles specified, so nothing to check - allow access.
return true;
}
return subject.isPermittedAll(permissionsArray);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;

/**
* ajax request/accept json return JSON, not ajax request will redirect to unauthorizedUrl.
*
* @author hengyunabc
*
*/
public class CustomRolesAuthorizationFilter extends AuthorizationFilter {

String unauthorizedJSONString =
Expand All @@ -39,7 +45,8 @@ protected boolean onAccessDenied(ServletRequest request, ServletResponse respons
}
} else {
if (AjaxUtils.isAjaxRequest(httpRequest) || AjaxUtils.isAcceptJSON(httpRequest)) {
WebUtil.wrietJSONResponse(httpResponse, forbiddenJSONString, HttpServletResponse.SC_FORBIDDEN);
WebUtil.wrietJSONResponse(httpResponse, forbiddenJSONString,
HttpServletResponse.SC_FORBIDDEN);
} else {
String unauthorizedUrl = getUnauthorizedUrl();
if (StringUtils.hasText(unauthorizedUrl)) {
Expand Down
56 changes: 27 additions & 29 deletions xdiamond-server/src/main/resources/spring-shiro-web.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
Expand All @@ -19,8 +18,7 @@
<property name="storedCredentialsHexEncoded" value="true" />
</bean>

<bean id="allowAllCredentialsMatcher"
class="org.apache.shiro.authc.credential.AllowAllCredentialsMatcher"></bean>
<bean id="allowAllCredentialsMatcher" class="org.apache.shiro.authc.credential.AllowAllCredentialsMatcher"></bean>

<!-- 数据库有更改,权限有改变时,清除shiro authorizationCache -->
<bean id="shiroCacheCleanFilter" class="io.github.xdiamond.web.shiro.ShiroCacheCleanFilter" />
Expand All @@ -36,8 +34,7 @@
</bean>

<!-- 会话ID生成器,用于SessionDAO缓冲相关 -->
<bean id="sessionIdGenerator"
class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator" />
<bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator" />

<!-- 会话Cookie模板,用于rememberMe 功能 -->
<bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
Expand All @@ -47,24 +44,20 @@
</bean>

<!-- Shiro本身提供SessionDAO的实现用以保存企业级/分布式的缓存数据.EnterpriseCacheSessionDAO,可以在CacheManager中配置它来实现缓存机制 -->
<bean id="sessionDAO"
class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
<bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
<property name="activeSessionsCacheName" value="shiro-activeSessionCache" />
<property name="sessionIdGenerator" ref="sessionIdGenerator" />
</bean>

<!-- Shiro提供了会话验证调度器,用于定期的验证会话是否已过期,如果过期将停止会话;出 于性能考虑,一般情况下都是获取会话时来验证会话是否过期并停止会话的;但是如在web
环境中,如果用户不主动退出是不知道会话是否过期的,因此需要定期的检测会话是否过 期.下方配置是使用Quartz会话验证调度器 -->
<bean id="sessionValidationScheduler"
class="org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler">
<!-- Shiro提供了会话验证调度器,用于定期的验证会话是否已过期,如果过期将停止会话;出 于性能考虑,一般情况下都是获取会话时来验证会话是否过期并停止会话的;但是如在web 环境中,如果用户不主动退出是不知道会话是否过期的,因此需要定期的检测会话是否过 期.下方配置是使用Quartz会话验证调度器 -->
<bean id="sessionValidationScheduler" class="org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler">
<property name="sessionValidationInterval" value="1800000" />
<property name="sessionManager" ref="sessionManager" />
</bean>

<!-- 会话管理器 -->
<!-- 用于Web 环境的实现, 可以替代 ServletContainerSessionManager,自己维护着会话,直接废弃了Servlet容器的会话管理。 -->
<bean id="sessionManager"
class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<property name="globalSessionTimeout" value="1800000" />
<property name="deleteInvalidSessions" value="true" />
<property name="sessionDAO" ref="sessionDAO" />
Expand All @@ -82,19 +75,17 @@
</bean>

<!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod"
value="org.apache.shiro.SecurityUtils.setSecurityManager" />
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager" />
<property name="arguments" ref="securityManager" />
</bean>

<!-- 对于ajjax,json请求返回JSON结果,非ajax,json请求重定向到一个登陆URL -->
<bean id="customAuthenticationFilter" class="io.github.xdiamond.web.shiro.CustomAuthenticationFilter"></bean>

<!-- 自定义的role filter,对于ajjax,json请求返回JSON结果,非ajax,json请求重定向到一个登陆URL -->
<bean id="customRolesAuthorizationFilter"
class="io.github.xdiamond.web.shiro.CustomRolesAuthorizationFilter"></bean>
<bean id="customRolesAuthorizationFilter" class="io.github.xdiamond.web.shiro.CustomRolesAuthorizationFilter"></bean>
<bean id="customPermissionsAuthorizationFilter" class="io.github.xdiamond.web.shiro.CustomPermissionsAuthorizationFilter"></bean>

<!-- Shiro的Web过滤器 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
Expand All @@ -105,6 +96,7 @@
<util:map>
<entry key="authc" value-ref="customAuthenticationFilter" />
<entry key="customRoles" value-ref="customRolesAuthorizationFilter" />
<entry key="customPerms" value-ref="customPermissionsAuthorizationFilter" />
</util:map>
</property>
<property name="filterChainDefinitions">
Expand All @@ -115,17 +107,23 @@
/api/authenticate = anon
/api/session = anon

/api/ldap/** = customRoles[admin]
/api/roles = customRoles[admin]
/api/permissions = customRoles[admin]
/api/roles = customPerms[admin]
/api/permissions = customPerms[admin]

/api/metrics = customRoles[admin]
/api/threadinfo = customRoles[admin]
/api/systemproperties = customRoles[admin]
/api/logs = customRoles[admin]
/api/connections = customRoles[admin]
/api/dependencies/all = customPerms[manager]
/api/configs/all = customPerms[manager]

/druid/** = customRoles[admin]
/api/ldap/** = customPerms[manager]

/api/metrics = customPerms[manager]
/api/threadinfo = customPerms[manager]
/api/systemproperties = customPerms[manager]
/api/logs = customPerms[manager]
/api/connections = customPerms[manager]

/api/crash/token = customPerms[manager]

/druid/** = customPerms[manager]

/api/** = authc

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ angular.module('xdiamondApp')
var service = {};

service.all = function () {
return $http.get('api/dependencies').then(function (response) {
return $http.get('api/dependencies/all').then(function (response) {
console.log('dependencies:' + response.data);

if (response.data.success) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,27 @@ angular.module('xdiamondApp').controller("UserController", ['$scope', '$state',
});
}

}]);
}]);


angular.module('xdiamondApp').controller("UserUpdateController",
['$scope', '$state', '$modal', '$modalInstance', 'UserService', 'user',
function ($scope, $state, $modal, $modalInstance, UserService, user) {
$scope.user = user;

$scope.update = function () {
UserService.patch(user).then(function () {
$state.reload();
})
$modalInstance.close();
}

$scope.ok = function () {
$modalInstance.close();
};

$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};

}]);

0 comments on commit 81ae775

Please sign in to comment.