コード例 #1
0
  /**
   * This method checks if the user account exist or is locked. If the account is locked, the
   * authentication process will be terminated after this method returning false.
   */
  @Override
  public boolean doPreAuthenticate(
      String userName, Object credential, UserStoreManager userStoreManager)
      throws UserStoreException {

    if (log.isDebugEnabled()) {
      log.debug("Pre authenticator is called in IdentityMgtEventListener");
    }

    IdentityMgtConfig config = IdentityMgtConfig.getInstance();

    if (!config.isEnableAuthPolicy()) {
      return true;
    }

    if (config.isAuthPolicyAccountExistCheck() && !userStoreManager.isExistingUser(userName)) {
      log.warn("User name does not exist in system : " + userName);
      throw new UserStoreException(UserCoreConstants.ErrorCode.USER_DOES_NOT_EXIST);
    }

    UserIdentityClaimsDO userIdentityDTO = module.load(userName, userStoreManager);

    // if the account is locked, should not be able to log in
    if (userIdentityDTO != null && userIdentityDTO.isAccountLocked()) {

      // If unlock time is specified then unlock the account.
      if ((userIdentityDTO.getUnlockTime() != 0)
          && (System.currentTimeMillis() >= userIdentityDTO.getUnlockTime())) {

        userIdentityDTO.setAccountLock(false);
        userIdentityDTO.setUnlockTime(0);

        try {
          module.store(userIdentityDTO, userStoreManager);
        } catch (IdentityException e) {
          throw new UserStoreException("Error while saving user", e);
        }
      } else {

        log.warn(
            "User account is locked for user : "******". cannot login until the account is unlocked ");
        throw new UserStoreException(UserCoreConstants.ErrorCode.USER_IS_LOCKED);
      }
    }

    return true;
  }
