Java Code Examples for org.wso2.carbon.user.api.UserStoreManager#addRole()

The following examples show how to use org.wso2.carbon.user.api.UserStoreManager#addRole() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ApplicationMgtUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Create a role for the application and assign the user to that role.
 *
 * @param applicationName
 * @throws IdentityApplicationManagementException
 */
public static void createAppRole(String applicationName, String username)
        throws IdentityApplicationManagementException {

    String roleName = getAppRoleName(applicationName);
    String[] usernames = {username};
    UserStoreManager userStoreManager = null;
    try {
        userStoreManager = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getUserStoreManager();
        // create a role for the application and assign the user to that role.
        if (log.isDebugEnabled()) {
            log.debug("Creating application role : " + roleName + " and assign the user : "
                    + Arrays.toString(usernames) + " to that role");
        }
        userStoreManager.addRole(roleName, usernames, null);
    } catch (UserStoreException e) {
        assignRoleToUser(username, roleName, userStoreManager, e);
    }
}
 
Example 2
Source File: BaseWebAppAuthenticatorFrameworkTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
/**
 * To get the registry service.
 * @return RegistryService
 * @throws RegistryException Registry Exception
 */
private  RegistryService getRegistryService() throws RegistryException, UserStoreException {
    RealmService realmService = new InMemoryRealmService();
    AuthenticatorFrameworkDataHolder.getInstance().setRealmService(realmService);
    UserStoreManager userStoreManager = AuthenticatorFrameworkDataHolder.getInstance().getRealmService()
            .getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).getUserStoreManager();
    Permission adminPermission = new Permission(PermissionUtils.ADMIN_PERMISSION_REGISTRY_PATH,
            CarbonConstants.UI_PERMISSION_ACTION);
    userStoreManager.addRole(ADMIN_ROLE + "t", new String[] { ADMIN_USER }, new Permission[] { adminPermission });
    RegistryDataHolder.getInstance().setRealmService(realmService);
    DeviceManagementDataHolder.getInstance().setRealmService(realmService);
    InputStream is = BaseWebAppAuthenticatorFrameworkTest.class.getClassLoader()
            .getResourceAsStream("carbon-home/repository/conf/registry.xml");
    RegistryContext context = RegistryContext.getBaseInstance(is, realmService);
    context.setSetup(true);
    return context.getEmbeddedRegistryService();
}
 
Example 3
Source File: GroupManagementProviderServiceTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(dependsOnMethods = ("updateGroupSecondTime"))
public void manageGroupSharing() throws GroupManagementException, RoleDoesNotExistException, UserStoreException {
    groupManagementProviderService.manageGroupSharing(0, null);
    List<String> newRoles = new ArrayList<>();
    newRoles.add("TEST_ROLE_1");
    newRoles.add("TEST_ROLE_2");
    newRoles.add("TEST_ROLE_3");

    UserStoreManager userStoreManager =
            DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(
                    -1234).getUserStoreManager();
    Permission[] permissions = new Permission[1];
    Permission perm = new Permission("/admin/test/perm", "add");
    permissions[0] = perm;

    userStoreManager.addRole("TEST_ROLE_1", null, permissions);
    userStoreManager.addRole("TEST_ROLE_2", null, permissions);
    userStoreManager.addRole("TEST_ROLE_3", null, permissions);

    groupManagementProviderService.manageGroupSharing(groupManagementProviderService.getGroup(
            TestUtils.createDeviceGroup1().getName()).getGroupId(), newRoles);
}
 
Example 4
Source File: APIUtil.java    From product-iots with Apache License 2.0 6 votes vote down vote up
public static void registerApiAccessRoles(String user) {
    UserStoreManager userStoreManager = null;
    try {
        userStoreManager = getUserStoreManager();
        String[] userList = new String[]{user};
        if (userStoreManager != null) {
            String rolesOfUser[] = userStoreManager.getRoleListOfUser(user);
            if (!userStoreManager.isExistingRole(Constants.DEFAULT_ROLE_NAME)) {
                userStoreManager.addRole(Constants.DEFAULT_ROLE_NAME, userList, Constants.DEFAULT_PERMISSION);
            } else if (rolesOfUser != null && Arrays.asList(rolesOfUser).contains(Constants.DEFAULT_ROLE_NAME)) {
                return;
            } else {
                userStoreManager.updateUserListOfRole(Constants.DEFAULT_ROLE_NAME, new String[0], userList);
            }
        }
    } catch (UserStoreException e) {
        log.error("Error while creating a role and adding a user for virtual_firealarm.", e);
    }
}
 
Example 5
Source File: UserRoleCreator.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 6
Source File: TenantCreateObserver.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
/**
 * Create configuration context.
 *
 * @param configurationContext {@link ConfigurationContext} object
 */
