Search in sources :

Example 16 with UserModel

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

the class UsersResource method getUsers.

/**
 * Get users
 *
 * Returns a stream of users, filtered according to query parameters.
 *
 * @param search A String contained in username, first or last name, or email
 * @param last A String contained in lastName, or the complete lastName, if param "exact" is true
 * @param first A String contained in firstName, or the complete firstName, if param "exact" is true
 * @param email A String contained in email, or the complete email, if param "exact" is true
 * @param username A String contained in username, or the complete username, if param "exact" is true
 * @param emailVerified whether the email has been verified
 * @param idpAlias The alias of an Identity Provider linked to the user
 * @param idpUserId The userId at an Identity Provider linked to the user
 * @param firstResult Pagination offset
 * @param maxResults Maximum results size (defaults to 100)
 * @param enabled Boolean representing if user is enabled or not
 * @param briefRepresentation Boolean which defines whether brief representations are returned (default: false)
 * @param exact Boolean which defines whether the params "last", "first", "email" and "username" must match exactly
 * @param searchQuery A query to search for custom attributes, in the format 'key1:value2 key2:value2'
 * @return a non-null {@code Stream} of users
 */
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public Stream<UserRepresentation> getUsers(@QueryParam("search") String search, @QueryParam("lastName") String last, @QueryParam("firstName") String first, @QueryParam("email") String email, @QueryParam("username") String username, @QueryParam("emailVerified") Boolean emailVerified, @QueryParam("idpAlias") String idpAlias, @QueryParam("idpUserId") String idpUserId, @QueryParam("first") Integer firstResult, @QueryParam("max") Integer maxResults, @QueryParam("enabled") Boolean enabled, @QueryParam("briefRepresentation") Boolean briefRepresentation, @QueryParam("exact") Boolean exact, @QueryParam("q") String searchQuery) {
    UserPermissionEvaluator userPermissionEvaluator = auth.users();
    userPermissionEvaluator.requireQuery();
    firstResult = firstResult != null ? firstResult : -1;
    maxResults = maxResults != null ? maxResults : Constants.DEFAULT_MAX_RESULTS;
    Map<String, String> searchAttributes = searchQuery == null ? Collections.emptyMap() : SearchQueryUtils.getFields(searchQuery);
    Stream<UserModel> userModels = Stream.empty();
    if (search != null) {
        if (search.startsWith(SEARCH_ID_PARAMETER)) {
            UserModel userModel = session.users().getUserById(realm, search.substring(SEARCH_ID_PARAMETER.length()).trim());
            if (userModel != null) {
                userModels = Stream.of(userModel);
            }
        } else {
            Map<String, String> attributes = new HashMap<>();
            attributes.put(UserModel.SEARCH, search.trim());
            if (enabled != null) {
                attributes.put(UserModel.ENABLED, enabled.toString());
            }
            return searchForUser(attributes, realm, userPermissionEvaluator, briefRepresentation, firstResult, maxResults, false);
        }
    } else if (last != null || first != null || email != null || username != null || emailVerified != null || idpAlias != null || idpUserId != null || enabled != null || exact != null || !searchAttributes.isEmpty()) {
        Map<String, String> attributes = new HashMap<>();
        if (last != null) {
            attributes.put(UserModel.LAST_NAME, last);
        }
        if (first != null) {
            attributes.put(UserModel.FIRST_NAME, first);
        }
        if (email != null) {
            attributes.put(UserModel.EMAIL, email);
        }
        if (username != null) {
            attributes.put(UserModel.USERNAME, username);
        }
        if (emailVerified != null) {
            attributes.put(UserModel.EMAIL_VERIFIED, emailVerified.toString());
        }
        if (idpAlias != null) {
            attributes.put(UserModel.IDP_ALIAS, idpAlias);
        }
        if (idpUserId != null) {
            attributes.put(UserModel.IDP_USER_ID, idpUserId);
        }
        if (enabled != null) {
            attributes.put(UserModel.ENABLED, enabled.toString());
        }
        if (exact != null) {
            attributes.put(UserModel.EXACT, exact.toString());
        }
        attributes.putAll(searchAttributes);
        return searchForUser(attributes, realm, userPermissionEvaluator, briefRepresentation, firstResult, maxResults, true);
    } else {
        return searchForUser(new HashMap<>(), realm, userPermissionEvaluator, briefRepresentation, firstResult, maxResults, false);
    }
    return toRepresentation(realm, userPermissionEvaluator, briefRepresentation, userModels);
}
Also used : UserModel(org.keycloak.models.UserModel) UserPermissionEvaluator(org.keycloak.services.resources.admin.permissions.UserPermissionEvaluator) HashMap(java.util.HashMap) Map(java.util.Map) HashMap(java.util.HashMap) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 17 with UserModel

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

the class UsersResource method toRepresentation.

private Stream<UserRepresentation> toRepresentation(RealmModel realm, UserPermissionEvaluator usersEvaluator, Boolean briefRepresentation, Stream<UserModel> userModels) {
    boolean briefRepresentationB = briefRepresentation != null && briefRepresentation;
    boolean canViewGlobal = usersEvaluator.canView();
    usersEvaluator.grantIfNoPermission(session.getAttribute(UserModel.GROUPS) != null);
    return userModels.filter(user -> canViewGlobal || usersEvaluator.canView(user)).map(user -> {
        UserRepresentation userRep = briefRepresentationB ? ModelToRepresentation.toBriefRepresentation(user) : ModelToRepresentation.toRepresentation(session, realm, user);
        userRep.setAccess(usersEvaluator.getAccess(user));
        return userRep;
    });
}
Also used : ResourceType(org.keycloak.events.admin.ResourceType) Produces(javax.ws.rs.Produces) PasswordPolicyNotMetException(org.keycloak.policy.PasswordPolicyNotMetException) Path(javax.ws.rs.Path) USER_API(org.keycloak.userprofile.UserProfileContext.USER_API) RepresentationToModel(org.keycloak.models.utils.RepresentationToModel) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) ClientConnection(org.keycloak.common.ClientConnection) RealmModel(org.keycloak.models.RealmModel) Context(javax.ws.rs.core.Context) Set(java.util.Set) Collectors(java.util.stream.Collectors) NotFoundException(javax.ws.rs.NotFoundException) KeycloakModelUtils.findGroupByPath(org.keycloak.models.utils.KeycloakModelUtils.findGroupByPath) Objects(java.util.Objects) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) ForbiddenException(org.keycloak.services.ForbiddenException) Optional(java.util.Optional) SearchQueryUtils(org.keycloak.utils.SearchQueryUtils) OperationType(org.keycloak.events.admin.OperationType) UserProfile(org.keycloak.userprofile.UserProfile) PathParam(javax.ws.rs.PathParam) UserPermissionEvaluator(org.keycloak.services.resources.admin.permissions.UserPermissionEvaluator) Profile(org.keycloak.common.Profile) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) GET(javax.ws.rs.GET) Logger(org.jboss.logging.Logger) Constants(org.keycloak.models.Constants) HashMap(java.util.HashMap) ObjectUtil(org.keycloak.common.util.ObjectUtil) ResteasyProviderFactory(org.jboss.resteasy.spi.ResteasyProviderFactory) UserModel(org.keycloak.models.UserModel) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) GroupModel(org.keycloak.models.GroupModel) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) POST(javax.ws.rs.POST) AdminPermissionEvaluator(org.keycloak.services.resources.admin.permissions.AdminPermissionEvaluator) KeycloakSession(org.keycloak.models.KeycloakSession) NoCache(org.jboss.resteasy.annotations.cache.NoCache) ModelException(org.keycloak.models.ModelException) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) Collections(java.util.Collections) ErrorResponse(org.keycloak.services.ErrorResponse) UserRepresentation(org.keycloak.representations.idm.UserRepresentation)

Example 18 with UserModel

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

the class UsersResource method createUser.