コード例 #2
0
  /**
   * This method is used to register an user in the system. The account will be locked if the
   * Authentication.Policy.Account.Lock.On.Creation is set to true. Else user will be able to login
   * after registration.
   *
   * @param userName
   * @param password
   * @param claims
   * @param profileName
   * @param tenantDomain
   * @return
   * @throws IdentityMgtServiceException
   */
  public VerificationBean registerUser(
      String userName,
      String password,
      UserIdentityClaimDTO[] claims,
      String profileName,
      String tenantDomain)
      throws IdentityMgtServiceException {

    VerificationBean vBean = new VerificationBean();

    org.wso2.carbon.user.core.UserStoreManager userStoreManager = null;
    Permission permission = null;

    if (!IdentityMgtConfig.getInstance().isSaasEnabled()) {
      String loggedInTenant =
          PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
      if (tenantDomain != null && !tenantDomain.isEmpty() && !loggedInTenant.equals(tenantDomain)) {
        String msg = "Trying to create users in unauthorized tenant space";
        log.error(msg);
        throw new IdentityMgtServiceException(msg);
      }
      if (tenantDomain == null || tenantDomain.isEmpty()) {
        tenantDomain = loggedInTenant;
      }
    }

    RealmService realmService = IdentityMgtServiceComponent.getRealmService();
    int tenantId;

    try {

      tenantId = Utils.getTenantId(tenantDomain);
      if (realmService.getTenantUserRealm(tenantId) != null) {
        userStoreManager =
            (org.wso2.carbon.user.core.UserStoreManager)
                realmService.getTenantUserRealm(tenantId).getUserStoreManager();
      }

    } catch (Exception e) {
      vBean =
          handleError(
              VerificationBean.ERROR_CODE_UNEXPECTED
                  + " Error retrieving the user store manager for the tenant",
              e);
      return vBean;
    }

    try {

      if (userStoreManager == null) {
        vBean = new VerificationBean();
        vBean.setVerified(false);
        vBean.setError(
            VerificationBean.ERROR_CODE_UNEXPECTED
                + " Error retrieving the user store manager for the tenant");
        return vBean;
      }

      Map<String, String> claimsMap = new HashMap<String, String>();
      for (UserIdentityClaimDTO userIdentityClaimDTO : claims) {
        claimsMap.put(userIdentityClaimDTO.getClaimUri(), userIdentityClaimDTO.getClaimValue());
      }

      userStoreManager.addUser(userName, password, null, claimsMap, profileName);

      String identityRoleName =
          UserCoreConstants.INTERNAL_DOMAIN
              + CarbonConstants.DOMAIN_SEPARATOR
              + IdentityConstants.IDENTITY_DEFAULT_ROLE;

      if (!userStoreManager.isExistingRole(identityRoleName, false)) {
        permission = new Permission("/permission/admin/login", UserMgtConstants.EXECUTE_ACTION);
        userStoreManager.addRole(
            identityRoleName, new String[] {userName}, new Permission[] {permission}, false);
      } else {
        userStoreManager.updateUserListOfRole(
            identityRoleName, new String[] {}, new String[] {userName});
      }

      IdentityEventListener identityEventListener =
          IdentityUtil.readEventListenerProperty(
              UserOperationEventListener.class.getName(), IdentityMgtEventListener.class.getName());

      boolean isListenerEnable = true;

      if (identityEventListener != null) {
        if (StringUtils.isNotBlank(identityEventListener.getEnable())) {
          isListenerEnable = Boolean.parseBoolean(identityEventListener.getEnable());
        }
      }

      IdentityMgtConfig config = IdentityMgtConfig.getInstance();

      if (isListenerEnable && config.isAuthPolicyAccountLockOnCreation()) {
        UserDTO userDTO = new UserDTO(userName);
        userDTO.setTenantId(tenantId);

        UserRecoveryDTO dto = new UserRecoveryDTO(userDTO);
        dto.setNotification(IdentityMgtConstants.Notification.ACCOUNT_CONFORM);
        dto.setNotificationType("EMAIL");

        RecoveryProcessor processor = IdentityMgtServiceComponent.getRecoveryProcessor();
        vBean = processor.updateConfirmationCode(1, userName, tenantId);

        dto.setConfirmationCode(vBean.getKey());
        NotificationDataDTO notificationDto = processor.notifyWithEmail(dto);
        vBean.setVerified(notificationDto.isNotificationSent());

        //				Send email data only if not internally managed.
        if (!(IdentityMgtConfig.getInstance().isNotificationInternallyManaged())) {
          vBean.setNotificationData(notificationDto);
        }

      } else {
        vBean.setVerified(true);
      }
    } catch (UserStoreException | IdentityException e) {
      UserIdentityManagementUtil.getCustomErrorMessages(e, userName);
      // Rollback if user exists
      try {
        if (userStoreManager.isExistingUser(userName)) {
          userStoreManager.deleteUser(userName);
        }
      } catch (org.wso2.carbon.user.core.UserStoreException e1) {
        UserIdentityManagementUtil.getCustomErrorMessages(e1, userName);
      }

      return vBean;
    }

    return vBean;
  }
