Commit c5115833 by 张乐 Committed by GitHub

Merge pull request #612 from lepdou/openapi-createnamespace

add create namespace open api
parents aeb9230b 8850633b
......@@ -18,11 +18,11 @@ public enum ConfigFileFormat {
return value;
}
public static ConfigFileFormat fromString(String value){
if (StringUtils.isEmpty(value)){
public static ConfigFileFormat fromString(String value) {
if (StringUtils.isEmpty(value)) {
throw new IllegalArgumentException("value can not be empty");
}
switch (value){
switch (value) {
case "properties":
return Properties;
case "xml":
......@@ -36,4 +36,13 @@ public enum ConfigFileFormat {
}
throw new IllegalArgumentException(value + " can not map enum");
}
public static boolean isValidFormat(String value) {
try {
fromString(value);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
}
......@@ -18,8 +18,13 @@ public class ConsumerPermissionValidator {
@Autowired
private ConsumerAuthUtil consumerAuthUtil;
public boolean hasModifyNamespacePermission(HttpServletRequest request, String appId, String
namespaceName) {
if (hasCreateNamespacePermission(request, appId)) {
return true;
}
return permissionService.consumerHasPermission(consumerAuthUtil.retrieveConsumerId(request),
PermissionType.MODIFY_NAMESPACE,
RoleUtils.buildNamespaceTargetId(appId, namespaceName));
......@@ -28,10 +33,19 @@ public class ConsumerPermissionValidator {
public boolean hasReleaseNamespacePermission(HttpServletRequest request, String appId, String
namespaceName) {
if (hasCreateNamespacePermission(request, appId)) {
return true;
}
return permissionService.consumerHasPermission(consumerAuthUtil.retrieveConsumerId(request),
PermissionType.RELEASE_NAMESPACE,
RoleUtils.buildNamespaceTargetId(appId, namespaceName));
}
public boolean hasCreateNamespacePermission(HttpServletRequest request, String appId) {
return permissionService.consumerHasPermission(consumerAuthUtil.retrieveConsumerId(request),
PermissionType.CREATE_NAMESPACE,
appId);
}
}
package com.ctrip.framework.apollo.openapi.dto;
import com.ctrip.framework.apollo.common.dto.BaseDTO;
public class OpenAppNamespaceDTO extends BaseDTO {
private String name;
private String appId;
private String format;
private boolean isPublic;
private String comment;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public boolean isPublic() {
return isPublic;
}
public void setPublic(boolean aPublic) {
isPublic = aPublic;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
......@@ -132,8 +132,9 @@ public class ConsumerService {
long namespaceReleaseRoleId = namespaceReleaseRole.getId();
ConsumerRole managedModifyRole = consumerRoleRepository.findByConsumerIdAndRoleId(consumerId, namespaceModifyRoleId);
if (managedModifyRole != null) {
throw new BadRequestException("Namespace's role has assigned to consumer.");
ConsumerRole managedReleaseRole = consumerRoleRepository.findByConsumerIdAndRoleId(consumerId, namespaceReleaseRoleId);
if (managedModifyRole != null && managedReleaseRole != null) {
return Arrays.asList(managedModifyRole, managedReleaseRole);
}
String operator = userInfoHolder.getUser().getUserId();
......@@ -148,6 +149,29 @@ public class ConsumerService {
}
@Transactional
public ConsumerRole assignAppRoleToConsumer(String token, String appId) {
Long consumerId = getConsumerIdByToken(token);
if (consumerId == null) {
throw new BadRequestException("Token is Illegal");
}
Role masterRole = rolePermissionService.findRoleByRoleName(RoleUtils.buildAppMasterRoleName(appId));
if (masterRole == null) {
throw new BadRequestException("App's role does not exist. Please check whether app has created.");
}
long roleId = masterRole.getId();
ConsumerRole managedModifyRole = consumerRoleRepository.findByConsumerIdAndRoleId(consumerId, roleId);
if (managedModifyRole != null) {
return managedModifyRole;
}
String operator = userInfoHolder.getUser().getUserId();
ConsumerRole consumerRole = createConsumerRole(consumerId, roleId, operator);
return consumerRoleRepository.save(consumerRole);
}
@Transactional
public void createConsumerAudits(Iterable<ConsumerAudit> consumerAudits) {
consumerAuditRepository.save(consumerAudits);
}
......
......@@ -4,10 +4,13 @@ import com.google.common.base.Preconditions;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.ctrip.framework.apollo.common.dto.AppNamespaceDTO;
import com.ctrip.framework.apollo.common.dto.ItemDTO;
import com.ctrip.framework.apollo.common.dto.NamespaceLockDTO;
import com.ctrip.framework.apollo.common.dto.ReleaseDTO;
import com.ctrip.framework.apollo.common.entity.AppNamespace;
import com.ctrip.framework.apollo.common.utils.BeanUtils;
import com.ctrip.framework.apollo.openapi.dto.OpenAppNamespaceDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenItemDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenNamespaceDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenNamespaceLockDTO;
......@@ -40,6 +43,15 @@ public class OpenApiBeanUtils {
return BeanUtils.transfrom(ItemDTO.class, openItemDTO);
}
public static OpenAppNamespaceDTO transformToOpenAppNamespaceDTO(AppNamespace appNamespace) {
Preconditions.checkArgument(appNamespace != null);
return BeanUtils.transfrom(OpenAppNamespaceDTO.class, appNamespace);
}
public static AppNamespace transformToAppNamespace(OpenAppNamespaceDTO openAppNamespaceDTO) {
Preconditions.checkArgument(openAppNamespaceDTO != null);
return BeanUtils.transfrom(AppNamespace.class, openAppNamespaceDTO);
}
public static OpenReleaseDTO transformFromReleaseDTO(ReleaseDTO release) {
Preconditions.checkArgument(release != null);
......
......@@ -3,32 +3,88 @@ package com.ctrip.framework.apollo.openapi.v1.controller;
import com.ctrip.framework.apollo.common.dto.NamespaceDTO;
import com.ctrip.framework.apollo.common.dto.NamespaceLockDTO;
import com.ctrip.framework.apollo.common.entity.AppNamespace;
import com.ctrip.framework.apollo.common.exception.BadRequestException;
import com.ctrip.framework.apollo.common.utils.InputValidator;
import com.ctrip.framework.apollo.common.utils.RequestPrecondition;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.core.enums.Env;
import com.ctrip.framework.apollo.openapi.dto.OpenAppNamespaceDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenNamespaceDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenNamespaceLockDTO;
import com.ctrip.framework.apollo.openapi.util.OpenApiBeanUtils;
import com.ctrip.framework.apollo.portal.entity.bo.NamespaceBO;
import com.ctrip.framework.apollo.portal.listener.AppNamespaceCreationEvent;
import com.ctrip.framework.apollo.portal.service.AppNamespaceService;
import com.ctrip.framework.apollo.portal.service.NamespaceLockService;
import com.ctrip.framework.apollo.portal.service.NamespaceService;
import com.ctrip.framework.apollo.portal.spi.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
@RestController("openapiNamespaceController")
@RequestMapping("/openapi/v1/envs/{env}")
public class NamespaceController {
@Autowired
private NamespaceLockService namespaceLockService;
@Autowired
private NamespaceService namespaceService;
@Autowired
private AppNamespaceService appNamespaceService;
@Autowired
private ApplicationEventPublisher publisher;
@Autowired
private UserService userService;
@PreAuthorize(value = "@consumerPermissionValidator.hasCreateNamespacePermission(#request, #appId)")
@RequestMapping(value = "/openapi/v1/apps/{appId}/appnamespaces", method = RequestMethod.POST)
public OpenAppNamespaceDTO createNamespace(@PathVariable String appId, @RequestBody OpenAppNamespaceDTO appNamespaceDTO,
HttpServletRequest request) {
if (!Objects.equals(appId, appNamespaceDTO.getAppId())) {
throw new BadRequestException(String.format("AppId not equal. AppId in path = %s, AppId in payload = %s", appId,
appNamespaceDTO.getAppId()));
}
RequestPrecondition.checkArgumentsNotEmpty(appNamespaceDTO.getAppId(), appNamespaceDTO.getName(),
appNamespaceDTO.getFormat(), appNamespaceDTO.getDataChangeCreatedBy());
if (!InputValidator.isValidAppNamespace(appNamespaceDTO.getName())) {
throw new BadRequestException(String.format("Namespace格式错误: %s",
InputValidator.INVALID_CLUSTER_NAMESPACE_MESSAGE + " & "
+ InputValidator.INVALID_NAMESPACE_NAMESPACE_MESSAGE));
}
if (!ConfigFileFormat.isValidFormat(appNamespaceDTO.getFormat())) {
throw new BadRequestException(String.format("Invalid namespace format. format = %s", appNamespaceDTO.getFormat()));
}
String operator = appNamespaceDTO.getDataChangeCreatedBy();
if (userService.findByUserId(operator) == null) {
throw new BadRequestException(String.format("Illegal user. user = %s", operator));
}
AppNamespace appNamespace = OpenApiBeanUtils.transformToAppNamespace(appNamespaceDTO);
AppNamespace createdAppNamespace = appNamespaceService.createAppNamespaceInLocal(appNamespace);
publisher.publishEvent(new AppNamespaceCreationEvent(createdAppNamespace));
return OpenApiBeanUtils.transformToOpenAppNamespaceDTO(createdAppNamespace);
}
@RequestMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces", method = RequestMethod.GET)
@RequestMapping(value = "/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces", method = RequestMethod.GET)
public List<OpenNamespaceDTO> findNamespaces(@PathVariable String appId, @PathVariable String env,
@PathVariable String clusterName) {
......@@ -37,7 +93,7 @@ public class NamespaceController {
.fromString(env), clusterName));
}
@RequestMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName:.+}", method = RequestMethod.GET)
@RequestMapping(value = "/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName:.+}", method = RequestMethod.GET)
public OpenNamespaceDTO loadNamespace(@PathVariable String appId, @PathVariable String env,
@PathVariable String clusterName, @PathVariable String
namespaceName) {
......@@ -49,7 +105,7 @@ public class NamespaceController {
return OpenApiBeanUtils.transformFromNamespaceBO(namespaceBO);
}
@RequestMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/lock", method = RequestMethod.GET)
@RequestMapping(value = "/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/lock", method = RequestMethod.GET)
public OpenNamespaceLockDTO getNamespaceLock(@PathVariable String appId, @PathVariable String env,
@PathVariable String clusterName, @PathVariable
String namespaceName) {
......
......@@ -36,15 +36,15 @@ public class ReleaseController {
@PreAuthorize(value = "@consumerPermissionValidator.hasReleaseNamespacePermission(#request, #appId, #namespaceName)")
@RequestMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/releases", method = RequestMethod.POST)
public OpenReleaseDTO createRelease(@PathVariable String appId, @PathVariable String env,
@PathVariable String clusterName, @PathVariable String
namespaceName,
@PathVariable String clusterName,
@PathVariable String namespaceName,
@RequestBody NamespaceReleaseModel model,
HttpServletRequest request) {
checkModel(model != null);
RequestPrecondition.checkArguments(!StringUtils.isContainEmpty(model.getReleasedBy(), model
.getReleaseTitle()),
"releaseTitle and releaseBy can not be empty");
"Params(releaseTitle and releasedBy) can not be empty");
if (userService.findByUserId(model.getReleasedBy()) == null) {
throw new BadRequestException("user(releaseBy) not exists");
......
......@@ -20,9 +20,11 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Objects;
/**
* @author Jason Song(song_s@ctrip.com)
......@@ -65,17 +67,27 @@ public class ConsumerController {
@PreAuthorize(value = "@permissionValidator.isSuperAdmin()")
@RequestMapping(value = "/consumers/{token}/assign-role", method = RequestMethod.POST)
public List<ConsumerRole> assignRoleToConsumer(@PathVariable String token, @RequestBody NamespaceDTO namespace) {
public List<ConsumerRole> assignNamespaceRoleToConsumer(@PathVariable String token,
@RequestParam String type,
@RequestBody NamespaceDTO namespace) {
String appId = namespace.getAppId();
String namespaceName = namespace.getNamespaceName();
if (StringUtils.isContainEmpty(appId, namespaceName)) {
throw new BadRequestException("Params(AppId、NamespaceName) can not be empty.");
if (StringUtils.isEmpty(appId)) {
throw new BadRequestException("Params(AppId) can not be empty.");
}
return consumerService.assignNamespaceRoleToConsumer(token, appId, namespaceName);
if (Objects.equals("AppRole", type)) {
return Collections.singletonList(consumerService.assignAppRoleToConsumer(token, appId));
} else {
if (StringUtils.isEmpty(namespaceName)) {
throw new BadRequestException("Params(NamespaceName) can not be empty.");
}
return consumerService.assignNamespaceRoleToConsumer(token, appId, namespaceName);
}
}
}
......@@ -3,21 +3,17 @@ package com.ctrip.framework.apollo.portal.controller;
import com.google.common.collect.Sets;
import com.ctrip.framework.apollo.common.dto.NamespaceDTO;
import com.ctrip.framework.apollo.common.entity.App;
import com.ctrip.framework.apollo.common.entity.AppNamespace;
import com.ctrip.framework.apollo.common.exception.BadRequestException;
import com.ctrip.framework.apollo.common.utils.InputValidator;
import com.ctrip.framework.apollo.common.utils.RequestPrecondition;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.core.enums.Env;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import com.ctrip.framework.apollo.portal.component.config.PortalConfig;
import com.ctrip.framework.apollo.portal.constant.RoleType;
import com.ctrip.framework.apollo.portal.entity.model.NamespaceCreationModel;
import com.ctrip.framework.apollo.portal.entity.bo.NamespaceBO;
import com.ctrip.framework.apollo.portal.entity.model.NamespaceCreationModel;
import com.ctrip.framework.apollo.portal.listener.AppNamespaceCreationEvent;
import com.ctrip.framework.apollo.portal.service.AppNamespaceService;
import com.ctrip.framework.apollo.portal.service.AppService;
import com.ctrip.framework.apollo.portal.service.NamespaceService;
import com.ctrip.framework.apollo.portal.service.RoleInitializationService;
import com.ctrip.framework.apollo.portal.service.RolePermissionService;
......@@ -50,8 +46,6 @@ public class NamespaceController {
private static final Logger logger = LoggerFactory.getLogger(NamespaceController.class);
@Autowired
private AppService appService;
@Autowired
private ApplicationEventPublisher publisher;
@Autowired
private UserInfoHolder userInfoHolder;
......@@ -102,18 +96,18 @@ public class NamespaceController {
@RequestBody List<NamespaceCreationModel> models) {
checkModel(!CollectionUtils.isEmpty(models));
roleInitializationService.initNamespaceRoles(appId, models.get(0).getNamespace().getNamespaceName());
String namespaceName = null;
String namespaceName = models.get(0).getNamespace().getNamespaceName();
String operator = userInfoHolder.getUser().getUserId();
roleInitializationService.initNamespaceRoles(appId, namespaceName, operator);
for (NamespaceCreationModel model : models) {
NamespaceDTO namespace = model.getNamespace();
namespaceName = namespace.getNamespaceName();
RequestPrecondition
.checkArgumentsNotEmpty(model.getEnv(), namespace.getAppId(), namespace.getClusterName(),
namespace.getNamespaceName());
RequestPrecondition.checkArgumentsNotEmpty(model.getEnv(), namespace.getAppId(),
namespace.getClusterName(), namespace.getNamespaceName());
try {
// TODO: 16/6/17 某些环境创建失败,统一处理这种场景
namespaceService.createNamespace(Env.valueOf(model.getEnv()), namespace);
} catch (Exception e) {
logger.error("create namespace fail.", e);
......@@ -149,21 +143,6 @@ public class NamespaceController {
+ InputValidator.INVALID_NAMESPACE_NAMESPACE_MESSAGE));
}
//add app org id as prefix
App app = appService.load(appId);
StringBuilder appNamespaceName = new StringBuilder();
//add prefix postfix
appNamespaceName
.append(appNamespace.isPublic() ? app.getOrgId() + "." : "")
.append(appNamespace.getName())
.append(appNamespace.formatAsEnum() == ConfigFileFormat.Properties ? "" : "." + appNamespace.getFormat());
appNamespace.setName(appNamespaceName.toString());
String operator = userInfoHolder.getUser().getUserId();
if (StringUtils.isEmpty(appNamespace.getDataChangeCreatedBy())) {
appNamespace.setDataChangeCreatedBy(operator);
}
appNamespace.setDataChangeLastModifiedBy(operator);
AppNamespace createdAppNamespace = appNamespaceService.createAppNamespaceInLocal(appNamespace);
if (portalConfig.canAppAdminCreatePrivateNamespace() || createdAppNamespace.isPublic()) {
......
package com.ctrip.framework.apollo.portal.service;
import com.ctrip.framework.apollo.common.entity.App;
import com.ctrip.framework.apollo.common.entity.AppNamespace;
import com.ctrip.framework.apollo.common.exception.BadRequestException;
import com.ctrip.framework.apollo.common.exception.ServiceException;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import com.ctrip.framework.apollo.portal.repository.AppNamespaceRepository;
import com.ctrip.framework.apollo.portal.spi.UserInfoHolder;
......@@ -24,6 +26,8 @@ public class AppNamespaceService {
private AppNamespaceRepository appNamespaceRepository;
@Autowired
private RoleInitializationService roleInitializationService;
@Autowired
private AppService appService;
/**
* 公共的app ns,能被其它项目关联到的app ns
......@@ -65,6 +69,38 @@ public class AppNamespaceService {
@Transactional
public AppNamespace createAppNamespaceInLocal(AppNamespace appNamespace) {
String appId = appNamespace.getAppId();
//add app org id as prefix
App app = appService.load(appId);
if (app == null) {
throw new BadRequestException("App not exist. AppId = " + appId);
}
StringBuilder appNamespaceName = new StringBuilder();
//add prefix postfix
appNamespaceName
.append(appNamespace.isPublic() ? app.getOrgId() + "." : "")
.append(appNamespace.getName())
.append(appNamespace.formatAsEnum() == ConfigFileFormat.Properties ? "" : "." + appNamespace.getFormat());
appNamespace.setName(appNamespaceName.toString());
if (appNamespace.getComment() == null) {
appNamespace.setComment("");
}
if (!ConfigFileFormat.isValidFormat(appNamespace.getFormat())) {
throw new BadRequestException("Invalid namespace format. format must be properties、json、yaml、yml、xml");
}
String operator = appNamespace.getDataChangeCreatedBy();
if (StringUtils.isEmpty(operator)) {
operator = userInfoHolder.getUser().getUserId();
appNamespace.setDataChangeCreatedBy(operator);
}
appNamespace.setDataChangeLastModifiedBy(operator);
// unique check
if (appNamespace.isPublic() && findPublicAppNamespace(appNamespace.getName()) != null) {
throw new BadRequestException(appNamespace.getName() + "已存在");
......@@ -77,7 +113,7 @@ public class AppNamespaceService {
AppNamespace createdAppNamespace = appNamespaceRepository.save(appNamespace);
roleInitializationService.initNamespaceRoles(appNamespace.getAppId(), appNamespace.getName());
roleInitializationService.initNamespaceRoles(appNamespace.getAppId(), appNamespace.getName(), operator);
return createdAppNamespace;
}
......
......@@ -61,11 +61,7 @@ public class AppService {
}
public App load(String appId) {
App app = appRepository.findByAppId(appId);
if (app == null) {
throw new BadRequestException(String.format("app %s cant found.", appId));
}
return app;
return appRepository.findByAppId(appId);
}
public AppDTO load(Env env, String appId) {
......
......@@ -3,7 +3,9 @@ package com.ctrip.framework.apollo.portal.service;
import com.ctrip.framework.apollo.common.entity.App;
public interface RoleInitializationService {
public void initAppRoles(App app);
public void initNamespaceRoles(String appId, String namespaceName);
public void initNamespaceRoles(String appId, String namespaceName, String operator);
}
package com.ctrip.framework.apollo.portal.spi.defaultimpl;
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;
......@@ -10,9 +14,7 @@ import com.ctrip.framework.apollo.portal.service.RoleInitializationService;
import com.ctrip.framework.apollo.portal.service.RolePermissionService;
import com.ctrip.framework.apollo.portal.spi.UserInfoHolder;
import com.ctrip.framework.apollo.portal.util.RoleUtils;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
......@@ -22,99 +24,101 @@ import java.util.Set;
* Created by timothy on 2017/4/26.
*/
public class DefaultRoleInitializationService implements 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));
}
@Autowired
private UserInfoHolder userInfoHolder;
@Autowired
private RolePermissionService rolePermissionService;
String releaseNamespaceRoleName = RoleUtils.buildReleaseNamespaceRoleName(appId, namespaceName);
if (rolePermissionService.findRoleByRoleName(releaseNamespaceRoleName) == null) {
createDefaultNamespaceRole(appId, namespaceName, PermissionType.RELEASE_NAMESPACE,
RoleUtils.buildReleaseNamespaceRoleName(appId, namespaceName));
}
}
@Transactional
public void initAppRoles(App app) {
String appId = app.getAppId();
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();
String appMasterRoleName = RoleUtils.buildAppMasterRoleName(appId);
//create app master role
Role appMasterRole = createRole(RoleUtils.buildAppMasterRoleName(appId));
rolePermissionService.createRoleWithPermissions(appMasterRole, appPermissionIds);
//has created before
if (rolePermissionService.findRoleByRoleName(appMasterRoleName) != null) {
return;
}
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;
String operator = app.getDataChangeCreatedBy();
//create app permissions
createAppMasterRole(appId, operator);
//assign master role to user
rolePermissionService
.assignRoleToUsers(RoleUtils.buildAppMasterRoleName(appId), Sets.newHashSet(app.getOwnerName()),
operator);
initNamespaceRoles(appId, ConfigConsts.NAMESPACE_APPLICATION, operator);
//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 operator) {
String modifyNamespaceRoleName = RoleUtils.buildModifyNamespaceRoleName(appId, namespaceName);
if (rolePermissionService.findRoleByRoleName(modifyNamespaceRoleName) == null) {
createNamespaceRole(appId, namespaceName, PermissionType.MODIFY_NAMESPACE,
RoleUtils.buildModifyNamespaceRoleName(appId, namespaceName), operator);
}
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);
Role role = createRole(roleName);
rolePermissionService
.createRoleWithPermissions(role, Sets.newHashSet(createdPermission.getId()));
String releaseNamespaceRoleName = RoleUtils.buildReleaseNamespaceRoleName(appId, namespaceName);
if (rolePermissionService.findRoleByRoleName(releaseNamespaceRoleName) == null) {
createNamespaceRole(appId, namespaceName, PermissionType.RELEASE_NAMESPACE,
RoleUtils.buildReleaseNamespaceRoleName(appId, namespaceName), operator);
}
}
private void createAppMasterRole(String appId, String operator) {
Set<Permission> appPermissions =
FluentIterable.from(Lists.newArrayList(
PermissionType.CREATE_CLUSTER, PermissionType.CREATE_NAMESPACE, PermissionType.ASSIGN_ROLE))
.transform(permissionType -> createPermission(appId, permissionType, operator)).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), operator);
rolePermissionService.createRoleWithPermissions(appMasterRole, appPermissionIds);
}
private Permission createPermission(String targetId, String permissionType, String operator) {
Permission permission = new Permission();
permission.setPermissionType(permissionType);
permission.setTargetId(targetId);
permission.setDataChangeCreatedBy(operator);
permission.setDataChangeLastModifiedBy(operator);
return permission;
}
private Role createRole(String roleName, String operator) {
Role role = new Role();
role.setRoleName(roleName);
role.setDataChangeCreatedBy(operator);
role.setDataChangeLastModifiedBy(operator);
return role;
}
private void createNamespaceRole(String appId, String namespaceName, String permissionType,
String roleName, String operator) {
Permission permission =
createPermission(RoleUtils.buildNamespaceTargetId(appId, namespaceName), permissionType, operator);
Permission createdPermission = rolePermissionService.createPermission(permission);
Role role = createRole(roleName, operator);
rolePermissionService
.createRoleWithPermissions(role, Sets.newHashSet(createdPermission.getId()));
}
}
......@@ -90,7 +90,7 @@
<section class="row">
<h5>赋权
<small>
(说明: 第三方应用只能管理已经赋权的Namespace)
(Namespace级别权限包括: 修改、发布Namespace。应用级别权限包括: 创建Namespace、修改或发布应用下任何Namespace)
</small>
</h5>
<hr>
......@@ -100,7 +100,7 @@
<label class="col-sm-2 control-label">
<apollorequiredfield></apollorequiredfield>
token</label>
<div class="col-sm-3">
<div class="col-sm-5">
<input type="text" class="form-control" ng-model="consumerRole.token" required>
</div>
</div>
......@@ -114,13 +114,27 @@
</div>
<div class="form-group" valdr-form-group>
<label class="col-sm-2 control-label">
<apollorequiredfield></apollorequiredfield>
被管理的Namespace</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="consumerRole.namespaceName" required>
<input type="text" class="form-control" ng-model="consumerRole.namespaceName">
<small>(非properties类型的namespace请加上类型后缀,例如apollo.xml)</small>
</div>
</div>
<div class="form-group" valdr-form-group>
<label class="col-sm-2 control-label">
授权类型
</label>
<div class="col-sm-3">
<label class="radio-inline">
<input type="radio" name="inlineRadioOptions" ng-value="'NamespaceRole'" ng-model="consumerRole.type">
Namespace
</label>
<label class="radio-inline">
<input type="radio" name="inlineRadioOptions" ng-value="'AppRole'" ng-model="consumerRole.type">
App
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-9">
<button type="submit" class="btn btn-primary"
......
......@@ -7,7 +7,9 @@ function OpenManageController($scope, toastr, AppUtil, OrganizationService, Cons
var $orgWidget = $('#organization');
$scope.consumer = {};
$scope.consumerRole = {};
$scope.consumerRole = {
type: 'NamespaceRole'
};
$scope.submitBtnDisabled = false;
$scope.userSelectWidgetId = 'toAssignMasterRoleUser';
......@@ -110,6 +112,7 @@ function OpenManageController($scope, toastr, AppUtil, OrganizationService, Cons
function assignRoleToConsumer() {
ConsumerService.assignRoleToConsumer($scope.consumerRole.token,
$scope.consumerRole.type,
$scope.consumerRole.appId,
$scope.consumerRole.namespaceName)
.then(function (consumerRoles) {
......@@ -118,4 +121,5 @@ function OpenManageController($scope, toastr, AppUtil, OrganizationService, Cons
AppUtil.showErrorMsg(response, "赋权失败");
})
}
}
......@@ -29,11 +29,17 @@ appService.service('ConsumerService', ['$resource', '$q', 'AppUtil',
appId: appId
});
},
assignRoleToConsumer: function (token, appId, namespaceName) {
return AppUtil.ajax(resource.assign_role_to_consumer, {token: token}, {
appId: appId,
namespaceName: namespaceName
})
assignRoleToConsumer: function (token, type, appId, namespaceName) {
return AppUtil.ajax(resource.assign_role_to_consumer,
{
token: token,
type: type
},
{
appId: appId,
namespaceName: namespaceName
}
)
}
}
}]);
......@@ -71,7 +71,7 @@ public class AppNamespaceServiceTest extends AbstractIntegrationTest {
public void testCreatePublicAppNamespaceExisted() {
AppNamespace appNamespace = assmbleBaseAppNamespace();
appNamespace.setPublic(true);
appNamespace.setName("FX.old");
appNamespace.setName("old");
appNamespaceService.createAppNamespaceInLocal(appNamespace);
}
......
......@@ -74,7 +74,7 @@ public class RoleInitializationServiceTest extends AbstractUnitTest {
when(rolePermissionService.findRoleByRoleName(releaseNamespaceRoleName)).
thenReturn(mockRole(releaseNamespaceRoleName));
roleInitializationService.initNamespaceRoles(APP_ID, NAMESPACE);
roleInitializationService.initNamespaceRoles(APP_ID, NAMESPACE, CURRENT_USER);
verify(rolePermissionService, times(2)).findRoleByRoleName(anyString());
verify(rolePermissionService, times(0)).createPermission(any());
......@@ -95,7 +95,7 @@ public class RoleInitializationServiceTest extends AbstractUnitTest {
when(userInfoHolder.getUser()).thenReturn(mockUser());
when(rolePermissionService.createPermission(any())).thenReturn(mockPermission());
roleInitializationService.initNamespaceRoles(APP_ID, NAMESPACE);
roleInitializationService.initNamespaceRoles(APP_ID, NAMESPACE, CURRENT_USER);
verify(rolePermissionService, times(2)).findRoleByRoleName(anyString());
verify(rolePermissionService, times(2)).createPermission(any());
......@@ -116,7 +116,7 @@ public class RoleInitializationServiceTest extends AbstractUnitTest {
when(userInfoHolder.getUser()).thenReturn(mockUser());
when(rolePermissionService.createPermission(any())).thenReturn(mockPermission());
roleInitializationService.initNamespaceRoles(APP_ID, NAMESPACE);
roleInitializationService.initNamespaceRoles(APP_ID, NAMESPACE, CURRENT_USER);
verify(rolePermissionService, times(2)).findRoleByRoleName(anyString());
verify(rolePermissionService, times(1)).createPermission(any());
......
INSERT INTO `appnamespace` (`Id`, `Name`, `AppId`, `Format`, `IsPublic`, `Comment`, `IsDeleted`, `DataChange_CreatedBy`, `DataChange_CreatedTime`, `DataChange_LastModifiedBy`, `DataChange_LastTime`)
VALUES
(139, 'FX.old', '100003173', 'properties', 1, '', 0, 'zhanglea', '2016-07-11 10:00:58', 'zhanglea', '2016-07-11 10:00:58'),
(139, 'FX.old.xml', '100003173', 'properties', 1, '', 0, 'zhanglea', '2016-07-11 10:00:58', 'zhanglea', '2016-07-11 10:00:58'),
(140, 'SCC.song0711-03', 'song0711-01', 'properties', 1, '', 0, 'song_s', '2016-07-11 10:04:09', 'song_s', '2016-07-11 10:04:09'),
(141, 'SCC.song0711-04', 'song0711-01', 'properties', 1, '', 0, 'song_s', '2016-07-11 10:06:29', 'song_s', '2016-07-11 10:06:29'),
(142, 'application', 'song0711-02', 'properties', 1, 'default app namespace', 0, 'song_s', '2016-07-11 11:18:24', 'song_s', '2016-07-11 11:18:24'),
(143, 'TFF.song0711-02', 'song0711-02', 'properties', 0, '', 0, 'song_s', '2016-07-11 11:15:11', 'song_s', '2016-07-11 11:15:11'),
(144, 'datasourcexml', '100003173', 'xml', 1, '', 0, 'apollo', '2016-07-11 12:08:29', 'apollo', '2016-07-11 12:08:29'),
(145, 'datasource.xml', '100003173', 'xml', 0, '', 0, 'apollo', '2016-07-11 12:09:30', 'apollo', '2016-07-11 12:09:30');
INSERT INTO `app` (`AppId`, `Name`, `OrgId`, `OrgName`, `OwnerName`, `OwnerEmail`, `IsDeleted`, `DataChange_CreatedBy`, `DataChange_LastModifiedBy`)
VALUES
('1000', 'apollo-portal', 'FX', '框架', 'song_s', 'song_s@ctrip.com', 0, 'song_s', 'song_s');
......@@ -5,3 +5,4 @@ delete from UserRole;
delete from AppNamespace;
DELETE FROM Favorite;
DELETE FROM ServerConfig;
DELETE FROM App;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment