org.wso2.carbon.user.api.UserRealm Java Examples

The following examples show how to use org.wso2.carbon.user.api.UserRealm. 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: JsClaims.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Sets a local claim directly at the userstore for the given user by given claim uri
 *
 * @param claimUri   Local claim URI
 * @param claimValue Claim value
 */
private void setLocalUserClaim(String claimUri, Object claimValue) {

    int usersTenantId = IdentityTenantUtil.getTenantId(authenticatedUser.getTenantDomain());
    RealmService realmService = FrameworkServiceDataHolder.getInstance().getRealmService();
    String usernameWithDomain = UserCoreUtil.addDomainToName(authenticatedUser.getUserName(), authenticatedUser
        .getUserStoreDomain());
    try {
        UserRealm userRealm = realmService.getTenantUserRealm(usersTenantId);
        Map<String, String> claimUriMap = new HashMap<>();
        claimUriMap.put(claimUri, String.valueOf(claimValue));
        userRealm.getUserStoreManager().setUserClaimValues(usernameWithDomain, claimUriMap, null);
    } catch (UserStoreException e) {
        LOG.error(String.format("Error when setting claim : %s of user: %s to value: %s", claimUri,
                authenticatedUser, String.valueOf(claimValue)), e);
    }
}
 
Example #2
Source File: CarbonUserRealmHostObject.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public static boolean jsFunction_isUserAuthorized(Context cx,
		Scriptable thisObj, Object[] args, Function funObj) throws Exception {
	boolean isAuthorized = false;
	int argLength = args.length;
	if (argLength != 3) {
		throw new ScriptException("Invalid arguments.");
	}
	String user = (String) args[0];
	String userName = MultitenantUtils.getTenantAwareUsername(user);
	String domainName = MultitenantUtils.getTenantDomain(user);
	RealmService service = ServiceHodler.getRealmService();
	int tenantId = service.getTenantManager().getTenantId(domainName);
	UserRealm realm = service.getTenantUserRealm(tenantId);
	isAuthorized = realm.getAuthorizationManager().isUserAuthorized(userName, (String) args[1], (String) args[2]);
	return isAuthorized;
}
 
Example #3
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetRoleNamesNonSuperTenant() throws Exception {
    String userName = "John";

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);

    String[] roleNames = {"role1", "role2"};

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(MultitenantUtils.class);
    Mockito.when(MultitenantUtils.getTenantDomain(userName)).
            thenReturn("test.com");
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(realmService.getTenantUserRealm(Mockito.anyInt())).thenReturn(userRealm);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.when(userStoreManager.getRoleNames()).thenReturn(roleNames);

    Assert.assertEquals(roleNames, APIUtil.getRoleNames(userName));
}
 
Example #4
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsRoleNameNotExist() throws Exception {
    String userName = "John";
    String roleName = "developer";

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(realmService.getTenantUserRealm(Mockito.anyInt())).thenReturn(userRealm);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.when(userStoreManager.isExistingRole(roleName)).thenReturn(false);

    Assert.assertFalse(APIUtil.isRoleNameExist(userName, roleName));
}
 
Example #5
Source File: AuthenticatorUtilTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test(expected = AuthenticationException.class)
public void authorizeUser_throwsException() throws Exception {
    List<String> authorization = new ArrayList<>();
    authorization.add("OGpvbmExakBnb29nbC5pZ2cuYml6QGNjYzIyMjI6QW1hbmRhMTI=");
    HttpHeaders httpHeaders = Mockito.mock(HttpHeaders.class);
    Mockito.doReturn(authorization).when(httpHeaders).getRequestHeader("Authorization");

    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);

    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    CarbonContext carbonContext = Mockito.mock(CarbonContext.class);
    PowerMockito.mockStatic(CarbonContext.class);
    PowerMockito.when(CarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    Mockito.when(carbonContext.getUserRealm()).thenReturn(userRealm);
    Mockito.when(userRealm.getUserStoreManager()).thenThrow(UserStoreException.class);

    AuthenticatorUtil.authorizeUser(httpHeaders);
}
 