/**
 * Create a new user
 *
 * Username must be unique.
 *
 * @param rep
 * @return
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createUser(final UserRepresentation rep) {
    // first check if user has manage rights
    try {
        auth.users().requireManage();
    } catch (ForbiddenException exception) {
        if (!canCreateGroupMembers(rep)) {
            throw exception;
        }
    }
    String username = rep.getUsername();
    if (realm.isRegistrationEmailAsUsername()) {
        username = rep.getEmail();
    }
    if (ObjectUtil.isBlank(username)) {
        return ErrorResponse.error("User name is missing", Response.Status.BAD_REQUEST);
    }
    // Double-check duplicated username and email here due to federation
    if (session.users().getUserByUsername(realm, username) != null) {
        return ErrorResponse.exists("User exists with same username");
    }
    if (rep.getEmail() != null && !realm.isDuplicateEmailsAllowed()) {
        try {
            if (session.users().getUserByEmail(realm, rep.getEmail()) != null) {
                return ErrorResponse.exists("User exists with same email");
            }
        } catch (ModelDuplicateException e) {
            return ErrorResponse.exists("User exists with same email");
        }
    }
    UserProfileProvider profileProvider = session.getProvider(UserProfileProvider.class);
    UserProfile profile = profileProvider.create(USER_API, rep.toAttributes());
    try {
        Response response = UserResource.validateUserProfile(profile, null, session);
        if (response != null) {
            return response;
        }
        UserModel user = profile.create();
        UserResource.updateUserFromRep(profile, user, rep, session, false);
        RepresentationToModel.createFederatedIdentities(rep, session, realm, user);
        RepresentationToModel.createGroups(rep, realm, user);
        RepresentationToModel.createCredentials(rep, session, realm, user, true);
        adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), user.getId()).representation(rep).success();
        if (session.getTransactionManager().isActive()) {
            session.getTransactionManager().commit();
        }
        return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(user.getId()).build()).build();
    } catch (ModelDuplicateException e) {
        if (session.getTransactionManager().isActive()) {
            session.getTransactionManager().setRollbackOnly();
        }
        return ErrorResponse.exists("User exists with same username or email");
    } catch (PasswordPolicyNotMetException e) {
        if (session.getTransactionManager().isActive()) {
            session.getTransactionManager().setRollbackOnly();
        }
        return ErrorResponse.error("Password policy not met", Response.Status.BAD_REQUEST);
    } catch (ModelException me) {
        if (session.getTransactionManager().isActive()) {
            session.getTransactionManager().setRollbackOnly();
        }
        logger.warn("Could not create user", me);
        return ErrorResponse.error("Could not create user", Response.Status.BAD_REQUEST);
    }
}
Also used : Response(javax.ws.rs.core.Response) ErrorResponse(org.keycloak.services.ErrorResponse) UserModel(org.keycloak.models.UserModel) ForbiddenException(org.keycloak.services.ForbiddenException) UserProfile(org.keycloak.userprofile.UserProfile) ModelException(org.keycloak.models.ModelException) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) PasswordPolicyNotMetException(org.keycloak.policy.PasswordPolicyNotMetException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 19 with UserModel

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

the class DefaultClientSessionContext method loadRoles.

private Set<RoleModel> loadRoles() {
    UserModel user = clientSession.getUserSession().getUser();
    ClientModel client = clientSession.getClient();
    return TokenManager.getAccess(user, client, getClientScopesStream());
}
Also used : UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel)

Example 20 with UserModel

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

the class RefreshTokenTest method refreshTokenAfterUserAdminLogoutEndpointAndLoginAgain.

@Test
@AuthServerContainerExclude(AuthServerContainerExclude.AuthServer.REMOTE)
public void refreshTokenAfterUserAdminLogoutEndpointAndLoginAgain() {
    try {
        String refreshToken1 = loginAndForceNewLoginPage();
        RefreshToken refreshTokenParsed1 = oauth.parseRefreshToken(refreshToken1);
        String userId = refreshTokenParsed1.getSubject();
        UserResource user = adminClient.realm("test").users().get(userId);
        user.logout();
        // Set time offset to 2 (Just to simulate to be more close to real situation)
        setTimeOffset(2);
        // Continue with login
        WaitUtils.waitForPageToLoad();
        loginPage.login("password");
        assertFalse(loginPage.isCurrent());
        OAuthClient.AccessTokenResponse tokenResponse2 = null;
        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
        tokenResponse2 = oauth.doAccessTokenRequest(code, "password");
        setTimeOffset(4);
        // Now try refresh with the original refreshToken1 created in logged-out userSession. It should fail
        OAuthClient.AccessTokenResponse responseReuseExceeded = oauth.doRefreshTokenRequest(refreshToken1, "password");
        assertEquals(400, responseReuseExceeded.getStatusCode());
        setTimeOffset(6);
        // Finally try with valid refresh token
        responseReuseExceeded = oauth.doRefreshTokenRequest(tokenResponse2.getRefreshToken(), "password");
        assertEquals(200, responseReuseExceeded.getStatusCode());
    } finally {
        // Need to reset not-before of user, which was updated during user.logout()
        testingClient.server().run(session -> {
            RealmModel realm = session.realms().getRealmByName("test");
            UserModel user = session.users().getUserByUsername(realm, "test-user@localhost");
            session.users().setNotBeforeForUser(realm, user, 0);
        });
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) RefreshToken(org.keycloak.representations.RefreshToken) OAuthClient(org.keycloak.testsuite.util.OAuthClient) UserResource(org.keycloak.admin.client.resource.UserResource) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Aggregations

UserModel (org.keycloak.models.UserModel)383 RealmModel (org.keycloak.models.RealmModel)220 Test (org.junit.Test)126 ClientModel (org.keycloak.models.ClientModel)86 KeycloakSession (org.keycloak.models.KeycloakSession)81 CachedUserModel (org.keycloak.models.cache.CachedUserModel)52 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)43 List (java.util.List)41 UserSessionModel (org.keycloak.models.UserSessionModel)40 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)40 RoleModel (org.keycloak.models.RoleModel)39 ComponentModel (org.keycloak.component.ComponentModel)31 HashMap (java.util.HashMap)30 Response (javax.ws.rs.core.Response)29 Path (javax.ws.rs.Path)28 UserManager (org.keycloak.models.UserManager)28 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)27 Map (java.util.Map)25 GroupModel (org.keycloak.models.GroupModel)24 AbstractAuthTest (org.keycloak.testsuite.AbstractAuthTest)24