Java源码示例:org.wso2.carbon.user.mgt.UserMgtConstants
示例1
/**
* Convert csv format user information into JSON format. The input stream should be in following format
* <p>
* UserName, Password, Claims.
*
* @return : JSON representation of the input csv stream.
* @throws IOException : Throws if there is any error occurred when reading from the input stream.
*/
public String csvToJSON(InputStream sourceStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(sourceStream));
CSVReader csvReader = new CSVReader(bufferedReader, ',', '"', 1);
String[] line = csvReader.readNext();
users = new JsonArray();
if (log.isDebugEnabled()) {
log.debug("Converting csv to json.");
}
while (line != null) {
JsonPrimitive user = new JsonPrimitive(line[0]);
users.add(user);
line = csvReader.readNext();
}
content.add(UserMgtConstants.USERS, users);
return content.toString();
}
示例2
/**
* Converts xls sheet to json format.
* Currently considering the username.
*
* @param sheet : The XLS sheet that needs to be converted.
* @return : Json string which represents the sheet.
*/
public String xlsToJSON(Sheet sheet) {
int limit = sheet.getLastRowNum();
users = new JsonArray();
if (log.isDebugEnabled()) {
log.debug("Converting XLS sheet to json.");
}
for (int i = 1; i < limit + 1; i++) {
Row row = sheet.getRow(i);
Cell cell = row.getCell(0);
String name = cell.getStringCellValue();
JsonPrimitive userJson = new JsonPrimitive(name);
users.add(userJson);
}
content.add(UserMgtConstants.USERS, users);
return content.toString();
}
示例3
public static Permission[] getRoleUIPermissions(String roleName, String[] rawPermissions)
throws UserAdminException {
Permission[] permissions;
if (ArrayUtils.isEmpty(rawPermissions)) {
return new Permission[0];
}
String[] optimizedList = UserCoreUtil.optimizePermissions(rawPermissions);
permissions = new Permission[optimizedList.length];
int i = 0;
for (String path : optimizedList) {
permissions[i++] = new Permission(path, UserMgtConstants.EXECUTE_ACTION);
}
return permissions;
}
示例4
/**
* Creating Internal/user Role at Carbon Server Start-up
*/
public static void createInternalUserRole(UserStoreManager userStoreManager) throws UserManagerException {
String userRole = "Internal/user";
try {
if (!userStoreManager.isExistingRole(userRole)) {
log.info("Creating internal user role: " + userRole);
//Set permissions to the Internal/user role
List<Permission> permissions = new ArrayList<Permission>();
for (String permissionResourceId : PermissionConstants.STRATOS_PERMISSIONS) {
Permission permission = new Permission(permissionResourceId, UserMgtConstants.EXECUTE_ACTION);
permissions.add(permission);
}
String[] userList = new String[]{};
userStoreManager.addRole(userRole, userList, permissions.toArray(new Permission[permissions.size()]));
}
} catch (UserStoreException e) {
String msg = "Error while creating the role: " + userRole;
log.error(msg, e);
throw new UserManagerException(msg, e);
}
}
示例5
private void setupSelfRegistration(APIManagerConfiguration config) throws APIManagementException {
boolean enabled = Boolean.parseBoolean(config.getFirstProperty(APIConstants.SELF_SIGN_UP_ENABLED));
if (!enabled) {
return;
}
String role = config.getFirstProperty(APIConstants.SELF_SIGN_UP_ROLE);
if (role == null) {
// Required parameter missing - Throw an exception and interrupt startup
throw new APIManagementException("Required subscriber role parameter missing " + "in the self sign up configuration");
}
try {
RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
UserRealm realm = realmService.getBootstrapRealm();
UserStoreManager manager = realm.getUserStoreManager();
if (!manager.isExistingRole(role)) {
if (log.isDebugEnabled()) {
log.debug("Creating subscriber role: " + role);
}
Permission[] subscriberPermissions = new Permission[] { new Permission("/permission/admin/login", UserMgtConstants.EXECUTE_ACTION), new Permission(APIConstants.Permissions.API_SUBSCRIBE, UserMgtConstants.EXECUTE_ACTION) };
String superTenantName = ServiceReferenceHolder.getInstance().getRealmService().getBootstrapRealmConfiguration().getAdminUserName();
String[] userList = new String[] { superTenantName };
manager.addRole(role, userList, subscriberPermissions);
}
} catch (UserStoreException e) {
throw new APIManagementException("Error while creating subscriber role: " + role + " - " + "Self registration might not function properly.", e);
}
}
示例6
public void addUserList(UserStoreManager userStore) throws UserAdminException {
Workbook wb = this.createWorkbook();
Sheet sheet = wb.getSheet(wb.getSheetName(0));
userStoreDomain = config.getUserStoreDomain();
if (sheet == null || sheet.getLastRowNum() == -1) {
throw new UserAdminException("The first sheet is empty");
}
int limit = sheet.getLastRowNum();
boolean isDuplicate = false;
boolean fail = false;
for (int i = 1; i < limit + 1; i++) {
Row row = sheet.getRow(i);
Cell cell = row.getCell(0);
String userName = cell.getStringCellValue();
int index;
index = userName.indexOf(CarbonConstants.DOMAIN_SEPARATOR);
if (index > 0) {
String domainFreeName = userName.substring(index + 1);
userName = UserCoreUtil.addDomainToName(domainFreeName, userStoreDomain);
} else {
userName = UserCoreUtil.addDomainToName(userName, userStoreDomain);
}
if (StringUtils.isNotBlank(userName)) {
try {
if (!userStore.isExistingUser(userName)) {
userStore.addUser(userName, null, null, null, null, true);
successCount++;
if (log.isDebugEnabled()) {
log.debug("User import successful - Username : " + userName);
}
} else {
duplicateCount++;
duplicateUsers.add(userName);
isDuplicate = true;
log.error("User import unsuccessful - Username : " + userName + " - Error: Duplicate user");
duplicateUsers.add(userName);
}
} catch (UserStoreException e) {
fail = true;
failCount++;
log.error("User import unsuccessful - Username : " + userName + " - Error: " +
e.getMessage());
errorUsersMap.put(userName, e.getMessage());
}
}
}
String summeryLog = super.buildBulkImportSummary();
log.info(summeryLog);
JSONConverter jsonConverter = new JSONConverter();
String importedUsers = jsonConverter.xlsToJSON(sheet);
auditLog.info(String.format(UserMgtConstants.AUDIT_LOG_FORMAT, tenantUser, UserMgtConstants.OPERATION_NAME,
userStoreDomain, importedUsers, summeryLog));
if (fail || isDuplicate) {
throw new UserAdminException(String.format(UserMgtConstants.ERROR_MESSAGE, successCount, failCount,
duplicateCount));
}
}
示例7
public void addUIPermissionFromBundle(Bundle bundle) throws Exception {
BundleContext bundleContext = bundle.getBundleContext();
if (bundleContext == null) { // If the bundle got uninstalled, the bundleContext will be null
return;
}
URL url = bundleContext.getBundle().getEntry("META-INF/component.xml");
if (url == null) {
return;
}
InputStream xmlStream = url.openStream();
if (xmlStream == null) {
return;
}
if (log.isDebugEnabled()) {
log.debug("Adding permissions in bundle" +
bundle.getSymbolicName());
}
Component component = ComponentConfigFactory.build(xmlStream);
ManagementPermission[] uiPermissions = null;
if (component != null) {
uiPermissions = (ManagementPermission[]) component
.getComponentConfig(ManagementPermissionsBuilder.LOCALNAME_MGT_PERMISSIONS);
}
if (uiPermissions != null) {
// at the starup we are only adding permission only to tenant 0
Registry registry = UserMgtDSComponent.getRegistryService().getGovernanceSystemRegistry();
for (ManagementPermission uiPermission : uiPermissions) {
if (registry.resourceExists(uiPermission.getResourceId())) {
Resource existingResource = registry.get(uiPermission.getResourceId());
if (existingResource.getProperty(UserMgtConstants.DISPLAY_NAME) == null) {
existingResource.setProperty(UserMgtConstants.DISPLAY_NAME, uiPermission.getDisplayName());
registry.put(uiPermission.getResourceId(), existingResource);
}
continue;
}
Collection resource = registry.newCollection();
resource.setProperty(UserMgtConstants.DISPLAY_NAME, uiPermission.getDisplayName());
registry.put(uiPermission.getResourceId(), resource);
}
}
}
示例8
private String[] checkRolesPermissions(String[] roles) throws UserStoreException,
MultipleCredentialsUserAdminException {
RealmConfiguration realmConfig = realm.getRealmConfiguration();
if (realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_EXTERNAL_IDP) != null) {
throw new MultipleCredentialsUserAdminException(
"Please contact your external Identity Provider to add users");
}
if (roles != null) {
String loggedInUserName = getLoggedInUser();
Arrays.sort(roles);
boolean isRoleHasAdminPermission = false;
for (String role : roles) {
isRoleHasAdminPermission =
realm.getAuthorizationManager()
.isRoleAuthorized(role, "/permission",
UserMgtConstants.EXECUTE_ACTION);
if (!isRoleHasAdminPermission) {
isRoleHasAdminPermission =
realm.getAuthorizationManager()
.isRoleAuthorized(role,
"/permission/admin",
UserMgtConstants.EXECUTE_ACTION);
}
if (isRoleHasAdminPermission) {
break;
}
}
if ((Arrays.binarySearch(roles, realmConfig.getAdminRoleName()) > -1 || isRoleHasAdminPermission) &&
!realmConfig.getAdminUserName().equals(loggedInUserName)) {
log.warn("An attempt to assign user to Admin permission role by user : " +
loggedInUserName);
throw new UserStoreException("Can not assign user to Admin permission role");
}
boolean isContained = false;
String[] temp = new String[roles.length + 1];
for (int i = 0; i < roles.length; i++) {
temp[i] = roles[i];
if (roles[i].equals(realmConfig.getEveryOneRoleName())) {
isContained = true;
break;
}
}
if (!isContained) {
temp[roles.length] = realmConfig.getEveryOneRoleName();
roles = temp;
}
}
return roles;
}
示例9
/**
* @param applicationName
* @param permissionsConfig
* @throws IdentityApplicationManagementException
*/
public static void storePermissions(String applicationName, String username, PermissionsAndRoleConfig permissionsConfig)
throws IdentityApplicationManagementException {
Registry tenantGovReg = CarbonContext.getThreadLocalCarbonContext().getRegistry(
RegistryType.USER_GOVERNANCE);
String permissionResourcePath = getApplicationPermissionPath();
try {
if (!tenantGovReg.resourceExists(permissionResourcePath)) {
boolean loggedInUserChanged = false;
UserRealm realm =
(UserRealm) CarbonContext.getThreadLocalCarbonContext().getUserRealm();
if (!realm.getAuthorizationManager()
.isUserAuthorized(username, permissionResourcePath,
UserMgtConstants.EXECUTE_ACTION)) {
//Logged in user is not authorized to create the permission.
// Temporarily change the user to the admin for creating the permission
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(
realm.getRealmConfiguration().getAdminUserName());
tenantGovReg = CarbonContext.getThreadLocalCarbonContext()
.getRegistry(RegistryType.USER_GOVERNANCE);
loggedInUserChanged = true;
}
Collection appRootNode = tenantGovReg.newCollection();
appRootNode.setProperty("name", "Applications");
tenantGovReg.put(permissionResourcePath, appRootNode);
if (loggedInUserChanged) {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username);
}
}
if (permissionsConfig != null) {
ApplicationPermission[] permissions = permissionsConfig.getPermissions();
if (permissions == null || permissions.length < 1) {
return;
}
// creating the application node in the tree
String appNode = permissionResourcePath + PATH_CONSTANT + applicationName;
Collection appNodeColl = tenantGovReg.newCollection();
tenantGovReg.put(appNode, appNodeColl);
// now start storing the permissions
for (ApplicationPermission permission : permissions) {
String permissinPath = appNode + PATH_CONSTANT + permission;
Resource permissionNode = tenantGovReg.newResource();
permissionNode.setProperty("name", permission.getValue());
tenantGovReg.put(permissinPath, permissionNode);
}
}
} catch (Exception e) {
throw new IdentityApplicationManagementException("Error while storing permissions for application " +
applicationName, e);
}
}
示例10
public void addUIPermissionFromBundle(Bundle bundle) throws Exception {
BundleContext bundleContext = bundle.getBundleContext();
if (bundleContext == null) { // If the bundle got uninstalled, the bundleContext will be null
return;
}
URL url = bundleContext.getBundle().getEntry("META-INF/component.xml");
if (url == null) {
return;
}
InputStream xmlStream = url.openStream();
if (xmlStream == null) {
return;
}
if (log.isDebugEnabled()) {
log.debug("Adding permissions in bundle" +
bundle.getSymbolicName());
}
Component component = ComponentConfigFactory.build(xmlStream);
ManagementPermission[] uiPermissions = null;
if (component != null) {
uiPermissions = (ManagementPermission[]) component
.getComponentConfig(ManagementPermissionsBuilder.LOCALNAME_MGT_PERMISSIONS);
}
if (uiPermissions != null) {
// at the starup we are only adding permission only to tenant 0
Registry registry = UserMgtDSComponent.getRegistryService().getGovernanceSystemRegistry();
for (ManagementPermission uiPermission : uiPermissions) {
if (registry.resourceExists(uiPermission.getResourceId())) {
continue;
}
Collection resource = registry.newCollection();
resource.setProperty(UserMgtConstants.DISPLAY_NAME, uiPermission.getDisplayName());
registry.put(uiPermission.getResourceId(), resource);
}
}
}
示例11
private String[] checkRolesPermissions(String[] roles) throws UserStoreException,
MultipleCredentialsUserAdminException {
RealmConfiguration realmConfig = realm.getRealmConfiguration();
if (realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_EXTERNAL_IDP) != null) {
throw new MultipleCredentialsUserAdminException(
"Please contact your external Identity Provider to add users");
}
if (roles != null) {
String loggedInUserName = getLoggedInUser();
Arrays.sort(roles);
boolean isRoleHasAdminPermission = false;
for (String role : roles) {
isRoleHasAdminPermission =
realm.getAuthorizationManager()
.isRoleAuthorized(role, "/permission",
UserMgtConstants.EXECUTE_ACTION);
if (!isRoleHasAdminPermission) {
isRoleHasAdminPermission =
realm.getAuthorizationManager()
.isRoleAuthorized(role,
"/permission/admin",
UserMgtConstants.EXECUTE_ACTION);
}
if (isRoleHasAdminPermission) {
break;
}
}
if ((Arrays.binarySearch(roles, realmConfig.getAdminRoleName()) > -1 || isRoleHasAdminPermission) &&
!realmConfig.getAdminUserName().equals(loggedInUserName)) {
log.warn("An attempt to assign user to Admin permission role by user : " +
loggedInUserName);
throw new UserStoreException("Can not assign user to Admin permission role");
}
boolean isContained = false;
String[] temp = new String[roles.length + 1];
for (int i = 0; i < roles.length; i++) {
temp[i] = roles[i];
if (roles[i].equals(realmConfig.getEveryOneRoleName())) {
isContained = true;
break;
}
}
if (!isContained) {
temp[roles.length] = realmConfig.getEveryOneRoleName();
roles = temp;
}
}
return roles;
}
示例12
public static void setCloudServiceActive(boolean active,
String cloudServiceName,
int tenantId, CloudServiceConfig cloudServiceConfig)
throws Exception {
if (cloudServiceConfig.getLabel() == null) {
// for the non-labled services, we are not setting/unsetting the
// service active
return;
}
UserRegistry govRegistry =
ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry(
MultitenantConstants.SUPER_TENANT_ID);
UserRegistry configRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getConfigSystemRegistry(tenantId);
String cloudServiceInfoPath = StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH +
RegistryConstants.PATH_SEPARATOR + tenantId +
RegistryConstants.PATH_SEPARATOR + cloudServiceName;
Resource cloudServiceInfoResource;
if (govRegistry.resourceExists(cloudServiceInfoPath)) {
cloudServiceInfoResource = govRegistry.get(cloudServiceInfoPath);
} else {
cloudServiceInfoResource = govRegistry.newCollection();
}
cloudServiceInfoResource.setProperty(StratosConstants.CLOUD_SERVICE_IS_ACTIVE_PROP_KEY,
active ? "true" : "false");
govRegistry.put(cloudServiceInfoPath, cloudServiceInfoResource);
// then we will copy the permissions
List<PermissionConfig> permissionConfigs = cloudServiceConfig.getPermissionConfigs();
for (PermissionConfig permissionConfig : permissionConfigs) {
String path = permissionConfig.getPath();
String name = permissionConfig.getName();
if (active) {
if (!configRegistry.resourceExists(path)) {
Collection collection = configRegistry.newCollection();
collection.setProperty(UserMgtConstants.DISPLAY_NAME, name);
configRegistry.put(path, collection);
}
} else {
if (configRegistry.resourceExists(path)) {
configRegistry.delete(path);
}
}
}
}