Example #6
Source File: InMemoryDeliveryManager.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public void subscribe(Subscription subscription) throws EventBrokerException {
   String resoucePath = JavaUtil.getResourcePath(subscription.getTopicName(), this.topicStoragePath);
    try {
        UserRealm userRealm =
                EventBrokerHolder.getInstance().getRealmService().getTenantUserRealm
                                           (CarbonContext.getThreadLocalCarbonContext().getTenantId());
        String userName = subscription.getOwner();
        // trim the domain part if it is there.
        if (userName.lastIndexOf("@") != -1){
            userName = userName.substring(0, userName.lastIndexOf("@"));
        }
        if (userName.equals(CarbonConstants.REGISTRY_SYSTEM_USERNAME) ||
                userRealm.getAuthorizationManager().isUserAuthorized(
                    userName,
                    resoucePath,
                    EventBrokerConstants.EB_PERMISSION_SUBSCRIBE)){
                   this.matchingManager.addSubscription(subscription);
        } else {
            throw new EventBrokerException("User " + CarbonContext.getThreadLocalCarbonContext().getUsername()
                           + " is not allowed to subscribes to " + subscription.getTopicName());
        }
    } catch (UserStoreException e) {
        throw new EventBrokerException("Can not access the user store manager");
    }

}
 
Example #7
Source File: StratosApiV41Utils.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * Get Tenant UserStoreManager
 *
 * @return UserStoreManager
 * @throws UserManagerException
 */
private static UserStoreManager getTenantUserStoreManager() throws UserManagerException {

    CarbonContext carbonContext = CarbonContext.getThreadLocalCarbonContext();
    UserRealm userRealm;
    UserStoreManager userStoreManager;

    try {
        userRealm = carbonContext.getUserRealm();
        userStoreManager = userRealm.getUserStoreManager();

    } catch (UserStoreException e) {
        String msg = "Error in retrieving UserStore Manager";
        log.error(msg, e);
        throw new UserManagerException(msg, e);
    }

    return userStoreManager;
}
 
Example #8
Source File: StratosAuthorizingHandler.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
private boolean authorize(String userName, String tenantDomain, int tenantId, Method targetMethod) throws Exception {
    // first we try to see whether this is a super.tenant only operation
    if (superTenantServiceSet.contains(targetMethod.getName()) && !isCurrentUserSuperTenant(tenantDomain, tenantId)) {
        return false;
    }
    // authorize using permissionString given as annotation in the service class
    String permissionString = authorizationActionMap.get(targetMethod.getName());

    // get the authorization manager for this tenant..
    UserRealm userRealm = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm();
    AuthorizationManager authorizationManager = userRealm.getAuthorizationManager();

    boolean isAuthorized = isAuthorized(authorizationManager, userName, permissionString, ACTION_ON_RESOURCE);
    return isAuthorized;

}
 
Example #9
Source File: ApiPermissionFilter.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether the client is authorized with the given permission and action.
 * @param permission           Carbon permission that requires for the use
 * @param action               Carbon permission action that requires for the given permission.
 * @return boolean - true if user is authorized else return false.
 */
private boolean isUserAuthorized(String permission, String action) {
    PrivilegedCarbonContext context = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    String username = context.getUsername();
    try {
        UserRealm userRealm = APIUtil.getRealmService().getTenantUserRealm(PrivilegedCarbonContext
                            .getThreadLocalCarbonContext().getTenantId());
        String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
        boolean status =  userRealm.getAuthorizationManager()
                .isUserAuthorized(tenantAwareUsername, permission, action);
        if (!status) {
            String[] roles = userRealm.getUserStoreManager().getRoleListOfUser(tenantAwareUsername);
            for (String role : roles) {
                if (role.equals(DEFAULT_ADMIN_ROLE)) {
                    return true;
                }
            }
        }
        return status;
    } catch (UserStoreException e) {
        String errorMsg = String.format("Unable to authorize the user : %s", username);
        log.error(errorMsg, e);
        return false;
    }
}
 
