Search in sources :

Example 6 with UserManager

use of org.keycloak.models.UserManager in project keycloak by keycloak.

the class ClientManager method removeClient.

public boolean removeClient(RealmModel realm, ClientModel client) {
    if (!isInternalClient(realm.getName(), client.getClientId()) && realm.removeClient(client.getId())) {
        UserSessionProvider sessions = realmManager.getSession().sessions();
        if (sessions != null) {
            sessions.onClientRemoved(realm, client);
        }
        AuthenticationSessionProvider authSessions = realmManager.getSession().authenticationSessions();
        if (authSessions != null) {
            authSessions.onClientRemoved(realm, client);
        }
        UserModel serviceAccountUser = realmManager.getSession().users().getServiceAccount(client);
        if (serviceAccountUser != null) {
            new UserManager(realmManager.getSession()).removeUser(realm, serviceAccountUser);
        }
        return true;
    } else {
        return false;
    }
}
Also used : UserModel(org.keycloak.models.UserModel) UserSessionProvider(org.keycloak.models.UserSessionProvider) UserManager(org.keycloak.models.UserManager) AuthenticationSessionProvider(org.keycloak.sessions.AuthenticationSessionProvider)

Example 7 with UserManager

use of org.keycloak.models.UserManager in project keycloak by keycloak.

the class ResetCredentialsAlternativeFlowsTest method deviceNameOptionalForFirstOTPCredentialButRequiredForEachNextOne.

// KEYCLOAK-12168 Verify the 'Device Name' label is optional for the first OTP credential created
// (either via Account page or by registering new user), but required for each next created OTP credential
@Test
// TODO remove this (KEYCLOAK-16228)
@DisableFeature(value = Profile.Feature.ACCOUNT2, skipRestart = true)
public void deviceNameOptionalForFirstOTPCredentialButRequiredForEachNextOne() {
    // Enable 'Default Action' on 'Configure OTP' RA for the 'test' realm
    RequiredActionProviderRepresentation otpRequiredAction = testRealm().flows().getRequiredAction("CONFIGURE_TOTP");
    otpRequiredAction.setDefaultAction(true);
    testRealm().flows().updateRequiredAction("CONFIGURE_TOTP", otpRequiredAction);
    try {
        // Make a copy of the default Reset Credentials flow, but:
        // * Without 'Send Reset Email' authenticator,
        // * Without 'Reset Password' authenticator
        final String newFlowAlias = "resetcred - KEYCLOAK-12168 - firstOTP - account - test";
        configureResetCredentialsRemoveExecutionsAndBindTheFlow(newFlowAlias, Arrays.asList("reset-credential-email", "reset-password"));
        /* Verify the 'Device Name' is optional when creating new OTP credential via the Account page */
        // Login & set up the initial OTP code for the user
        loginPage.open();
        loginPage.login("login@test.com", "password");
        accountTotpPage.open();
        Assert.assertTrue(accountTotpPage.isCurrent());
        String pageSource = driver.getPageSource();
        // Check the One-time code label is followed by asterisk character (since always required)
        final String oneTimeCodeLabelFollowedByAsterisk = "(?s)<label for=\"totp\"((?!</span>).)+((?=<span class=\"required\">\\*).)*";
        Assert.assertTrue(Pattern.compile(oneTimeCodeLabelFollowedByAsterisk).matcher(pageSource).find());
        // Check the Device Name label is not followed by asterisk character (since optional if no OTP credential defined yet)
        final String asteriskPrecededByDeviceNameLabel = "(?s)((?<=<label for=\"userLabel\").)+.*<span class=\"required\">\\s+\\*";
        Assert.assertFalse(Pattern.compile(asteriskPrecededByDeviceNameLabel).matcher(pageSource).find());
        // Create OTP credential with empty label
        final String emptyOtpLabel = "";
        accountTotpPage.configure(totp.generateTOTP(accountTotpPage.getTotpSecret()), emptyOtpLabel);
        // Get the updated Account TOTP page source post OTP credential creation
        pageSource = driver.getPageSource();
        // Check if OTP credential with empty label was created successfully
        assertThat(driver.findElements(By.className("provider")).stream().map(WebElement::getText).collect(Collectors.toList()), Matchers.hasItem(""));
        accountTotpPage.removeTotp();
        // Logout
        oauth.openLogout();
        /* Verify the 'Device Name' is optional when creating the first OTP credential via the login config TOTP page */
        // Register new user
        loginPage.open();
        loginPage.clickRegister();
        registerPage.assertCurrent();
        registerPage.register("Bruce", "Wilson", "bwilson@keycloak.org", "bwilson", "password", "password");
        Assert.assertTrue(totpPage.isCurrent());
        pageSource = driver.getPageSource();
        // Check the One-time code label is required
        Assert.assertTrue(Pattern.compile(oneTimeCodeLabelFollowedByAsterisk).matcher(pageSource).find());
        // Check the Device Name label is optional
        Assert.assertFalse(Pattern.compile(asteriskPrecededByDeviceNameLabel).matcher(pageSource).find());
        // Create OTP credential with empty label
        totpPage.configure(totp.generateTOTP(accountTotpPage.getTotpSecret()), emptyOtpLabel);
        Assert.assertNull(totpPage.getAlertError());
        Assert.assertNull(totpPage.getInputCodeError());
        Assert.assertNull(totpPage.getInputLabelError());
        // Assert user authenticated
        appPage.assertCurrent();
        Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
        Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
        accountTotpPage.open();
        Assert.assertTrue(accountTotpPage.isCurrent());
        // Check if OTP credential with empty label was created successfully
        assertThat(driver.findElements(By.className("provider")).stream().map(WebElement::getText).collect(Collectors.toList()), Matchers.hasItem(""));
        ;
        // Logout
        oauth.openLogout();
        /* Verify the 'Device Name' is required for each next OTP credential created via the login config TOTP page */
        // Click "Forgot password" to define another OTP credential
        loginPage.open();
        loginPage.resetPassword();
        // Should be on reset password page now. Provide email of previously registered user & click Submit button
        Assert.assertTrue(resetPasswordPage.isCurrent());
        resetPasswordPage.changePassword("bwilson@keycloak.org");
        pageSource = driver.getPageSource();
        // Check the One-time code label is required
        Assert.assertTrue(Pattern.compile(oneTimeCodeLabelFollowedByAsterisk).matcher(pageSource).find());
        // Check the Device Name label is required (since one OTP credential already defined)
        final String deviceNameLabelFollowedByAsterisk = "(?s)<label for=\"userLabel\"((?!</span>).)+((?=<span class=\"required\">\\*).)*";
        Assert.assertTrue(Pattern.compile(deviceNameLabelFollowedByAsterisk).matcher(pageSource).find());
        // Try to create another OTP credential with empty label again. This
        // should fail with error since OTP label is required in this case already
        final String deviceNameLabelRequiredErrorMessage = "Please specify device name.";
        totpPage.configure(totp.generateTOTP(accountTotpPage.getTotpSecret()), emptyOtpLabel);
        Assert.assertTrue(totpPage.getInputLabelError().equals(deviceNameLabelRequiredErrorMessage));
        // Create 2nd OTP credential with valid (non-empty) Device Name label. This should pass
        final String secondOtpLabel = "My 2nd OTP device";
        totpPage.configure(totp.generateTOTP(accountTotpPage.getTotpSecret()), secondOtpLabel);
        Assert.assertNull(totpPage.getAlertError());
        Assert.assertNull(totpPage.getInputCodeError());
        Assert.assertNull(totpPage.getInputLabelError());
        // Assert user authenticated
        appPage.assertCurrent();
        Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
        Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
        accountTotpPage.open();
        Assert.assertTrue(accountTotpPage.isCurrent());
        // Get the updated Account TOTP page source after both the OTP credentials were created
        pageSource = driver.getPageSource();
        // Verify 2nd OTP credential was successfully created too
        Assert.assertTrue(pageSource.contains(secondOtpLabel));
        // Remove both OTP credentials
        accountTotpPage.removeTotp();
        accountTotpPage.removeTotp();
        // Logout
        oauth.openLogout();
    // Undo setup changes performed within the test
    } finally {
        revertFlows();
        // Disable 'Default Action' on 'Configure OTP' RA for the 'test' realm
        otpRequiredAction.setDefaultAction(false);
        testRealm().flows().updateRequiredAction("CONFIGURE_TOTP", otpRequiredAction);
        // Remove the within test registered 'bwilson' user
        testingClient.server("test").run(session -> {
            UserManager um = new UserManager(session);
            UserModel user = session.users().getUserByUsername(session.getContext().getRealm(), "bwilson");
            if (user != null) {
                um.removeUser(session.getContext().getRealm(), user);
            }
        });
    }
}
Also used : RequiredActionProviderRepresentation(org.keycloak.representations.idm.RequiredActionProviderRepresentation) UserModel(org.keycloak.models.UserModel) UserManager(org.keycloak.models.UserManager) WebElement(org.openqa.selenium.WebElement) DisableFeature(org.keycloak.testsuite.arquillian.annotation.DisableFeature) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest) AbstractAuthenticationTest(org.keycloak.testsuite.admin.authentication.AbstractAuthenticationTest)

