use of org.keycloak.models.GroupModel in project keycloak by keycloak.
the class GroupLDAPStorageMapper method syncNonExistingGroup.
private void syncNonExistingGroup(RealmModel realm, Map.Entry<String, LDAPObject> groupEntry, SynchronizationResult syncResult, Set<String> visitedGroupIds, String groupName) {
try {
// Create each non-existing group to be synced in its own inner transaction to prevent race condition when
// the group intended to be created was already created via other channel in the meantime
KeycloakModelUtils.runJobInTransaction(ldapProvider.getSession().getKeycloakSessionFactory(), session -> {
RealmModel innerTransactionRealm = session.realms().getRealm(realm.getId());
GroupModel kcGroup = createKcGroup(innerTransactionRealm, groupName, null);
updateAttributesOfKCGroup(kcGroup, groupEntry.getValue());
syncResult.increaseAdded();
visitedGroupIds.add(kcGroup.getId());
});
} catch (ModelException me) {
logger.error(String.format("Failed to sync group %s from LDAP: ", groupName), me);
syncResult.increaseFailed();
}
}
use of org.keycloak.models.GroupModel in project keycloak by keycloak.
the class DefaultEvaluation method createRealm.
private Realm createRealm() {
return new Realm() {
@Override
public boolean isUserInGroup(String id, String groupId, boolean checkParent) {
KeycloakSession session = authorizationProvider.getKeycloakSession();
UserModel user = getUser(id, session);
if (Objects.isNull(user)) {
return false;
}
RealmModel realm = session.getContext().getRealm();
GroupModel group = KeycloakModelUtils.findGroupByPath(realm, groupId);
if (Objects.isNull(group)) {
return false;
}
if (checkParent) {
return RoleUtils.isMember(user.getGroupsStream(), group);
}
return user.isMemberOf(group);
}
private UserModel getUser(String id, KeycloakSession session) {
RealmModel realm = session.getContext().getRealm();
UserModel user = session.users().getUserById(realm, id);
if (Objects.isNull(user)) {
user = session.users().getUserByUsername(realm, id);
}
if (Objects.isNull(user)) {
user = session.users().getUserByEmail(realm, id);
}
if (Objects.isNull(user)) {
user = session.users().getServiceAccount(realm.getClientById(id));
}
return user;
}
@Override
public boolean isUserInRealmRole(String id, String roleName) {
KeycloakSession session = authorizationProvider.getKeycloakSession();
UserModel user = getUser(id, session);
if (Objects.isNull(user)) {
return false;
}
Stream<RoleModel> roleMappings = user.getRoleMappingsStream().filter(isNotClientRole);
return RoleUtils.hasRole(roleMappings, session.getContext().getRealm().getRole(roleName));
}
@Override
public boolean isUserInClientRole(String id, String clientId, String roleName) {
KeycloakSession session = authorizationProvider.getKeycloakSession();
RealmModel realm = session.getContext().getRealm();
UserModel user = getUser(id, session);
if (Objects.isNull(user)) {
return false;
}
Set<RoleModel> roleMappings = user.getRoleMappingsStream().filter(RoleModel::isClientRole).filter(role -> Objects.equals(((ClientModel) role.getContainer()).getClientId(), clientId)).collect(Collectors.toSet());
if (roleMappings.isEmpty()) {
return false;
}
RoleModel role = realm.getClientById(roleMappings.iterator().next().getContainer().getId()).getRole(roleName);
if (Objects.isNull(role)) {
return false;
}
return RoleUtils.hasRole(roleMappings, role);
}
@Override
public boolean isGroupInRole(String id, String role) {
KeycloakSession session = authorizationProvider.getKeycloakSession();
RealmModel realm = session.getContext().getRealm();
GroupModel group = KeycloakModelUtils.findGroupByPath(realm, id);
return RoleUtils.hasRoleFromGroup(group, realm.getRole(role), false);
}
@Override
public List<String> getUserRealmRoles(String id) {
return getUser(id, authorizationProvider.getKeycloakSession()).getRoleMappingsStream().filter(isNotClientRole).map(RoleModel::getName).collect(Collectors.toList());
}
@Override
public List<String> getUserClientRoles(String id, String clientId) {
return getUser(id, authorizationProvider.getKeycloakSession()).getRoleMappingsStream().filter(RoleModel::isClientRole).map(RoleModel::getName).collect(Collectors.toList());
}
@Override
public List<String> getUserGroups(String id) {
return getUser(id, authorizationProvider.getKeycloakSession()).getGroupsStream().map(ModelToRepresentation::buildGroupPath).collect(Collectors.toList());
}
@Override
public Map<String, List<String>> getUserAttributes(String id) {
return Collections.unmodifiableMap(getUser(id, authorizationProvider.getKeycloakSession()).getAttributes());
}
};
}
use of org.keycloak.models.GroupModel in project keycloak by keycloak.
the class UserResource method removeMembership.
@DELETE
@Path("groups/{groupId}")
@NoCache
public void removeMembership(@PathParam("groupId") String groupId) {
auth.users().requireManageGroupMembership(user);
GroupModel group = session.groups().getGroupById(realm, groupId);
if (group == null) {
throw new NotFoundException("Group not found");
}
auth.groups().requireManageMembership(group);
try {
if (user.isMemberOf(group)) {
user.leaveGroup(group);
adminEvent.operation(OperationType.DELETE).resource(ResourceType.GROUP_MEMBERSHIP).representation(ModelToRepresentation.toRepresentation(group, true)).resourcePath(session.getContext().getUri()).success();
}
} catch (ModelException me) {
Properties messages = AdminRoot.getMessages(session, realm, auth.adminAuth().getToken().getLocale());
throw new ErrorResponseException(me.getMessage(), MessageFormat.format(messages.getProperty(me.getMessage(), me.getMessage()), me.getParameters()), Status.BAD_REQUEST);
}
}
use of org.keycloak.models.GroupModel in project keycloak by keycloak.
the class GroupsResource method addTopLevelGroup.
/**
* create or add a top level realm groupSet or create child. This will update the group and set the parent if it exists. Create it and set the parent
* if the group doesn't exist.
*
* @param rep
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response addTopLevelGroup(GroupRepresentation rep) {
auth.groups().requireManage();
GroupModel child;
Response.ResponseBuilder builder = Response.status(204);
String groupName = rep.getName();
if (ObjectUtil.isBlank(groupName)) {
return ErrorResponse.error("Group name is missing", Response.Status.BAD_REQUEST);
}
try {
if (rep.getId() != null) {
child = realm.getGroupById(rep.getId());
if (child == null) {
throw new NotFoundException("Could not find child by id");
}
realm.moveGroup(child, null);
adminEvent.operation(OperationType.UPDATE).resourcePath(session.getContext().getUri());
} else {
child = realm.createGroup(groupName);
GroupResource.updateGroup(rep, child);
URI uri = session.getContext().getUri().getAbsolutePathBuilder().path(child.getId()).build();
builder.status(201).location(uri);
rep.setId(child.getId());
adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), child.getId());
}
} catch (ModelDuplicateException mde) {
return ErrorResponse.exists("Top level group named '" + groupName + "' already exists.");
}
adminEvent.representation(rep).success();
return builder.build();
}
use of org.keycloak.models.GroupModel in project keycloak by keycloak.
the class GroupsResource method getGroupById.
/**
* Does not expand hierarchy. Subgroups will not be set.
*
* @param id
* @return
*/
@Path("{id}")
public GroupResource getGroupById(@PathParam("id") String id) {
GroupModel group = realm.getGroupById(id);
if (group == null) {
throw new NotFoundException("Could not find group by id");
}
GroupResource resource = new GroupResource(realm, group, session, this.auth, adminEvent);
ResteasyProviderFactory.getInstance().injectProperties(resource);
return resource;
}
Aggregations