Example #10
Source File: UserManagementServiceImplTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void setup() throws UserStoreException {
    initMocks(this);
    userManagementService = new UserManagementServiceImpl();
    userStoreManager = Mockito.mock(UserStoreManager.class, Mockito.RETURNS_MOCKS);
    deviceManagementProviderService = Mockito
            .mock(DeviceManagementProviderServiceImpl.class, Mockito.CALLS_REAL_METHODS);
    userRealm = Mockito.mock(UserRealm.class);
    RealmConfiguration realmConfiguration = Mockito.mock(RealmConfiguration.class);
    Mockito.doReturn(null).when(realmConfiguration).getSecondaryRealmConfig();
    Mockito.doReturn(realmConfiguration).when(userRealm).getRealmConfiguration();
    enrollmentInvitation = new EnrollmentInvitation();
    List<String> recipients = new ArrayList<>();
    recipients.add(TEST_USERNAME);
    enrollmentInvitation.setDeviceType("android");
    enrollmentInvitation.setRecipients(recipients);
    userList = new ArrayList<>();
    userList.add(TEST_USERNAME);
}
 
Example #11
Source File: UserManagementServiceImplTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void setup() throws UserStoreException {
    initMocks(this);
    userManagementService = new UserManagementServiceImpl();
    userStoreManager = Mockito.mock(UserStoreManager.class, Mockito.RETURNS_MOCKS);
    deviceManagementProviderService = Mockito
            .mock(DeviceManagementProviderServiceImpl.class, Mockito.CALLS_REAL_METHODS);
    userRealm = Mockito.mock(UserRealm.class);
    RealmConfiguration realmConfiguration = Mockito.mock(RealmConfiguration.class);
    Mockito.doReturn(null).when(realmConfiguration).getSecondaryRealmConfig();
    Mockito.doReturn(realmConfiguration).when(userRealm).getRealmConfiguration();
    enrollmentInvitation = new EnrollmentInvitation();
    List<String> recipients = new ArrayList<>();
    recipients.add(TEST_USERNAME);
    enrollmentInvitation.setDeviceType("android");
    enrollmentInvitation.setRecipients(recipients);
    userList = new ArrayList<>();
    userList.add(TEST_USERNAME);
}
 
Example #12
Source File: IdentityUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Check the case sensitivity of the user store.
 *
 * @param userStoreDomain user store domain
 * @param tenantId        tenant id of the user store
 * @return
 */
public static boolean isUserStoreCaseSensitive(String userStoreDomain, int tenantId) {

    boolean isUsernameCaseSensitive = true;
    if (tenantId == MultitenantConstants.INVALID_TENANT_ID) {
        //this is to handle federated scenarios
        return true;
    }
    try {
        UserRealm tenantUserRealm = IdentityTenantUtil.getRealmService().getTenantUserRealm(tenantId);
        if (tenantUserRealm != null) {
            org.wso2.carbon.user.core.UserStoreManager userStoreManager = (org.wso2.carbon.user.core.UserStoreManager) tenantUserRealm
                    .getUserStoreManager();
            org.wso2.carbon.user.core.UserStoreManager userAvailableUserStoreManager = userStoreManager.getSecondaryUserStoreManager(userStoreDomain);
            return isUserStoreCaseSensitive(userAvailableUserStoreManager);
        }
    } catch (UserStoreException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error while reading user store property CaseInsensitiveUsername. Considering as case " +
                    "sensitive.");
        }
    }
    return isUsernameCaseSensitive;
}
 
Example #13
Source File: JsClaims.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Get the local user claim value specified by the Claim URI.
 *
 * @param claimUri Local claim URI
 * @return Claim value of the given claim URI for the local user if available. Null Otherwise.
 */