コード例 #3
0
  public void doUserStuff() throws Exception {

    UserStoreManager admin = realm.getUserStoreManager();

    Map<String, String> userProps = new HashMap<String, String>();
    userProps.put(ClaimTestUtil.CLAIM_URI1, "1claim1Value");
    userProps.put(ClaimTestUtil.CLAIM_URI2, "2claim2Value");

    Permission[] permisions = new Permission[2];
    permisions[0] = new Permission("high security", "read");
    permisions[1] = new Permission("low security", "write");

    // add USER
    admin.addUser("dimuthu", "credential", null, null, null, false);
    try {
      admin.addUser(null, null, null, null, null, false);
      TestCase.assertTrue(false);
    } catch (Exception ex) {
      // expected error
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", ex);
      }
    }
    try {
      admin.addUser("dimuthu", null, null, null, null, false);
      TestCase.assertTrue(false);
    } catch (Exception ex) {
      // expected error
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", ex);
      }
    }
    try {
      admin.addUser(null, "credential", null, null, null, false);
      TestCase.assertTrue(false);
    } catch (Exception ex) {
      // expected error
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", ex);
      }
    }
    try {
      admin.addUser(" ", "credential", null, null, null, false);
      TestCase.assertTrue(false);
    } catch (Exception ex) {
      // expected error
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", ex);
      }
    }
    try {
      admin.addUser("dimuthu", "credential", null, null, null, false);
      fail("Exception at adding the same user again");
    } catch (Exception ex) {
      // expected error
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", ex);
      }
    }

    // add ROLE
    admin.addRole("role1", new String[] {"dimuthu"}, permisions); // dimuthu added to the role
    try {
      admin.addRole(null, null, null);
      fail("Exception at defining a roll with No information");
    } catch (Exception ex) {
      // expected error
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", ex);
      }
    }
    try {
      admin.addRole(null, new String[] {"dimuthu"}, permisions);
      fail("Exception at adding user to a non specified role");
    } catch (Exception ex) {
      // expected error
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", ex);
      }
    }
    try {
      admin.addRole("role1", new String[] {"isuru"}, permisions);
      fail("Exception at adding a non existing user to the role");
    } catch (Exception ex) {
      // expected error
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", ex);
      }
    }

    // add USER to a ROLE
    admin.addUser("vajira", "credential", new String[] {"role1"}, userProps, null, false);
    try {
      admin.addUser("Bence", "credential", new String[] {"rolexxx"}, userProps, null, false);
      fail("Exception at adding user to a Non-existing role");
    } catch (Exception ex) {
      // expected user
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", ex);
      }
    }
    try {
      admin.addUser(null, "credential", new String[] {"role1"}, userProps, null, false);
      fail("Exception at adding user to a role with no user name");
    } catch (Exception ex) {
      // expected user
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", ex);
      }
    }
    try {
      admin.addUser("vajira", "credential", new String[] {"role1"}, userProps, null, false);
      fail("Exception at adding same user to the same roll");
    } catch (Exception ex) {
      // expected user
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", ex);
      }
    }

    // Authenticate USER
    assertTrue(admin.authenticate("dimuthu", "credential"));
    assertFalse(admin.authenticate(null, "credential"));
    assertFalse(admin.authenticate("dimuthu", null));

    // update by ADMIN
    admin.updateCredentialByAdmin("dimuthu", "topsecret");
    assertTrue(admin.authenticate("dimuthu", "topsecret"));

    // isExistingUser
    assertTrue(admin.isExistingUser("dimuthu"));
    assertFalse(admin.isExistingUser("muhaha"));

    // update by USER
    admin.updateCredential("dimuthu", "password", "topsecret");
    // assertTrue(admin.authenticate("dimuthu", "password")); //TO DO
    assertFalse(admin.authenticate("dimuthu", "credential"));
    try {
      admin.updateCredential("dimuthu", "password", "xxx");
      TestCase.assertTrue(false);
    } catch (Exception ex) {
      // expected exception
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", ex);
      }
    }

    String[] names = admin.listUsers("*", 100);
    assertEquals(3, names.length);

    String[] names1 = admin.listUsers("*", 0);
    assertEquals(0, names1.length);

    String[] names2 = admin.listUsers("*", 2);
    assertEquals(2, names2.length);

    String[] names3 = admin.listUsers("di?uthu", 100);
    assertEquals(1, names3.length);

    String[] names4 = admin.listUsers("is?ru", 100);
    assertEquals(0, names4.length);

    String[] roleNames = admin.getRoleNames();
    assertEquals(3, roleNames.length);

    // delete
    admin.deleteUser("vajira");
    assertFalse(admin.isExistingUser("vajira"));
    assertFalse(admin.authenticate("vajira", "credential"));

    // delete ROLE
    admin.addUser("vajira", "credential", new String[] {"role1"}, userProps, null, false);
    assertTrue(admin.isExistingUser("vajira"));
    admin.deleteRole("role1");

    // add role
    admin.addRole("role1", new String[] {"dimuthu"}, permisions);
  }