Example 8 with UserManager

use of org.keycloak.models.UserManager in project keycloak by keycloak.

the class ClientResource method updateClientFromRep.

private void updateClientFromRep(ClientRepresentation rep, ClientModel client, KeycloakSession session) throws ModelDuplicateException {
    UserModel serviceAccount = this.session.users().getServiceAccount(client);
    if (TRUE.equals(rep.isServiceAccountsEnabled())) {
        if (serviceAccount == null) {
            new ClientManager(new RealmManager(session)).enableServiceAccount(client);
        }
    } else {
        if (serviceAccount != null) {
            new UserManager(session).removeUser(realm, serviceAccount);
        }
    }
    if (rep.getClientId() != null && !rep.getClientId().equals(client.getClientId())) {
        new ClientManager(new RealmManager(session)).clientIdChanged(client, rep);
    }
    if (rep.isFullScopeAllowed() != null && rep.isFullScopeAllowed() != client.isFullScopeAllowed()) {
        auth.clients().requireManage(client);
    }
    if ((rep.isBearerOnly() != null && rep.isBearerOnly()) || (rep.isPublicClient() != null && rep.isPublicClient())) {
        rep.setAuthorizationServicesEnabled(false);
    }
    RepresentationToModel.updateClient(rep, client);
    RepresentationToModel.updateClientProtocolMappers(rep, client);
    updateAuthorizationSettings(rep);
}
Also used : UserModel(org.keycloak.models.UserModel) UserManager(org.keycloak.models.UserManager) ClientManager(org.keycloak.services.managers.ClientManager) RealmManager(org.keycloak.services.managers.RealmManager)

Example 9 with UserManager

use of org.keycloak.models.UserManager in project keycloak by keycloak.

the class UserSessionPersisterProviderTest method cleanEnvironment.

@Override
public void cleanEnvironment(KeycloakSession s) {
    RealmModel realm = s.realms().getRealm(realmId);
    s.sessions().removeUserSessions(realm);
    UserModel user1 = s.users().getUserByUsername(realm, "user1");
    UserModel user2 = s.users().getUserByUsername(realm, "user2");
    UserManager um = new UserManager(s);
    if (user1 != null) {
        um.removeUser(realm, user1);
    }
    if (user2 != null) {
        um.removeUser(realm, user2);
    }
    s.realms().removeRealm(realmId);
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) UserManager(org.keycloak.models.UserManager)

Example 10 with UserManager

use of org.keycloak.models.UserManager in project keycloak by keycloak.

the class UserSessionProviderModelTest method cleanEnvironment.

@Override
public void cleanEnvironment(KeycloakSession s) {
    RealmModel realm = s.realms().getRealm(realmId);
    s.sessions().removeUserSessions(realm);
    UserModel user1 = s.users().getUserByUsername(realm, "user1");
    UserModel user2 = s.users().getUserByUsername(realm, "user2");
    UserManager um = new UserManager(s);
    if (user1 != null) {
        um.removeUser(realm, user1);
    }
    if (user2 != null) {
        um.removeUser(realm, user2);
    }
    s.realms().removeRealm(realmId);
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) UserManager(org.keycloak.models.UserManager)

Aggregations

UserManager (org.keycloak.models.UserManager)26 UserModel (org.keycloak.models.UserModel)25 RealmModel (org.keycloak.models.RealmModel)20 After (org.junit.After)7 KeycloakSession (org.keycloak.models.KeycloakSession)7 Test (org.junit.Test)6 RealmManager (org.keycloak.services.managers.RealmManager)5 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)4 UserSessionModel (org.keycloak.models.UserSessionModel)3 ClientModel (org.keycloak.models.ClientModel)2 CachedUserModel (org.keycloak.models.cache.CachedUserModel)2 UserCache (org.keycloak.models.cache.UserCache)2 ClientManager (org.keycloak.services.managers.ClientManager)2 DELETE (javax.ws.rs.DELETE)1 NoCache (org.jboss.resteasy.annotations.cache.NoCache)1 EventBuilder (org.keycloak.events.EventBuilder)1 KeycloakContext (org.keycloak.models.KeycloakContext)1 ModelException (org.keycloak.models.ModelException)1