private String getLocalUserClaim(String claimUri) {

    int usersTenantId = IdentityTenantUtil.getTenantId(authenticatedUser.getTenantDomain());
    String usernameWithDomain = UserCoreUtil.addDomainToName(authenticatedUser.getUserName(), authenticatedUser
        .getUserStoreDomain());
    RealmService realmService = FrameworkServiceDataHolder.getInstance().getRealmService();
    try {
        UserRealm userRealm = realmService.getTenantUserRealm(usersTenantId);
        Map<String, String> claimValues = userRealm.getUserStoreManager().getUserClaimValues(usernameWithDomain, new
            String[]{claimUri}, null);
        return claimValues.get(claimUri);
    } catch (UserStoreException e) {
        LOG.error(String.format("Error when getting claim : %s of user: %s", claimUri, authenticatedUser), e);
    }
    return null;
}
 
Example #14
Source File: JsAuthenticatedUser.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private String[] getLocalRoles() {

        if (idp == null || FrameworkConstants.LOCAL.equals(idp)) {
            RealmService realmService = FrameworkServiceDataHolder.getInstance().getRealmService();
            int usersTenantId = IdentityTenantUtil.getTenantId(getWrapped().getTenantDomain());

            try {
                String usernameWithDomain = UserCoreUtil.addDomainToName(getWrapped().getUserName(), getWrapped()
                    .getUserStoreDomain());
                UserRealm userRealm = realmService.getTenantUserRealm(usersTenantId);
                return userRealm.getUserStoreManager().getRoleListOfUser(usernameWithDomain);
            } catch (UserStoreException e) {
                LOG.error("Error when getting role list of user: " + getWrapped(), e);
            }
        }
        return ArrayUtils.EMPTY_STRING_ARRAY;
    }
 
Example #15
Source File: ApplicationManagementServiceImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private void assignApplicationRole(String applicationName, String username)
        throws IdentityApplicationManagementException {

    String roleName = getAppRoleName(applicationName);
    String[] newRoles = {roleName};

    try {
        // assign new application role to the user.
        UserRealm realm = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm();
        if (realm != null) {
            if (((AbstractUserStoreManager) realm.getUserStoreManager()).isUserInRole(username, roleName)) {
                if (log.isDebugEnabled()) {
                    log.debug("The user: " + username + " is already having the role: " + roleName);
                }
            } else {
                realm.getUserStoreManager().updateRoleListOfUser(username, null, newRoles);
                if (log.isDebugEnabled()) {
                    log.debug("Assigning application role : " + roleName + " to the user : " + username);
                }
            }
        }
    } catch (UserStoreException e) {
        throw new IdentityApplicationManagementException("Error while assigning application role: " + roleName +
                " to the user: " + username, e);
    }
}
 
Example #16
Source File: StratosAuthorizingHandler.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
private boolean authorize(String userName, String tenantDomain, int tenantId,
                          Method targetMethod) throws Exception {
    // first we try to see whether this is a super.tenant only operation
    if (superTenantServiceSet.contains(targetMethod.getName()) &&
            !isCurrentUserSuperTenant(tenantDomain, tenantId)) {
        return false;
    }
    // authorize using permissionString given as annotation in the service
    // class
    String permissionString = authorizationActionMap.get(targetMethod.getName());

    // get the authorization manager for this tenant..
    UserRealm userRealm = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm();
    AuthorizationManager authorizationManager = userRealm.getAuthorizationManager();

    boolean isAuthorized =
            isAuthorized(authorizationManager, userName, permissionString,
                    ACTION_ON_RESOURCE);
    return isAuthorized;

}
 
Example #17
Source File: StratosAuthorizingHandler.java    From product-private-paas with Apache License 2.0 6 votes vote down vote up
private boolean authorize(String userName, String tenantDomain, int tenantId, Method targetMethod)
        throws Exception {
    // first we try to see whether this is a super.tenant only operation
    if (superTenantServiceSet.contains(targetMethod.getName()) && !isCurrentUserSuperTenant(tenantDomain,
            tenantId)) {
        return false;
    }
    // authorize using permissionString given as annotation in the service class
    String permissionString = authorizationActionMap.get(targetMethod.getName());

    // get the authorization manager for this tenant..
    UserRealm userRealm = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm();
    AuthorizationManager authorizationManager = userRealm.getAuthorizationManager();

    boolean isAuthorized = isAuthorized(authorizationManager, userName, permissionString, ACTION_ON_RESOURCE);
    return isAuthorized;

}
 
