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);
}
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;
});
}
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);
}
}
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());
}
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);
});
}
}
Aggregations