public void createdConfigurationContext(ConfigurationContext configurationContext) {
    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();

    try {
        //Add the devicemgt-user and devicemgt-admin roles if not exists.
        UserRealm userRealm = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm();
        UserStoreManager userStoreManager =
                DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
                        .getUserStoreManager();
        String tenantAdminName = userRealm.getRealmConfiguration().getAdminUserName();
        userStoreManager.addRole(User.DEFAULT_DEVICE_USER, null, User.PERMISSIONS_FOR_DEVICE_USER);
        userStoreManager.addRole(User.DEFAULT_DEVICE_ADMIN, new String[]{tenantAdminName},
                                 User.PERMISSIONS_FOR_DEVICE_ADMIN);
        if (log.isDebugEnabled()) {
            log.debug("Device management roles: " + User.DEFAULT_DEVICE_USER + ", " + User.DEFAULT_DEVICE_ADMIN +
                              " created for the tenant:" + tenantDomain + "."
            );
            log.debug("Tenant administrator: " + tenantAdminName + "@" + tenantDomain +
                              " is assigned to the role:" + User.DEFAULT_DEVICE_ADMIN + "."
            );
        }
    } catch (UserStoreException e) {
        log.error("Error occurred while creating roles for the tenant: " + tenantDomain + ".");
    }
}
 
Example 7
Source File: DeviceAccessAuthorizationServiceTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
private void initializeTestEnvironment() throws UserStoreException, GroupManagementException,
        RoleDoesNotExistException, DeviceNotFoundException {
    //creating UI permission
    Permission adminPermission = new Permission(ADMIN_PERMISSION, CarbonConstants.UI_PERMISSION_ACTION);
    Permission deviceViewPermission = new Permission(NON_ADMIN_PERMISSION, CarbonConstants.UI_PERMISSION_ACTION);
    UserStoreManager userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService()
            .getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).getUserStoreManager();
    //Adding a non Admin User
    userStoreManager.addUser(NON_ADMIN_ALLOWED_USER, PASSWORD, null, defaultUserClaims, null);
    //Adding a normal user
    userStoreManager.addUser(NORMAL_USER, PASSWORD, null, defaultUserClaims, null);
    //Adding role with permission to Admin user
    userStoreManager.addRole(ADMIN_ROLE, new String[]{ADMIN_USER}, new Permission[]{adminPermission});
    //Adding role with permission to non Admin user
    userStoreManager.addRole(NON_ADMIN_ROLE, new String[]{NON_ADMIN_ALLOWED_USER},
            new Permission[]{deviceViewPermission});
    //Creating default group
    GroupManagementProviderService groupManagementProviderService = DeviceManagementDataHolder.getInstance()
            .getGroupManagementProviderService();
    groupManagementProviderService.createDefaultGroup(DEFAULT_GROUP);
    int groupId = groupManagementProviderService.getGroup(DEFAULT_GROUP).getGroupId();
    //Sharing group with admin and non admin roles
    groupManagementProviderService.manageGroupSharing(groupId, new ArrayList<>(Arrays.asList(ADMIN_ROLE,
            NON_ADMIN_ROLE)));
    //Adding first 2 devices to the group
    groupDeviceIds.add(deviceIds.get(0));
    groupDeviceIds.add(deviceIds.get(1));
    groupManagementProviderService.addDevices(groupId, groupDeviceIds);
}
 
Example 8
Source File: APIManagerComponent.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 9
Source File: RegistryTopicManager.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new role which has the same name as the destinationName and assign the logged in
 * user to the newly created role. Then, authorize the newly created role to subscribe and
 * publish to the destination.
 *
 * @param username        name of the logged in user
 * @param destinationName destination name. Either topic or queue name
 * @param destinationId   ID given to the destination
 * @param userRealm       the  user store
 * @throws UserStoreException
 */
private static void authorizePermissionsToLoggedInUser(String username, String destinationName,
                                                       String destinationId,
                                                       UserRealm userRealm) throws
                                                                            UserStoreException {

    //For registry we use a modified queue name
    String newDestinationName = destinationName.replace("@", AT_REPLACE_CHAR);

    // creating the internal role name
    String roleName = UserCoreUtil.addInternalDomainName(TOPIC_ROLE_PREFIX +
                                                         newDestinationName.replace("/", "-"));

    // the interface to store user data
    UserStoreManager userStoreManager = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getUserStoreManager();

    if (!userStoreManager.isExistingRole(roleName)) {
        String[] user = {MultitenantUtils.getTenantAwareUsername(username)};

        // adds the internal role to user store
        userStoreManager.addRole(roleName, user, null);
        // gives subscribe permissions to the internal role in the user store
        userRealm.getAuthorizationManager().authorizeRole(
                roleName, destinationId, EventBrokerConstants.EB_PERMISSION_SUBSCRIBE);
        // gives publish permissions to the internal role in the user store
        userRealm.getAuthorizationManager().authorizeRole(
                roleName, destinationId, EventBrokerConstants.EB_PERMISSION_PUBLISH);
        // gives change permissions to the internal role in the user store
        userRealm.getAuthorizationManager().authorizeRole(
                roleName, destinationId, EventBrokerConstants.EB_PERMISSION_CHANGE_PERMISSION);

    } else {
        log.warn("Unable to provide permissions to the user, " +
                 " " + username + ", to subscribe and publish to " + newDestinationName);
    }
}