Example #18
Source File: AuthenticationServiceImpl.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * If the use is invalid, throws an <code>AuthenticationException</code>
 * If the password is equals to the shared key, returns <code>true</code>
 * Otherwise, calls the authenticate method of the <code>UserStoreManager<code>
 *
 * @param username The name of the user to be authenticated
 * @param password The password of the user to be authenticated.
 * @return <code>true</code> if the authentication is successful.
 * @throws AuthenticationException for failures in the authentication
 */
public boolean authenticate(String username, String password) throws AuthenticationException {
    String tenantLessUsername = MultitenantUtils.getTenantAwareUsername(username);
    try {
        int tenantID = MultitenantConstants.SUPER_TENANT_ID;
        if (username.contains("@")) {
            tenantID = realmService.getTenantManager().getTenantId(username.substring(username.lastIndexOf("@") + 1));
        }
        UserRealm userRealm = realmService.getTenantUserRealm(tenantID);

        // User not found in the UM
        if (!userRealm.getUserStoreManager().isExistingUser(tenantLessUsername)) {
            throw new AuthenticationException("Invalid User : " + tenantLessUsername, log);
        }

        // Authenticate internal call from another Carbon bundle
        if (password.equals(sharedKeyAccessService.getSharedKey())) {
            return true;
        }

        // Check if the user is authenticated
        return userRealm.getUserStoreManager().authenticate(tenantLessUsername, password);

        // Let the engine know if the user is authenticated or not
    } catch (UserStoreException e) {
        throw new AuthenticationException("User not authenticated for the given username : " + tenantLessUsername, log);
    }
}
 
Example #19
Source File: DeviceMgtAPIUtils.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
public static boolean isAdmin() throws UserStoreException {
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
    UserRealm realmService = DeviceMgtAPIUtils.getRealmService().getTenantUserRealm(tenantId);
    String adminRoleName = realmService.getRealmConfiguration().getAdminRoleName();
    String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
    String[] roles = realmService.getUserStoreManager().getRoleListOfUser(userName);
    for (String role: roles){
        if (role != null && role.equals(adminRoleName)){
            return true;
        }
    }
    return false;
}
 
Example #20
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsRoleNameExist() throws Exception {
    String userName = "John";
    String roleName = "developer";

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(realmService.getTenantUserRealm(Mockito.anyInt())).thenReturn(userRealm);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.when(userStoreManager.isExistingRole(roleName)).thenReturn(true);

    Mockito.when(userStoreManager.isExistingRole("NonExistingDomain/role")).thenThrow(UserStoreException.class);
    Mockito.when(userStoreManager.isExistingRole("NonExistingDomain/")).thenThrow(UserStoreException.class);
    
    Assert.assertTrue(APIUtil.isRoleNameExist(userName, roleName));
    Assert.assertFalse(APIUtil.isRoleNameExist(userName, "NonExistingDomain/role"));
    Assert.assertFalse(APIUtil.isRoleNameExist(userName, "NonExistingDomain/"));
    Assert.assertTrue(APIUtil.isRoleNameExist(userName, ""));//allow adding empty role
}
 
Example #21
Source File: SharedMemoryDeliveryManager.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
public void subscribe(Subscription subscription) throws EventBrokerException {

       String resourcePath = JavaUtil.getResourcePath(subscription.getTopicName(), this.topicStoragePath);
        try {
            UserRealm userRealm =
                    EventBrokerHolder.getInstance().getRealmService().getTenantUserRealm
                                               (CarbonContext.getThreadLocalCarbonContext().getTenantId());
            String userName = subscription.getOwner();

            // trim the domain part if it is there.
            if (userName.lastIndexOf("@") != -1){
                userName = userName.substring(0, userName.lastIndexOf("@"));
            }
            if (userName.equals(CarbonConstants.REGISTRY_SYSTEM_USERNAME) ||
                    userRealm.getAuthorizationManager().isUserAuthorized(
                        userName,
                        resourcePath,
                        EventBrokerConstants.EB_PERMISSION_SUBSCRIBE)){
                getMatchingManager().addSubscription(subscription);
            } else {
                throw new EventBrokerException("User " + CarbonContext.getThreadLocalCarbonContext().getUsername()
                               + " is not allowed to subscribes to " + subscription.getTopicName());
            }
        } catch (UserStoreException e) {
            throw new EventBrokerException("Can not access the user store manager",e);
        }

    }
 
Example #22
Source File: UserSignupHandler.java    From cellery-security with Apache License 2.0 5 votes vote down vote up
public void addUser(String username, String password) {

        UserRealm tenantUserRealm = null;
        try {
            tenantUserRealm = IdentityTenantUtil.getRealmService().getTenantUserRealm(-1234);
            tenantUserRealm.getUserStoreManager().addUser(username, password, new String[]{"admin"}, null, null);
        } catch (UserStoreException e) {
            log.info("User already exists. Hence not adding: " + username);
            log.debug("Error while adding user :" + username, e);
        }

    }
 
Example #23
Source File: AuthenticatorUtilTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void authorizeUser_unauthroizedUser() throws Exception {
    List<String> authorization = new ArrayList<>();
    authorization.add("OGpvbmExakBnb29nbC5pZ2cuYml6QGNjYzIyMjI6QW1hbmRhMTI=");
    HttpHeaders httpHeaders = Mockito.mock(HttpHeaders.class);
    Mockito.doReturn(authorization).when(httpHeaders).getRequestHeader("Authorization");

    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);

    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    CarbonContext carbonContext = Mockito.mock(CarbonContext.class);
    PowerMockito.mockStatic(CarbonContext.class);
    PowerMockito.when(CarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    Mockito.when(carbonContext.getUserRealm()).thenReturn(userRealm);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.doReturn(true).when(userStoreManager).authenticate(any(String.class), any(String.class));

    RealmConfiguration realmConfiguration = Mockito.mock(RealmConfiguration.class);
    Mockito.when(userRealm.getRealmConfiguration()).thenReturn(realmConfiguration);
    Mockito.doReturn("admin").when(realmConfiguration).getAdminRoleName();

    String[] userRoles = new String[2];
    userRoles[0] = "subscriber";
    userRoles[1] = "publisher";

    Mockito.doReturn(userRoles).when(userStoreManager).getRoleListOfUser(any(String.class));

    AuthDTO response = AuthenticatorUtil.authorizeUser(httpHeaders);
    Assert.assertEquals(Response.Status.UNAUTHORIZED, response.getResponseStatus());
}
 
Example #24
Source File: AuthenticatorUtilTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void authorizeUser() throws Exception {
    List<String> authorization = new ArrayList<>();
    authorization.add("OGpvbmExakBnb29nbC5pZ2cuYml6QGNjYzIyMjI6QW1hbmRhMTI=");
    HttpHeaders httpHeaders = Mockito.mock(HttpHeaders.class);
    Mockito.doReturn(authorization).when(httpHeaders).getRequestHeader("Authorization");

    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);

    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    CarbonContext carbonContext = Mockito.mock(CarbonContext.class);
    PowerMockito.mockStatic(CarbonContext.class);
    PowerMockito.when(CarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    Mockito.when(carbonContext.getUserRealm()).thenReturn(userRealm);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.doReturn(true).when(userStoreManager).authenticate(any(String.class), any(String.class));

    RealmConfiguration realmConfiguration = Mockito.mock(RealmConfiguration.class);
    Mockito.when(userRealm.getRealmConfiguration()).thenReturn(realmConfiguration);
    Mockito.doReturn("admin").when(realmConfiguration).getAdminRoleName();

    String[] userRoles = new String[2];
    userRoles[0] = "admin";
    userRoles[1] = "publisher";
    Mockito.doReturn(userRoles).when(userStoreManager).getRoleListOfUser(any(String.class));

    AuthDTO response = AuthenticatorUtil.authorizeUser(httpHeaders);
    Assert.assertEquals(Response.Status.OK, response.getResponseStatus());
}
 
