Skip to content

Commit

Permalink
change Role**Service to interface impl
Browse files Browse the repository at this point in the history
  • Loading branch information
timothynode committed Apr 28, 2017
1 parent bc0e484 commit 701a384
Show file tree
Hide file tree
Showing 9 changed files with 396 additions and 314 deletions.
Original file line number Diff line number Diff line change
@@ -1,120 +1,9 @@
package com.ctrip.framework.apollo.portal.service;

import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import com.ctrip.framework.apollo.common.entity.App;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.portal.constant.PermissionType;
import com.ctrip.framework.apollo.portal.constant.RoleType;
import com.ctrip.framework.apollo.portal.entity.po.Permission;
import com.ctrip.framework.apollo.portal.entity.po.Role;
import com.ctrip.framework.apollo.portal.spi.UserInfoHolder;
import com.ctrip.framework.apollo.portal.util.RoleUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

@Service
public class RoleInitializationService {

@Autowired
private UserInfoHolder userInfoHolder;
@Autowired
private RolePermissionService rolePermissionService;

@Transactional
public void initAppRoles(App app) {
String appId = app.getAppId();

String appMasterRoleName = RoleUtils.buildAppMasterRoleName(appId);

//has created before
if (rolePermissionService.findRoleByRoleName(appMasterRoleName) != null) {
return;
}
String operator = userInfoHolder.getUser().getUserId();
//create app permissions
createAppMasterRole(appId);

//assign master role to user
rolePermissionService
.assignRoleToUsers(RoleUtils.buildAppMasterRoleName(appId), Sets.newHashSet(app.getOwnerName()),
operator);

initNamespaceRoles(appId, ConfigConsts.NAMESPACE_APPLICATION);

//assign modify、release namespace role to user
rolePermissionService.assignRoleToUsers(RoleUtils.buildNamespaceRoleName(appId, ConfigConsts.NAMESPACE_APPLICATION, RoleType.MODIFY_NAMESPACE),
Sets.newHashSet(operator), operator);
rolePermissionService.assignRoleToUsers(RoleUtils.buildNamespaceRoleName(appId, ConfigConsts.NAMESPACE_APPLICATION, RoleType.RELEASE_NAMESPACE),
Sets.newHashSet(operator), operator);

}

@Transactional
public void initNamespaceRoles(String appId, String namespaceName) {

String modifyNamespaceRoleName = RoleUtils.buildModifyNamespaceRoleName(appId, namespaceName);
if (rolePermissionService.findRoleByRoleName(modifyNamespaceRoleName) == null) {
createDefaultNamespaceRole(appId, namespaceName, PermissionType.MODIFY_NAMESPACE,
RoleUtils.buildModifyNamespaceRoleName(appId, namespaceName));
}

String releaseNamespaceRoleName = RoleUtils.buildReleaseNamespaceRoleName(appId, namespaceName);
if (rolePermissionService.findRoleByRoleName(releaseNamespaceRoleName) == null) {
createDefaultNamespaceRole(appId, namespaceName, PermissionType.RELEASE_NAMESPACE,
RoleUtils.buildReleaseNamespaceRoleName(appId, namespaceName));
}
}

private void createAppMasterRole(String appId) {
Set<Permission> appPermissions =
FluentIterable.from(Lists.newArrayList(
PermissionType.CREATE_CLUSTER, PermissionType.CREATE_NAMESPACE, PermissionType.ASSIGN_ROLE))
.transform(permissionType -> createPermission(appId, permissionType)).toSet();
Set<Permission> createdAppPermissions = rolePermissionService.createPermissions(appPermissions);
Set<Long>
appPermissionIds =
FluentIterable.from(createdAppPermissions).transform(permission -> permission.getId()).toSet();

//create app master role
Role appMasterRole = createRole(RoleUtils.buildAppMasterRoleName(appId));

rolePermissionService.createRoleWithPermissions(appMasterRole, appPermissionIds);
}

private Permission createPermission(String targetId, String permissionType) {
Permission permission = new Permission();
permission.setPermissionType(permissionType);
permission.setTargetId(targetId);
String userId = userInfoHolder.getUser().getUserId();
permission.setDataChangeCreatedBy(userId);
permission.setDataChangeLastModifiedBy(userId);
return permission;
}

private Role createRole(String roleName) {
Role role = new Role();
role.setRoleName(roleName);
String operator = userInfoHolder.getUser().getUserId();
role.setDataChangeCreatedBy(operator);
role.setDataChangeLastModifiedBy(operator);
return role;
}

private void createDefaultNamespaceRole(String appId, String namespaceName, String permissionType, String roleName) {

Permission permission =
createPermission(RoleUtils.buildNamespaceTargetId(appId, namespaceName), permissionType);
Permission createdPermission = rolePermissionService.createPermission(permission);
public interface RoleInitializationService {
public void initAppRoles(App app);

Role role = createRole(roleName);
rolePermissionService
.createRoleWithPermissions(role, Sets.newHashSet(createdPermission.getId()));
}
public void initNamespaceRoles(String appId, String namespaceName);
}
Original file line number Diff line number Diff line change
@@ -1,231 +1,59 @@
package com.ctrip.framework.apollo.portal.service;

import com.google.common.base.Preconditions;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;

import com.ctrip.framework.apollo.portal.component.config.PortalConfig;
import com.ctrip.framework.apollo.portal.entity.bo.UserInfo;
import com.ctrip.framework.apollo.portal.entity.po.Permission;
import com.ctrip.framework.apollo.portal.entity.po.Role;
import com.ctrip.framework.apollo.portal.entity.po.RolePermission;
import com.ctrip.framework.apollo.portal.entity.bo.UserInfo;
import com.ctrip.framework.apollo.portal.entity.po.UserRole;
import com.ctrip.framework.apollo.portal.repository.PermissionRepository;
import com.ctrip.framework.apollo.portal.repository.RolePermissionRepository;
import com.ctrip.framework.apollo.portal.repository.RoleRepository;
import com.ctrip.framework.apollo.portal.repository.UserRoleRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
* @author Jason Song([email protected])
*/
@Service
public class RolePermissionService {

@Autowired
private RoleRepository roleRepository;
@Autowired
private RolePermissionRepository rolePermissionRepository;
@Autowired
private UserRoleRepository userRoleRepository;
@Autowired
private PermissionRepository permissionRepository;
@Autowired
private PortalConfig portalConfig;

public interface RolePermissionService {

/**
* Create role with permissions, note that role name should be unique
*/
@Transactional
public Role createRoleWithPermissions(Role role, Set<Long> permissionIds) {
Role current = findRoleByRoleName(role.getRoleName());
Preconditions.checkState(current == null, "Role %s already exists!", role.getRoleName());

Role createdRole = roleRepository.save(role);

if (!CollectionUtils.isEmpty(permissionIds)) {
Iterable<RolePermission> rolePermissions = FluentIterable.from(permissionIds).transform(
permissionId -> {
RolePermission rolePermission = new RolePermission();
rolePermission.setRoleId(createdRole.getId());
rolePermission.setPermissionId(permissionId);
rolePermission.setDataChangeCreatedBy(createdRole.getDataChangeCreatedBy());
rolePermission.setDataChangeLastModifiedBy(createdRole.getDataChangeLastModifiedBy());
return rolePermission;
});
rolePermissionRepository.save(rolePermissions);
}

return createdRole;
}
public Role createRoleWithPermissions(Role role, Set<Long> permissionIds);

/**
* Assign role to users
*
* @return the users assigned roles
*/
@Transactional
public Set<String> assignRoleToUsers(String roleName, Set<String> userIds,
String operatorUserId) {
Role role = findRoleByRoleName(roleName);
Preconditions.checkState(role != null, "Role %s doesn't exist!", roleName);

List<UserRole> existedUserRoles =
userRoleRepository.findByUserIdInAndRoleId(userIds, role.getId());
Set<String> existedUserIds =
FluentIterable.from(existedUserRoles).transform(userRole -> userRole.getUserId()).toSet();

Set<String> toAssignUserIds = Sets.difference(userIds, existedUserIds);

Iterable<UserRole> toCreate = FluentIterable.from(toAssignUserIds).transform(userId -> {
UserRole userRole = new UserRole();
userRole.setRoleId(role.getId());
userRole.setUserId(userId);
userRole.setDataChangeCreatedBy(operatorUserId);
userRole.setDataChangeLastModifiedBy(operatorUserId);
return userRole;
});

userRoleRepository.save(toCreate);
return toAssignUserIds;
}
String operatorUserId);

/**
* Remove role from users
*/
@Transactional
public void removeRoleFromUsers(String roleName, Set<String> userIds, String operatorUserId) {
Role role = findRoleByRoleName(roleName);
Preconditions.checkState(role != null, "Role %s doesn't exist!", roleName);

List<UserRole> existedUserRoles =
userRoleRepository.findByUserIdInAndRoleId(userIds, role.getId());

for (UserRole userRole : existedUserRoles) {
userRole.setDeleted(true);
userRole.setDataChangeLastModifiedTime(new Date());
userRole.setDataChangeLastModifiedBy(operatorUserId);
}

userRoleRepository.save(existedUserRoles);
}
public void removeRoleFromUsers(String roleName, Set<String> userIds, String operatorUserId);

/**
* Query users with role
*/
public Set<UserInfo> queryUsersWithRole(String roleName) {
Role role = findRoleByRoleName(roleName);

if (role == null) {
return Collections.emptySet();
}

List<UserRole> userRoles = userRoleRepository.findByRoleId(role.getId());

Set<UserInfo> users = FluentIterable.from(userRoles).transform(userRole -> {
UserInfo userInfo = new UserInfo();
userInfo.setUserId(userRole.getUserId());
return userInfo;
}).toSet();

return users;
}
public Set<UserInfo> queryUsersWithRole(String roleName);

/**
* Find role by role name, note that roleName should be unique
*/
public Role findRoleByRoleName(String roleName) {
return roleRepository.findTopByRoleName(roleName);
}
public Role findRoleByRoleName(String roleName);

/**
* Check whether user has the permission
*/
public boolean userHasPermission(String userId, String permissionType, String targetId) {
Permission permission =
permissionRepository.findTopByPermissionTypeAndTargetId(permissionType, targetId);
if (permission == null) {
return false;
}

if (isSuperAdmin(userId)) {
return true;
}
public boolean userHasPermission(String userId, String permissionType, String targetId);

List<UserRole> userRoles = userRoleRepository.findByUserId(userId);
if (CollectionUtils.isEmpty(userRoles)) {
return false;
}

Set<Long> roleIds =
FluentIterable.from(userRoles).transform(userRole -> userRole.getRoleId()).toSet();
List<RolePermission> rolePermissions = rolePermissionRepository.findByRoleIdIn(roleIds);
if (CollectionUtils.isEmpty(rolePermissions)) {
return false;
}

for (RolePermission rolePermission : rolePermissions) {
if (rolePermission.getPermissionId() == permission.getId()) {
return true;
}
}

return false;
}

public boolean isSuperAdmin(String userId) {
return portalConfig.superAdmins().contains(userId);
}
public boolean isSuperAdmin(String userId);

/**
* Create permission, note that permissionType + targetId should be unique
*/
@Transactional
public Permission createPermission(Permission permission) {
String permissionType = permission.getPermissionType();
String targetId = permission.getTargetId();
Permission current =
permissionRepository.findTopByPermissionTypeAndTargetId(permissionType, targetId);
Preconditions.checkState(current == null,
"Permission with permissionType %s targetId %s already exists!", permissionType, targetId);

return permissionRepository.save(permission);
}
public Permission createPermission(Permission permission);

/**
* Create permissions, note that permissionType + targetId should be unique
*/
@Transactional
public Set<Permission> createPermissions(Set<Permission> permissions) {
Multimap<String, String> targetIdPermissionTypes = HashMultimap.create();
for (Permission permission : permissions) {
targetIdPermissionTypes.put(permission.getTargetId(), permission.getPermissionType());
}

for (String targetId : targetIdPermissionTypes.keySet()) {
Collection<String> permissionTypes = targetIdPermissionTypes.get(targetId);
List<Permission> current =
permissionRepository.findByPermissionTypeInAndTargetId(permissionTypes, targetId);
Preconditions.checkState(CollectionUtils.isEmpty(current),
"Permission with permissionType %s targetId %s already exists!", permissionTypes,
targetId);
}

Iterable<Permission> results = permissionRepository.save(permissions);
return FluentIterable.from(results).toSet();
}
public Set<Permission> createPermissions(Set<Permission> permissions);

}
Loading

0 comments on commit 701a384

Please sign in to comment.