Example #25
Source File: SharedMemoryDeliveryManager.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
public void publish(Message message, String topicName, int deliveryMode) throws EventBrokerException {

        String resourcePath = JavaUtil.getResourcePath(topicName, this.topicStoragePath);
        try {
            UserRealm userRealm =
                    EventBrokerHolder.getInstance().getRealmService().getTenantUserRealm
                            (CarbonContext.getThreadLocalCarbonContext().getTenantId());
            String userName = CarbonContext.getThreadLocalCarbonContext().getUsername();
            
            if (userName == null){
                userName = CarbonConstants.REGISTRY_SYSTEM_USERNAME;
            }
            if (userName.equals(CarbonConstants.REGISTRY_SYSTEM_USERNAME) ||
                    userRealm.getAuthorizationManager().isUserAuthorized(
                        userName,
                        resourcePath,
                        EventBrokerConstants.EB_PERMISSION_PUBLISH)) {
                List<Subscription> subscriptions = getMatchingManager().getMatchingSubscriptions(topicName);

                for (Subscription subscription : subscriptions) {
                    String verified = org.wso2.carbon.event.core.sharedmemory.SharedMemorySubscriptionStorage
                    						.getSubscriptionIDTopicNameCache().get(subscription.getId()+"-notVerfied");
                    
                    if(verified != null && "false".equalsIgnoreCase(verified)){
                            subscription.addProperty("notVerfied", "false");
                    }

                    this.executor.submit(new Worker(this.notificationManager, message, subscription));
                }
            } else {
                throw new EventBrokerException("User " + CarbonContext.getThreadLocalCarbonContext().getUsername()
                        + " is not allowed to publish to " + topicName);
            }
        } catch (UserStoreException e) {
            throw new EventBrokerException("Can not access the user store manager",e);
        }
    }
 
Example #26
Source File: InMemoryDeliveryManager.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
public void publish(Message message, String topicName, int deliveryMode) throws EventBrokerException {

        String resoucePath = JavaUtil.getResourcePath(topicName, this.topicStoragePath);
        try {
            UserRealm userRealm =
                    EventBrokerHolder.getInstance().getRealmService().getTenantUserRealm
                            (CarbonContext.getThreadLocalCarbonContext().getTenantId());
            String userName = CarbonContext.getThreadLocalCarbonContext().getUsername();
            
            if (userName == null){
                userName = CarbonConstants.REGISTRY_SYSTEM_USERNAME;
            }
            if (userName.equals(CarbonConstants.REGISTRY_SYSTEM_USERNAME) ||
                    userRealm.getAuthorizationManager().isUserAuthorized(
                        userName,
                        resoucePath,
                        EventBrokerConstants.EB_PERMISSION_PUBLISH)) {
                List<Subscription> subscriptions = this.matchingManager.getMatchingSubscriptions(topicName);
                for (Subscription subscription : subscriptions) {
                    this.executor.submit(new Worker(this.notificationManager, message, subscription));
                }
            } else {
                throw new EventBrokerException("User " + CarbonContext.getThreadLocalCarbonContext().getUsername()
                        + " is not allowed to publish to " + topicName);
            }
        } catch (UserStoreException e) {
            throw new EventBrokerException("Can not access the user store manager");
        }
    }
 
Example #27
Source File: DeleteUserWFRequestHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public void onWorkflowCompletion(String status, Map<String, Object> requestParams,
                                 Map<String, Object> responseAdditionalParams, int tenantId)
        throws WorkflowException {
    String userName;
    Object requestUsername = requestParams.get(USERNAME);
    if (requestUsername == null || !(requestUsername instanceof String)) {
        throw new WorkflowException("Callback request for delete user received without the mandatory " +
                "parameter 'username'");
    }
    String userStoreDomain = (String) requestParams.get(USER_STORE_DOMAIN);
    if (StringUtils.isNotBlank(userStoreDomain)) {
        userName = userStoreDomain + "/" + requestUsername;
    } else {
        userName = (String) requestUsername;
    }

    if (WorkflowRequestStatus.APPROVED.toString().equals(status) ||
            WorkflowRequestStatus.SKIPPED.toString().equals(status)) {
        try {
            RealmService realmService = IdentityWorkflowDataHolder.getInstance().getRealmService();
            UserRealm userRealm = realmService.getTenantUserRealm(tenantId);
            userRealm.getUserStoreManager().deleteUser(userName);
        } catch (UserStoreException e) {
            // Sending e.getMessage() since it is required to give error message to end user.
            throw new WorkflowException(e.getMessage(), e);
        }
    } else {
        if (retryNeedAtCallback()) {
            //unset threadlocal variable
            unsetWorkFlowCompleted();
        }
        if (log.isDebugEnabled()) {
            log.debug("Deleting user is aborted for user '" + userName + "', Reason: Workflow response was " +
                    status);
        }
    }
}
 
Example #28
Source File: RegistryTopicManager.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public TopicRolePermission[] getTopicRolePermission(String topicName)
        throws EventBrokerException {
    String topicResourcePath = JavaUtil.getResourcePath(topicName, this.topicStoragePath);
    List<TopicRolePermission> topicRolePermissions = new ArrayList<TopicRolePermission>();
    UserRealm userRealm = CarbonContext.getThreadLocalCarbonContext().getUserRealm();
    String adminRole =
            EventBrokerHolder.getInstance().getRealmService().
                    getBootstrapRealmConfiguration().getAdminRoleName();
    TopicRolePermission topicRolePermission;
    try {
        for (String role : userRealm.getUserStoreManager().getRoleNames()) {
            // remove admin role and anonymous role related permissions
            if (!(role.equals(adminRole) ||
                  CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME.equals(role))) {
                topicRolePermission = new TopicRolePermission();
                topicRolePermission.setRoleName(role);
                topicRolePermission.setAllowedToSubscribe(
                        userRealm.getAuthorizationManager().isRoleAuthorized(
                                role, topicResourcePath, EventBrokerConstants.EB_PERMISSION_SUBSCRIBE));
                topicRolePermission.setAllowedToPublish(
                        userRealm.getAuthorizationManager().isRoleAuthorized(
                                role, topicResourcePath, EventBrokerConstants.EB_PERMISSION_PUBLISH));
                topicRolePermissions.add(topicRolePermission);
            }
        }
        return topicRolePermissions.toArray(
                new TopicRolePermission[topicRolePermissions.size()]);
    } catch (UserStoreException e) {
        throw new EventBrokerException("Cannot access the UserStore manager ", e);
    }
}
 
Example #29
Source File: RegistryTopicManager.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String[] getBackendRoles() throws EventBrokerException {
    UserRealm userRealm = CarbonContext.getThreadLocalCarbonContext().getUserRealm();
    String[] cleanedRoles = new String[0];
    try {
        String adminRole =
                EventBrokerHolder.getInstance().getRealmService().
                        getBootstrapRealmConfiguration().getAdminRoleName();
        String[] allRoles = userRealm.getUserStoreManager().getRoleNames();
        // check if there is only admin role exists.
        if (allRoles != null && allRoles.length > 1) {
            // check if more roles available than admin role and anonymous role
            List<String> allRolesArrayList = new ArrayList<>();
            Collections.addAll(allRolesArrayList, allRoles);

            Iterator<String> it = allRolesArrayList.iterator();
            while (it.hasNext()) {
                String nextRole = it.next();
                if (nextRole.equals(adminRole) || nextRole.equals(CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME)) {
                    it.remove();
                }
            }

            cleanedRoles = allRolesArrayList.toArray(new String[allRolesArrayList.size()]);
        }

    } catch (UserStoreException e) {
        throw new EventBrokerException("Unable to get Roles from user store", e);
    }

    return cleanedRoles;
}
 
Example #30
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);
    }
}