KEYCLOAK-2056: Removal of file model provider

This commit is contained in:
Bruno Oliveira 2015-11-13 09:38:09 -02:00
parent 8caaabb2e5
commit 4b0e33e388
23 changed files with 7 additions and 4422 deletions

View file

@ -36,10 +36,6 @@
<groupId>org.keycloak</groupId>
<artifactId>keycloak-model-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-model-file</artifactId>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-model-sessions-infinispan</artifactId>

View file

@ -1,18 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.3" name="org.keycloak.keycloak-model-file">
<resources>
<artifact name="${org.keycloak:keycloak-model-file}"/>
</resources>
<dependencies>
<module name="org.keycloak.keycloak-common"/>
<module name="org.keycloak.keycloak-core"/>
<module name="org.keycloak.keycloak-model-api"/>
<module name="org.keycloak.keycloak-connections-file"/>
<module name="org.jboss.logging"/>
<module name="javax.api"/>
</dependencies>
</module>

View file

@ -33,7 +33,6 @@
<module name="org.keycloak.keycloak-model-api" services="import"/>
<module name="org.keycloak.keycloak-model-jpa" services="import"/>
<module name="org.keycloak.keycloak-model-mongo" services="import"/>
<module name="org.keycloak.keycloak-model-file" services="import"/>
<module name="org.keycloak.keycloak-model-sessions-infinispan" services="import"/>
<module name="org.keycloak.keycloak-saml-protocol" services="import"/>
<module name="org.keycloak.keycloak-services" export="true" services="import"/>
@ -70,4 +69,4 @@
<subsystem name="weld"/>
</exclude-subsystems>
</deployment>
</jboss-deployment-structure>
</jboss-deployment-structure>

View file

@ -43,7 +43,6 @@
<module name="org.keycloak.keycloak-model-api" services="import"/>
<module name="org.keycloak.keycloak-model-jpa" services="import"/>
<module name="org.keycloak.keycloak-model-mongo" services="import"/>
<module name="org.keycloak.keycloak-model-file" services="import"/>
<module name="org.keycloak.keycloak-model-sessions-infinispan" services="import"/>
<module name="org.keycloak.keycloak-saml-core" services="import"/>
<module name="org.keycloak.keycloak-saml-protocol" services="import"/>

View file

@ -224,11 +224,11 @@
<module-def name="org.keycloak.keycloak-social-facebook">
<maven-resource group="org.keycloak" artifact="keycloak-social-facebook"/>
</module-def>
<module-def name="org.keycloak.keycloak-social-linkedin">
<maven-resource group="org.keycloak" artifact="keycloak-social-linkedin"/>
</module-def>
<module-def name="org.keycloak.keycloak-social-stackoverflow">
<maven-resource group="org.keycloak" artifact="keycloak-social-stackoverflow"/>
</module-def>
@ -250,12 +250,6 @@
<maven-resource group="org.keycloak" artifact="keycloak-saml-protocol"/>
</module-def>
<!-- file -->
<module-def name="org.keycloak.keycloak-model-file">
<maven-resource group="org.keycloak" artifact="keycloak-model-file"/>
</module-def>
<!-- mongo -->
<module-def name="org.keycloak.keycloak-connections-mongo">

View file

@ -33,7 +33,6 @@
<module name="org.keycloak.keycloak-model-api" services="import"/>
<module name="org.keycloak.keycloak-model-jpa" services="import"/>
<module name="org.keycloak.keycloak-model-mongo" services="import"/>
<module name="org.keycloak.keycloak-model-file" services="import"/>
<module name="org.keycloak.keycloak-model-sessions-infinispan" services="import"/>
<module name="org.keycloak.keycloak-saml-protocol" services="import"/>
<module name="org.keycloak.keycloak-services" export="true" services="import"/>
@ -70,4 +69,4 @@
<subsystem name="weld"/>
</exclude-subsystems>
</deployment>
</jboss-deployment-structure>
</jboss-deployment-structure>

View file

@ -1,16 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="org.keycloak.keycloak-model-file">
<resources>
<!-- Insert resources here -->
</resources>
<dependencies>
<module name="org.keycloak.keycloak-common"/>
<module name="org.keycloak.keycloak-core"/>
<module name="org.keycloak.keycloak-model-api"/>
<module name="org.keycloak.keycloak-connections-file"/>
<module name="org.jboss.logging"/>
<module name="javax.api"/>
</dependencies>
</module>

View file

@ -43,7 +43,6 @@
<module name="org.keycloak.keycloak-model-api" services="import"/>
<module name="org.keycloak.keycloak-model-jpa" services="import"/>
<module name="org.keycloak.keycloak-model-mongo" services="import"/>
<module name="org.keycloak.keycloak-model-file" services="import"/>
<module name="org.keycloak.keycloak-model-sessions-infinispan" services="import"/>
<module name="org.keycloak.keycloak-saml-core" services="import"/>

View file

@ -1,62 +0,0 @@
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>keycloak-parent</artifactId>
<groupId>org.keycloak</groupId>
<version>1.7.0.Final-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>keycloak-model-file</artifactId>
<name>Keycloak Model File</name>
<description/>
<dependencies>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-export-import-api</artifactId>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-export-import-single-file</artifactId>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-model-api</artifactId>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-connections-file</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View file

@ -1,119 +0,0 @@
/*
* Copyright 2015 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.keycloak.models.file;
import org.keycloak.connections.file.FileConnectionProvider;
import org.keycloak.connections.file.InMemoryModel;
import org.keycloak.migration.MigrationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.GroupModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ModelDuplicateException;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RealmProvider;
import org.keycloak.models.RoleModel;
import org.keycloak.models.entities.RealmEntity;
import org.keycloak.models.file.adapter.MigrationModelAdapter;
import org.keycloak.models.file.adapter.RealmAdapter;
import org.keycloak.models.utils.KeycloakModelUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Realm Provider for JSON persistence.
*
* @author Stan Silvert ssilvert@redhat.com (C) 2015 Red Hat Inc.
*/
public class FileRealmProvider implements RealmProvider {
private final KeycloakSession session;
private FileConnectionProvider fcProvider;
private final InMemoryModel inMemoryModel;
public FileRealmProvider(KeycloakSession session, FileConnectionProvider fcProvider) {
this.session = session;
this.fcProvider = fcProvider;
session.enlistForClose(this);
this.inMemoryModel = fcProvider.getModel();
}
@Override
public void close() {
fcProvider.sessionClosed(session);
}
@Override
public MigrationModel getMigrationModel() {
return new MigrationModelAdapter(inMemoryModel);
}
@Override
public RealmModel createRealm(String name) {
return createRealm(KeycloakModelUtils.generateId(), name);
}
@Override
public RealmModel createRealm(String id, String name) {
if (getRealmByName(name) != null) throw new ModelDuplicateException("Realm " + name + " already exists.");
RealmEntity realmEntity = new RealmEntity();
realmEntity.setName(name);
realmEntity.setId(id);
RealmAdapter realm = new RealmAdapter(session, realmEntity, inMemoryModel);
inMemoryModel.putRealm(id, realm);
return realm;
}
@Override
public GroupModel getGroupById(String id, RealmModel realm) {
return null;
}
@Override
public RealmModel getRealm(String id) {
RealmModel model = inMemoryModel.getRealm(id);
return model;
}
@Override
public List<RealmModel> getRealms() {
return new ArrayList(inMemoryModel.getRealms());
}
@Override
public RealmModel getRealmByName(String name) {
RealmModel model = inMemoryModel.getRealmByName(name);
return model;
}
@Override
public boolean removeRealm(String id) {
return inMemoryModel.removeRealm(id);
}
@Override
public RoleModel getRoleById(String id, RealmModel realm) {
return realm.getRoleById(id);
}
@Override
public ClientModel getClientById(String id, RealmModel realm) {
return realm.getClientById(id);
}
}

View file

@ -1,58 +0,0 @@
/*
* Copyright 2015 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.keycloak.models.file;
import org.keycloak.Config;
import org.keycloak.connections.file.FileConnectionProvider;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.RealmProvider;
import org.keycloak.models.RealmProviderFactory;
/**
* RealmProviderFactory for JSON persistence.
*
* @author Stan Silvert ssilvert@redhat.com (C) 2015 Red Hat Inc.
*/
public class FileRealmProviderFactory implements RealmProviderFactory {
@Override
public void init(Config.Scope config) {
}
@Override
public String getId() {
return "file";
}
@Override
public RealmProvider create(KeycloakSession session) {
FileConnectionProvider fcProvider = session.getProvider(FileConnectionProvider.class);
return new FileRealmProvider(session, fcProvider);
}
@Override
public void close() {
}
@Override
public void postInit(KeycloakSessionFactory factory) {
}
}

View file

@ -1,520 +0,0 @@
/*
* Copyright 2015 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.keycloak.models.file;
import org.keycloak.connections.file.FileConnectionProvider;
import org.keycloak.connections.file.InMemoryModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.CredentialValidationOutput;
import org.keycloak.models.FederatedIdentityModel;
import org.keycloak.models.GroupModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ModelDuplicateException;
import org.keycloak.models.ModelException;
import org.keycloak.models.session.PersistentClientSessionModel;
import org.keycloak.models.session.PersistentUserSessionModel;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RequiredActionProviderModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserFederationProviderModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserProvider;
import org.keycloak.models.entities.FederatedIdentityEntity;
import org.keycloak.models.entities.PersistentClientSessionEntity;
import org.keycloak.models.entities.PersistentUserSessionEntity;
import org.keycloak.models.entities.UserEntity;
import org.keycloak.models.file.adapter.UserAdapter;
import org.keycloak.models.utils.CredentialValidation;
import org.keycloak.models.utils.KeycloakModelUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/**
* UserProvider for JSON persistence.
*
* @author Stan Silvert ssilvert@redhat.com (C) 2015 Red Hat Inc.
*/
public class FileUserProvider implements UserProvider {
private final KeycloakSession session;
private FileConnectionProvider fcProvider;
private final InMemoryModel inMemoryModel;
public FileUserProvider(KeycloakSession session, FileConnectionProvider fcProvider) {
this.session = session;
this.fcProvider = fcProvider;
session.enlistForClose(this);
this.inMemoryModel = fcProvider.getModel();
}
@Override
public void close() {
fcProvider.sessionClosed(session);
}
@Override
public UserModel getUserById(String userId, RealmModel realm) {
return inMemoryModel.getUser(realm.getId(), userId);
}
@Override
public List<UserModel> getGroupMembers(RealmModel realm, GroupModel group, int firstResult, int maxResults) {
return null;
}
@Override
public List<UserModel> getGroupMembers(RealmModel realm, GroupModel group) {
return null;
}
@Override
public void preRemove(RealmModel realm, GroupModel group) {
}
@Override
public UserModel getUserByUsername(String username, RealmModel realm) {
for (UserModel user : inMemoryModel.getUsers(realm.getId())) {
if (user.getUsername() == null) continue;
if (user.getUsername().equals(username.toLowerCase())) return user;
}
return null;
}
@Override
public UserModel getUserByEmail(String email, RealmModel realm) {
for (UserModel user : inMemoryModel.getUsers(realm.getId())) {
if (user.getEmail() == null) continue;
if (user.getEmail().equals(email.toLowerCase())) return user;
}
return null;
}
@Override
public UserModel getUserByFederatedIdentity(FederatedIdentityModel socialLink, RealmModel realm) {
for (UserModel user : inMemoryModel.getUsers(realm.getId())) {
Set<FederatedIdentityModel> identities = this.getFederatedIdentities(user, realm);
for (FederatedIdentityModel idModel : identities) {
if (idModel.getUserId().equals(socialLink.getUserId())) return user;
}
}
return null;
}
@Override
public UserModel getUserByServiceAccountClient(ClientModel client) {
for (UserModel user : inMemoryModel.getUsers(client.getRealm().getId())) {
if (client.getId().equals(user.getServiceAccountClientLink())) {
return user;
}
}
return null;
}
@Override
public List<UserModel> getUsers(RealmModel realm, boolean includeServiceAccounts) {
return getUsers(realm, -1, -1, includeServiceAccounts);
}
@Override
public int getUsersCount(RealmModel realm) {
return inMemoryModel.getUsers(realm.getId()).size();
}
@Override
public List<UserModel> getUsers(RealmModel realm, int firstResult, int maxResults, boolean includeServiceAccounts) {
List<UserModel> users = new ArrayList<>(inMemoryModel.getUsers(realm.getId()));
if (!includeServiceAccounts) {
users = filterServiceAccountUsers(users);
}
List<UserModel> sortedList = sortedSubList(users, firstResult, maxResults);
return sortedList;
}
private List<UserModel> filterServiceAccountUsers(List<UserModel> users) {
List<UserModel> result = new ArrayList<>();
for (UserModel user : users) {
if (user.getServiceAccountClientLink() == null) {
result.add(user);
}
}
return result;
}
protected List<UserModel> sortedSubList(List list, int firstResult, int maxResults) {
if (list.isEmpty()) return list;
Collections.sort(list);
int first = (firstResult <= 0) ? 0 : firstResult;
int last = first + maxResults; // could be int overflow
if ((maxResults > list.size() - first) || (last > list.size())) { // int overflow or regular overflow
last = list.size();
}
if (maxResults <= 0) {
last = list.size();
}
return list.subList(first, last);
}
@Override
public List<UserModel> searchForUser(String search, RealmModel realm) {
return searchForUser(search, realm, -1, -1);
}
@Override
public List<UserModel> searchForUser(String search, RealmModel realm, int firstResult, int maxResults) {
search = search.trim();
Pattern caseInsensitivePattern = Pattern.compile("(?i:.*" + search + ".*)", Pattern.CASE_INSENSITIVE);
int spaceInd = search.lastIndexOf(" ");
boolean isFirstAndLastSearch = spaceInd != -1;
Pattern firstNamePattern = null;
Pattern lastNamePattern = null;
if (isFirstAndLastSearch) {
String firstNamePatternString = search.substring(0, spaceInd);
String lastNamePatternString = search.substring(spaceInd + 1);
firstNamePattern = Pattern.compile("(?i:.*" + firstNamePatternString + ".*$)", Pattern.CASE_INSENSITIVE);
lastNamePattern = Pattern.compile("(?i:^.*" + lastNamePatternString + ".*)", Pattern.CASE_INSENSITIVE);
}
List<UserModel> found = new ArrayList<UserModel>();
for (UserModel user : inMemoryModel.getUsers(realm.getId())) {
String firstName = user.getFirstName();
String lastName = user.getLastName();
// Case when we have search string like "ohn Bow". Then firstName must end with "ohn" AND lastName must start with "bow" (everything case-insensitive)
if (isFirstAndLastSearch) {
if (isAMatch(firstNamePattern, firstName) &&
isAMatch(lastNamePattern, lastName)) {
found.add(user);
continue;
}
}
if (isAMatch(caseInsensitivePattern, firstName) ||
isAMatch(caseInsensitivePattern, lastName) ||
isAMatch(caseInsensitivePattern, user.getUsername()) ||
isAMatch(caseInsensitivePattern, user.getEmail())) {
found.add(user);
}
}
// Remove users with service account link
found = filterServiceAccountUsers(found);
return sortedSubList(found, firstResult, maxResults);
}
@Override
public List<UserModel> searchForUserByAttributes(Map<String, String> attributes, RealmModel realm) {
return searchForUserByAttributes(attributes, realm, -1, -1);
}
protected boolean isAMatch(Pattern pattern, String value) {
return (value != null) && (pattern != null) && pattern.matcher(value).matches();
}
@Override
public List<UserModel> searchForUserByAttributes(Map<String, String> attributes, RealmModel realm, int firstResult, int maxResults) {
Pattern usernamePattern = null;
Pattern firstNamePattern = null;
Pattern lastNamePattern = null;
Pattern emailPattern = null;
for (Map.Entry<String, String> entry : attributes.entrySet()) {
if (entry.getKey().equalsIgnoreCase(UserModel.USERNAME)) {
usernamePattern = Pattern.compile(".*" + entry.getValue() + ".*", Pattern.CASE_INSENSITIVE);
} else if (entry.getKey().equalsIgnoreCase(UserModel.FIRST_NAME)) {
firstNamePattern = Pattern.compile(".*" + entry.getValue() + ".*", Pattern.CASE_INSENSITIVE);
} else if (entry.getKey().equalsIgnoreCase(UserModel.LAST_NAME)) {
lastNamePattern = Pattern.compile(".*" + entry.getValue() + ".*", Pattern.CASE_INSENSITIVE);
} else if (entry.getKey().equalsIgnoreCase(UserModel.EMAIL)) {
emailPattern = Pattern.compile(".*" + entry.getValue() + ".*", Pattern.CASE_INSENSITIVE);
}
}
List<UserModel> found = new ArrayList<UserModel>();
for (UserModel user : inMemoryModel.getUsers(realm.getId())) {
if (isAMatch(usernamePattern, user.getUsername()) ||
isAMatch(firstNamePattern, user.getFirstName()) ||
isAMatch(lastNamePattern, user.getLastName()) ||
isAMatch(emailPattern, user.getEmail())) {
found.add(user);
}
}
return sortedSubList(found, firstResult, maxResults);
}
@Override
public List<UserModel> searchForUserByUserAttribute(String attrName, String attrValue, RealmModel realm) {
Collection<UserModel> users = inMemoryModel.getUsers(realm.getId());
List<UserModel> matchedUsers = new ArrayList<>();
for (UserModel user : users) {
List<String> vals = user.getAttribute(attrName);
if (vals.contains(attrValue)) {
matchedUsers.add(user);
}
}
return matchedUsers;
}
@Override
public Set<FederatedIdentityModel> getFederatedIdentities(UserModel userModel, RealmModel realm) {
UserEntity userEntity = ((UserAdapter)getUserById(userModel.getId(), realm)).getUserEntity();
List<FederatedIdentityEntity> linkEntities = userEntity.getFederatedIdentities();
if (linkEntities == null) {
return Collections.EMPTY_SET;
}
Set<FederatedIdentityModel> result = new HashSet<FederatedIdentityModel>();
for (FederatedIdentityEntity federatedIdentityEntity : linkEntities) {
FederatedIdentityModel model = new FederatedIdentityModel(federatedIdentityEntity.getIdentityProvider(),
federatedIdentityEntity.getUserId(), federatedIdentityEntity.getUserName());
result.add(model);
}
return result;
}
private FederatedIdentityEntity findSocialLink(UserModel userModel, String socialProvider, RealmModel realm) {
UserModel user = getUserById(userModel.getId(), realm);
UserEntity userEntity = ((UserAdapter)getUserById(userModel.getId(), realm)).getUserEntity();
List<FederatedIdentityEntity> linkEntities = userEntity.getFederatedIdentities();
if (linkEntities == null) {
return null;
}
for (FederatedIdentityEntity federatedIdentityEntity : linkEntities) {
if (federatedIdentityEntity.getIdentityProvider().equals(socialProvider)) {
return federatedIdentityEntity;
}
}
return null;
}
@Override
public FederatedIdentityModel getFederatedIdentity(UserModel user, String socialProvider, RealmModel realm) {
FederatedIdentityEntity federatedIdentityEntity = findSocialLink(user, socialProvider, realm);
return federatedIdentityEntity != null ? new FederatedIdentityModel(federatedIdentityEntity.getIdentityProvider(), federatedIdentityEntity.getUserId(), federatedIdentityEntity.getUserName()) : null;
}
@Override
public UserAdapter addUser(RealmModel realm, String id, String username, boolean addDefaultRoles, boolean addDefaultRequiredActions) {
if (inMemoryModel.hasUserWithUsername(realm.getId(), username.toLowerCase()))
throw new ModelDuplicateException("User with username " + username + " already exists in realm.");
UserAdapter userModel = addUserEntity(realm, id, username.toLowerCase());
if (addDefaultRoles) {
for (String r : realm.getDefaultRoles()) {
userModel.grantRole(realm.getRole(r));
}
for (ClientModel application : realm.getClients()) {
for (String r : application.getDefaultRoles()) {
userModel.grantRole(application.getRole(r));
}
}
}
if (addDefaultRequiredActions) {
for (RequiredActionProviderModel r : realm.getRequiredActionProviders()) {
if (r.isEnabled() && r.isDefaultAction()) {
userModel.addRequiredAction(r.getAlias());
}
}
}
return userModel;
}
protected UserAdapter addUserEntity(RealmModel realm, String userId, String username) {
if (realm == null) throw new NullPointerException("realm == null");
if (username == null) throw new NullPointerException("username == null");
if (userId == null) userId = KeycloakModelUtils.generateId();
UserEntity userEntity = new UserEntity();
userEntity.setId(userId);
userEntity.setCreatedTimestamp(System.currentTimeMillis());
userEntity.setUsername(username);
// Compatibility with JPA model, which has user disabled by default
// userEntity.setEnabled(true);
userEntity.setRealmId(realm.getId());
UserAdapter user = new UserAdapter(realm, userEntity, inMemoryModel);
inMemoryModel.putUser(realm.getId(), userId, user);
return user;
}
@Override
public boolean removeUser(RealmModel realm, UserModel user) {
return inMemoryModel.removeUser(realm.getId(), user.getId());
}
@Override
public void addFederatedIdentity(RealmModel realm, UserModel user, FederatedIdentityModel socialLink) {
UserAdapter userAdapter = (UserAdapter)getUserById(user.getId(), realm);
UserEntity userEntity = userAdapter.getUserEntity();
FederatedIdentityEntity federatedIdentityEntity = new FederatedIdentityEntity();
federatedIdentityEntity.setIdentityProvider(socialLink.getIdentityProvider());
federatedIdentityEntity.setUserId(socialLink.getUserId());
federatedIdentityEntity.setUserName(socialLink.getUserName().toLowerCase());
//check if it already exitsts - do I need to do this?
for (FederatedIdentityEntity fedIdent : userEntity.getFederatedIdentities()) {
if (fedIdent.equals(federatedIdentityEntity)) return;
}
userEntity.getFederatedIdentities().add(federatedIdentityEntity);
}
@Override
public boolean removeFederatedIdentity(RealmModel realm, UserModel userModel, String socialProvider) {
UserModel user = getUserById(userModel.getId(), realm);
UserEntity userEntity = ((UserAdapter) user).getUserEntity();
FederatedIdentityEntity federatedIdentityEntity = findSocialLink(userEntity, socialProvider);
if (federatedIdentityEntity == null) {
return false;
}
userEntity.getFederatedIdentities().remove(federatedIdentityEntity);
return true;
}
private FederatedIdentityEntity findSocialLink(UserEntity userEntity, String socialProvider) {
List<FederatedIdentityEntity> linkEntities = userEntity.getFederatedIdentities();
if (linkEntities == null) {
return null;
}
for (FederatedIdentityEntity federatedIdentityEntity : linkEntities) {
if (federatedIdentityEntity.getIdentityProvider().equals(socialProvider)) {
return federatedIdentityEntity;
}
}
return null;
}
@Override
public UserModel addUser(RealmModel realm, String username) {
return this.addUser(realm, KeycloakModelUtils.generateId(), username.toLowerCase(), true, true);
}
@Override
public void grantToAllUsers(RealmModel realm, RoleModel role) {
for (UserModel user : inMemoryModel.getUsers(realm.getId())) {
user.grantRole(role);
}
}
@Override
public void preRemove(RealmModel realm) {
// Nothing to do here? Federation links are attached to users, which are removed by InMemoryModel
}
@Override
public void preRemove(RealmModel realm, UserFederationProviderModel link) {
Set<UserModel> toBeRemoved = new HashSet<UserModel>();
for (UserModel user : inMemoryModel.getUsers(realm.getId())) {
String fedLink = user.getFederationLink();
if (fedLink == null) continue;
if (fedLink.equals(link.getId())) toBeRemoved.add(user);
}
for (UserModel user : toBeRemoved) {
inMemoryModel.removeUser(realm.getId(), user.getId());
}
}
@Override
public void preRemove(RealmModel realm, RoleModel role) {
// todo not sure what to do for this
}
@Override
public void preRemove(RealmModel realm, ClientModel client) {
// TODO
}
@Override
public void preRemove(ClientModel client, ProtocolMapperModel protocolMapper) {
// TODO
}
@Override
public boolean validCredentials(RealmModel realm, UserModel user, List<UserCredentialModel> input) {
return CredentialValidation.validCredentials(realm, user, input);
}
@Override
public boolean validCredentials(RealmModel realm, UserModel user, UserCredentialModel... input) {
return CredentialValidation.validCredentials(realm, user, input);
}
@Override
public void updateFederatedIdentity(RealmModel realm, UserModel federatedUser, FederatedIdentityModel federatedIdentityModel) {
federatedUser = getUserById(federatedUser.getId(), realm);
UserEntity userEntity = ((UserAdapter) federatedUser).getUserEntity();
FederatedIdentityEntity federatedIdentityEntity = findFederatedIdentityLink(userEntity, federatedIdentityModel.getIdentityProvider());
federatedIdentityEntity.setToken(federatedIdentityModel.getToken());
}
private FederatedIdentityEntity findFederatedIdentityLink(UserEntity userEntity, String identityProvider) {
List<FederatedIdentityEntity> linkEntities = userEntity.getFederatedIdentities();
if (linkEntities == null) {
return null;
}
for (FederatedIdentityEntity federatedIdentityEntity : linkEntities) {
if (federatedIdentityEntity.getIdentityProvider().equals(identityProvider)) {
return federatedIdentityEntity;
}
}
return null;
}
@Override
public CredentialValidationOutput validCredentials(RealmModel realm, UserCredentialModel... input) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
return null; // not supported yet
}
}

View file

@ -1,56 +0,0 @@
/*
* Copyright 2015 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.keycloak.models.file;
import org.keycloak.Config;
import org.keycloak.connections.file.FileConnectionProvider;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.UserProvider;
import org.keycloak.models.UserProviderFactory;
/**
* UserProviderFactory for JSON persistence.
*
* @author Stan Silvert ssilvert@redhat.com (C) 2015 Red Hat Inc.
*/
public class FileUserProviderFactory implements UserProviderFactory {
@Override
public void init(Config.Scope config) {
}
@Override
public String getId() {
return "file";
}
@Override
public UserProvider create(KeycloakSession session) {
FileConnectionProvider fcProvider = session.getProvider(FileConnectionProvider.class);
return new FileUserProvider(session, fcProvider);
}
@Override
public void close() {
}
@Override
public void postInit(KeycloakSessionFactory factory) {
}
}

View file

@ -1,663 +0,0 @@
/*
* Copyright 2015 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.keycloak.models.file.adapter;
import org.keycloak.connections.file.InMemoryModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ModelDuplicateException;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.entities.ClientEntity;
import org.keycloak.models.entities.ProtocolMapperEntity;
import org.keycloak.models.entities.RoleEntity;
import org.keycloak.models.utils.KeycloakModelUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* ApplicationModel used for JSON persistence.
*
* @author Stan Silvert ssilvert@redhat.com (C) 2015 Red Hat Inc.
*/
public class ClientAdapter implements ClientModel {
private final RealmModel realm;
private KeycloakSession session;
private final ClientEntity entity;
private final InMemoryModel inMemoryModel;
private final Map<String, RoleAdapter> allRoles = new HashMap<String, RoleAdapter>();
private final Map<String, RoleModel> allScopeMappings = new HashMap<String, RoleModel>();
public ClientAdapter(KeycloakSession session, RealmModel realm, ClientEntity entity, InMemoryModel inMemoryModel) {
this.realm = realm;
this.session = session;
this.entity = entity;
this.inMemoryModel = inMemoryModel;
}
@Override
public void updateClient() {
}
@Override
public String getId() {
return entity.getId();
}
@Override
public String getName() {
return entity.getName();
}
@Override
public void setName(String name) {
entity.setName(name);
}
@Override
public String getDescription() { return entity.getDescription(); }
@Override
public void setDescription(String description) { entity.setDescription(description); }
@Override
public Set<String> getWebOrigins() {
Set<String> result = new HashSet<String>();
if (entity.getWebOrigins() != null) {
result.addAll(entity.getWebOrigins());
}
return result;
}
@Override
public void setWebOrigins(Set<String> webOrigins) {
List<String> result = new ArrayList<String>();
result.addAll(webOrigins);
entity.setWebOrigins(result);
}
@Override
public void addWebOrigin(String webOrigin) {
Set<String> webOrigins = getWebOrigins();
webOrigins.add(webOrigin);
setWebOrigins(webOrigins);
}
@Override
public void removeWebOrigin(String webOrigin) {
Set<String> webOrigins = getWebOrigins();
webOrigins.remove(webOrigin);
setWebOrigins(webOrigins);
}
@Override
public Set<String> getRedirectUris() {
Set<String> result = new HashSet<String>();
if (entity.getRedirectUris() != null) {
result.addAll(entity.getRedirectUris());
}
return result;
}
@Override
public void setRedirectUris(Set<String> redirectUris) {
List<String> result = new ArrayList<String>();
result.addAll(redirectUris);
entity.setRedirectUris(result);
}
@Override
public void addRedirectUri(String redirectUri) {
if (entity.getRedirectUris().contains(redirectUri)) return;
entity.getRedirectUris().add(redirectUri);
}
@Override
public void removeRedirectUri(String redirectUri) {
entity.getRedirectUris().remove(redirectUri);
}
@Override
public boolean isEnabled() {
return entity.isEnabled();
}
@Override
public void setEnabled(boolean enabled) {
entity.setEnabled(enabled);
}
@Override
public String getClientAuthenticatorType() {
return entity.getClientAuthenticatorType();
}
@Override
public void setClientAuthenticatorType(String clientAuthenticatorType) {
entity.setClientAuthenticatorType(clientAuthenticatorType);
}
@Override
public boolean validateSecret(String secret) {
return secret.equals(entity.getSecret());
}
@Override
public String getSecret() {
return entity.getSecret();
}
@Override
public void setSecret(String secret) {
entity.setSecret(secret);
}
@Override
public boolean isPublicClient() {
return entity.isPublicClient();
}
@Override
public void setPublicClient(boolean flag) {
entity.setPublicClient(flag);
}
@Override
public boolean isFrontchannelLogout() {
return entity.isFrontchannelLogout();
}
@Override
public void setFrontchannelLogout(boolean flag) {
entity.setFrontchannelLogout(flag);
}
@Override
public boolean isFullScopeAllowed() {
return entity.isFullScopeAllowed();
}
@Override
public void setFullScopeAllowed(boolean value) {
entity.setFullScopeAllowed(value);
}
@Override
public RealmModel getRealm() {
return realm;
}
@Override
public int getNotBefore() {
return entity.getNotBefore();
}
@Override
public void setNotBefore(int notBefore) {
entity.setNotBefore(notBefore);
}
@Override
public Set<RoleModel> getScopeMappings() {
return new HashSet<RoleModel>(allScopeMappings.values());
}
@Override
public Set<RoleModel> getRealmScopeMappings() {
Set<RoleModel> allScopes = getScopeMappings();
Set<RoleModel> realmRoles = new HashSet<RoleModel>();
for (RoleModel role : allScopes) {
RoleAdapter roleAdapter = (RoleAdapter)role;
if (roleAdapter.isRealmRole()) {
realmRoles.add(role);
}
}
return realmRoles;
}
@Override
public void addScopeMapping(RoleModel role) {
allScopeMappings.put(role.getId(), role);
}
@Override
public void deleteScopeMapping(RoleModel role) {
allScopeMappings.remove(role.getId());
}
@Override
public String getProtocol() {
return entity.getProtocol();
}
@Override
public void setProtocol(String protocol) {
entity.setProtocol(protocol);
}
@Override
public void setAttribute(String name, String value) {
entity.getAttributes().put(name, value);
}
@Override
public void removeAttribute(String name) {
entity.getAttributes().remove(name);
}
@Override
public String getAttribute(String name) {
return entity.getAttributes().get(name);
}
@Override
public Map<String, String> getAttributes() {
Map<String, String> copy = new HashMap<String, String>();
copy.putAll(entity.getAttributes());
return copy;
}
@Override
public Set<ProtocolMapperModel> getProtocolMappers() {
Set<ProtocolMapperModel> result = new HashSet<ProtocolMapperModel>();
for (ProtocolMapperEntity entity : this.entity.getProtocolMappers()) {
ProtocolMapperModel model = getProtocolMapperById(entity.getId());
if (model != null) result.add(model);
}
return result;
}
@Override
public ProtocolMapperModel addProtocolMapper(ProtocolMapperModel model) {
if (getProtocolMapperByName(model.getProtocol(), model.getName()) != null) {
throw new RuntimeException("protocol mapper name must be unique per protocol");
}
ProtocolMapperEntity entity = new ProtocolMapperEntity();
String id = model.getId() != null ? model.getId() : KeycloakModelUtils.generateId();
entity.setId(id);
entity.setProtocol(model.getProtocol());
entity.setName(model.getName());
entity.setProtocolMapper(model.getProtocolMapper());
entity.setConfig(model.getConfig());
entity.setConsentRequired(model.isConsentRequired());
entity.setConsentText(model.getConsentText());
this.entity.getProtocolMappers().add(entity);
return entityToModel(entity);
}
@Override
public void removeProtocolMapper(ProtocolMapperModel mapping) {
ProtocolMapperEntity toBeRemoved = null;
for (ProtocolMapperEntity e : entity.getProtocolMappers()) {
if (e.getId().equals(mapping.getId())) {
toBeRemoved = e;
break;
}
}
entity.getProtocolMappers().remove(toBeRemoved);
}
@Override
public void updateProtocolMapper(ProtocolMapperModel mapping) {
ProtocolMapperEntity entity = getProtocolMapperEntityById(mapping.getId());
entity.setProtocolMapper(mapping.getProtocolMapper());
entity.setConsentRequired(mapping.isConsentRequired());
entity.setConsentText(mapping.getConsentText());
if (entity.getConfig() != null) {
entity.getConfig().clear();
entity.getConfig().putAll(mapping.getConfig());
} else {
entity.setConfig(mapping.getConfig());
}
}
protected ProtocolMapperEntity getProtocolMapperEntityById(String id) {
for (ProtocolMapperEntity e : entity.getProtocolMappers()) {
if (e.getId().equals(id)) {
return e;
}
}
return null;
}
protected ProtocolMapperEntity getProtocolMapperEntityByName(String protocol, String name) {
for (ProtocolMapperEntity e : entity.getProtocolMappers()) {
if (e.getProtocol().equals(protocol) && e.getName().equals(name)) {
return e;
}
}
return null;
}
@Override
public ProtocolMapperModel getProtocolMapperById(String id) {
ProtocolMapperEntity entity = getProtocolMapperEntityById(id);
if (entity == null) return null;
return entityToModel(entity);
}
@Override
public ProtocolMapperModel getProtocolMapperByName(String protocol, String name) {
ProtocolMapperEntity entity = getProtocolMapperEntityByName(protocol, name);
if (entity == null) return null;
return entityToModel(entity);
}
protected ProtocolMapperModel entityToModel(ProtocolMapperEntity entity) {
ProtocolMapperModel mapping = new ProtocolMapperModel();
mapping.setId(entity.getId());
mapping.setName(entity.getName());
mapping.setProtocol(entity.getProtocol());
mapping.setProtocolMapper(entity.getProtocolMapper());
mapping.setConsentRequired(entity.isConsentRequired());
mapping.setConsentText(entity.getConsentText());
Map<String, String> config = new HashMap<String, String>();
if (entity.getConfig() != null) config.putAll(entity.getConfig());
mapping.setConfig(config);
return mapping;
}
@Override
public String getClientId() {
return entity.getClientId();
}
@Override
public void setClientId(String clientId) {
if (appNameExists(clientId)) throw new ModelDuplicateException("Application named " + clientId + " already exists.");
entity.setClientId(clientId);
}
private boolean appNameExists(String name) {
for (ClientModel app : realm.getClients()) {
if (app == this) continue;
if (app.getClientId().equals(name)) return true;
}
return false;
}
@Override
public boolean isSurrogateAuthRequired() {
return entity.isSurrogateAuthRequired();
}
@Override
public void setSurrogateAuthRequired(boolean surrogateAuthRequired) {
entity.setSurrogateAuthRequired(surrogateAuthRequired);
}
@Override
public String getManagementUrl() {
return entity.getManagementUrl();
}
@Override
public void setManagementUrl(String url) {
entity.setManagementUrl(url);
}
@Override
public void setRootUrl(String url) {
entity.setRootUrl(url);
}
@Override
public String getRootUrl() {
return entity.getRootUrl();
}
@Override
public void setBaseUrl(String url) {
entity.setBaseUrl(url);
}
@Override
public String getBaseUrl() {
return entity.getBaseUrl();
}
@Override
public boolean isBearerOnly() {
return entity.isBearerOnly();
}
@Override
public void setBearerOnly(boolean only) {
entity.setBearerOnly(only);
}
@Override
public boolean isConsentRequired() {
return entity.isConsentRequired();
}
@Override
public void setConsentRequired(boolean consentRequired) {
entity.setConsentRequired(consentRequired);
}
@Override
public boolean isServiceAccountsEnabled() {
return entity.isServiceAccountsEnabled();
}
@Override
public void setServiceAccountsEnabled(boolean serviceAccountsEnabled) {
entity.setServiceAccountsEnabled(serviceAccountsEnabled);
}
@Override
public boolean isDirectGrantsOnly() {
return entity.isDirectGrantsOnly();
}
@Override
public void setDirectGrantsOnly(boolean flag) {
entity.setDirectGrantsOnly(flag);
}
@Override
public RoleAdapter getRole(String name) {
for (RoleAdapter role : allRoles.values()) {
if (role.getName().equals(name)) return role;
}
return null;
}
@Override
public RoleAdapter addRole(String name) {
return this.addRole(KeycloakModelUtils.generateId(), name);
}
@Override
public RoleAdapter addRole(String id, String name) {
if (roleNameExists(name)) throw new ModelDuplicateException("Role named " + name + " already exists.");
RoleEntity roleEntity = new RoleEntity();
roleEntity.setId(id);
roleEntity.setName(name);
roleEntity.setClientId(getId());
RoleAdapter role = new RoleAdapter(getRealm(), roleEntity, this);
allRoles.put(id, role);
return role;
}
private boolean roleNameExists(String name) {
for (RoleModel role : allRoles.values()) {
if (role.getName().equals(name)) return true;
}
return false;
}
@Override
public boolean removeRole(RoleModel role) {
boolean removed = (allRoles.remove(role.getId()) != null);
// remove application roles from users
for (UserModel user : inMemoryModel.getUsers(realm.getId())) {
user.deleteRoleMapping(role);
}
// delete scope mappings from applications
for (ClientModel app : realm.getClients()) {
app.deleteScopeMapping(role);
}
// remove role from the realm
realm.removeRole(role);
this.deleteScopeMapping(role);
return removed;
}
@Override
public Set<RoleModel> getRoles() {
return new HashSet(allRoles.values());
}
@Override
public boolean hasScope(RoleModel role) {
if (isFullScopeAllowed()) return true;
Set<RoleModel> roles = getScopeMappings();
if (roles.contains(role)) return true;
for (RoleModel mapping : roles) {
if (mapping.hasRole(role)) return true;
}
roles = getRoles();
if (roles.contains(role)) return true;
for (RoleModel mapping : roles) {
if (mapping.hasRole(role)) return true;
}
return false;
}
@Override
public Set<RoleModel> getClientScopeMappings(ClientModel client) {
Set<RoleModel> allScopes = client.getScopeMappings();
Set<RoleModel> appRoles = new HashSet<RoleModel>();
for (RoleModel role : allScopes) {
RoleAdapter roleAdapter = (RoleAdapter)role;
if (getId().equals(roleAdapter.getRoleEntity().getClientId())) {
appRoles.add(role);
}
}
return appRoles;
}
@Override
public List<String> getDefaultRoles() {
return entity.getDefaultRoles();
}
@Override
public void addDefaultRole(String name) {
RoleModel role = getRole(name);
if (role == null) {
addRole(name);
}
List<String> defaultRoles = getDefaultRoles();
if (defaultRoles.contains(name)) return;
String[] defaultRoleNames = defaultRoles.toArray(new String[defaultRoles.size() + 1]);
defaultRoleNames[defaultRoleNames.length - 1] = name;
updateDefaultRoles(defaultRoleNames);
}
@Override
public void updateDefaultRoles(String[] defaultRoles) {
List<String> roleNames = new ArrayList<String>();
for (String roleName : defaultRoles) {
RoleModel role = getRole(roleName);
if (role == null) {
addRole(roleName);
}
roleNames.add(roleName);
}
entity.setDefaultRoles(roleNames);
}
@Override
public int getNodeReRegistrationTimeout() {
return entity.getNodeReRegistrationTimeout();
}
@Override
public void setNodeReRegistrationTimeout(int timeout) {
entity.setNodeReRegistrationTimeout(timeout);
}
@Override
public Map<String, Integer> getRegisteredNodes() {
return entity.getRegisteredNodes() == null ? Collections.<String, Integer>emptyMap() : Collections.unmodifiableMap(entity.getRegisteredNodes());
}
@Override
public void registerNode(String nodeHost, int registrationTime) {
if (entity.getRegisteredNodes() == null) {
entity.setRegisteredNodes(new HashMap<String, Integer>());
}
entity.getRegisteredNodes().put(nodeHost, registrationTime);
}
@Override
public void unregisterNode(String nodeHost) {
if (entity.getRegisteredNodes() == null) return;
entity.getRegisteredNodes().remove(nodeHost);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || !(o instanceof ClientModel)) return false;
ClientModel that = (ClientModel) o;
return that.getId().equals(getId());
}
@Override
public int hashCode() {
return getId().hashCode();
}
}

View file

@ -1,213 +0,0 @@
package org.keycloak.models.file.adapter;
import org.keycloak.models.ClientModel;
import org.keycloak.models.GroupModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.entities.GroupEntity;
import org.keycloak.models.utils.KeycloakModelUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
*
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
*/
public class GroupAdapter implements GroupModel {
private final GroupEntity group;
private RealmModel realm;
private KeycloakSession session;
public GroupAdapter(KeycloakSession session, RealmModel realm, GroupEntity group) {
this.group = group;
this.realm = realm;
this.session = session;
}
@Override
public String getId() {
return group.getId();
}
@Override
public String getName() {
return group.getName();
}
@Override
public void setName(String name) {
group.setName(name);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || !(o instanceof GroupModel)) return false;
GroupModel that = (GroupModel) o;
return that.getId().equals(getId());
}
@Override
public int hashCode() {
return getId().hashCode();
}
@Override
public void setSingleAttribute(String name, String value) {
if (group.getAttributes() == null) {
group.setAttributes(new HashMap<String, List<String>>());
}
List<String> attrValues = new ArrayList<>();
attrValues.add(value);
group.getAttributes().put(name, attrValues);
}
@Override
public void setAttribute(String name, List<String> values) {
if (group.getAttributes() == null) {
group.setAttributes(new HashMap<String, List<String>>());
}
group.getAttributes().put(name, values);
}
@Override
public void removeAttribute(String name) {
if (group.getAttributes() == null) return;
group.getAttributes().remove(name);
}
@Override
public String getFirstAttribute(String name) {
if (group.getAttributes()==null) return null;
List<String> attrValues = group.getAttributes().get(name);
return (attrValues==null || attrValues.isEmpty()) ? null : attrValues.get(0);
}
@Override
public List<String> getAttribute(String name) {
if (group.getAttributes()==null) return Collections.<String>emptyList();
List<String> attrValues = group.getAttributes().get(name);
return (attrValues == null) ? Collections.<String>emptyList() : Collections.unmodifiableList(attrValues);
}
@Override
public Map<String, List<String>> getAttributes() {
return group.getAttributes()==null ? Collections.<String, List<String>>emptyMap() : Collections.unmodifiableMap((Map) group.getAttributes());
}
@Override
public boolean hasRole(RoleModel role) {
Set<RoleModel> roles = getRoleMappings();
return KeycloakModelUtils.hasRole(roles, role);
}
@Override
public void grantRole(RoleModel role) {
if (group.getRoleIds() == null) {
group.setRoleIds(new LinkedList<String>());
}
if (group.getRoleIds().contains(role.getId())) {
return;
}
group.getRoleIds().add(role.getId());
}
@Override
public Set<RoleModel> getRoleMappings() {
if (group.getRoleIds() == null || group.getRoleIds().isEmpty()) return Collections.EMPTY_SET;
Set<RoleModel> roles = new HashSet<>();
for (String id : group.getRoleIds()) {
roles.add(realm.getRoleById(id));
}
return roles;
}
@Override
public Set<RoleModel> getRealmRoleMappings() {
Set<RoleModel> allRoles = getRoleMappings();
// Filter to retrieve just realm roles
Set<RoleModel> realmRoles = new HashSet<RoleModel>();
for (RoleModel role : allRoles) {
if (role.getContainer() instanceof RealmModel) {
realmRoles.add(role);
}
}
return realmRoles;
}
@Override
public void deleteRoleMapping(RoleModel role) {
if (group == null || role == null) return;
if (group.getRoleIds() == null) return;
group.getRoleIds().remove(role.getId());
}
@Override
public Set<RoleModel> getClientRoleMappings(ClientModel app) {
Set<RoleModel> result = new HashSet<RoleModel>();
Set<RoleModel> roles = getRoleMappings();
for (RoleModel role : roles) {
if (app.equals(role.getContainer())) {
result.add(role);
}
}
return result;
}
@Override
public GroupModel getParent() {
if (group.getParentId() == null) return null;
return realm.getGroupById(group.getParentId());
}
@Override
public String getParentId() {
return group.getParentId();
}
@Override
public Set<GroupModel> getSubGroups() {
Set<GroupModel> subGroups = new HashSet<>();
for (GroupModel groupModel : realm.getGroups()) {
if (groupModel.getParent().equals(this)) {
subGroups.add(groupModel);
}
}
return subGroups;
}
@Override
public void setParent(GroupModel group) {
this.group.setParentId(group.getId());
}
@Override
public void addChild(GroupModel subGroup) {
subGroup.setParent(this);
}
@Override
public void removeChild(GroupModel subGroup) {
subGroup.setParent(null);
}
}

View file

@ -1,26 +0,0 @@
package org.keycloak.models.file.adapter;
import org.keycloak.connections.file.InMemoryModel;
import org.keycloak.migration.MigrationModel;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class MigrationModelAdapter implements MigrationModel {
protected InMemoryModel em;
public MigrationModelAdapter(InMemoryModel em) {
this.em = em;
}
@Override
public String getStoredVersion() {
return em.getModelVersion();
}
@Override
public void setStoredVersion(String version) {
em.setModelVersion(version);
}
}

View file

@ -1,188 +0,0 @@
/*
* Copyright 2015 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.keycloak.models.file.adapter;
import org.keycloak.models.ModelDuplicateException;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleContainerModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.entities.RoleEntity;
import org.keycloak.models.utils.KeycloakModelUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* RoleModel for JSON persistence.
*
* @author Stan Silvert ssilvert@redhat.com (C) 2015 Red Hat Inc.
*/
public class RoleAdapter implements RoleModel {
private final RoleEntity role;
private RoleContainerModel roleContainer;
private final RealmModel realm;
private final Set<RoleModel> compositeRoles = new HashSet<RoleModel>();
public RoleAdapter(RealmModel realm, RoleEntity roleEntity) {
this(realm, roleEntity, null);
}
public RoleAdapter(RealmModel realm, RoleEntity roleEntity, RoleContainerModel roleContainer) {
this.role = roleEntity;
this.roleContainer = roleContainer;
this.realm = realm;
}
public RoleEntity getRoleEntity() {
return this.role;
}
public boolean isRealmRole() {
return role.getRealmId() != null;
}
@Override
public String getId() {
return role.getId();
}
@Override
public String getName() {
return role.getName();
}
@Override
public void setName(String name) {
RealmAdapter realmAdapter = (RealmAdapter)realm;
if (role.getName().equals(name)) return;
if (realmAdapter.hasRoleWithName(name)) throw new ModelDuplicateException("Role name " + name + " already exists.");
role.setName(name);
}
@Override
public String getDescription() {
return role.getDescription();
}
@Override
public void setDescription(String description) {
role.setDescription(description);
}
@Override
public boolean isScopeParamRequired() {
return role.isScopeParamRequired();
}
@Override
public void setScopeParamRequired(boolean scopeParamRequired) {
role.setScopeParamRequired(scopeParamRequired);
}
@Override
public boolean isComposite() {
return role.getCompositeRoleIds() != null && role.getCompositeRoleIds().size() > 0;
}
@Override
public void addCompositeRole(RoleModel childRole) {
List<String> compositeRoleIds = role.getCompositeRoleIds();
if (compositeRoleIds == null) compositeRoleIds = new ArrayList<String>();
compositeRoleIds.add(childRole.getId());
role.setCompositeRoleIds(compositeRoleIds);
compositeRoles.add(childRole);
}
/**
* Recursively remove composite roles for the specified app
* @param appId
*/
public void removeApplicationComposites(String appId) {
if (!isComposite()) return;
Set<RoleModel> toBeRemoved = new HashSet<RoleModel>();
for (RoleModel compositeRole : getComposites()) {
RoleAdapter roleAdapter = (RoleAdapter)compositeRole;
if (appId.equals(roleAdapter.getRoleEntity().getClientId())) {
toBeRemoved.add(compositeRole);
} else {
roleAdapter.removeApplicationComposites(appId);
}
}
for (RoleModel compositeRole : toBeRemoved) {
removeCompositeRole(compositeRole);
}
}
@Override
public void removeCompositeRole(RoleModel childRole) {
compositeRoles.remove(childRole);
List<String> compositeRoleIds = role.getCompositeRoleIds();
if (compositeRoleIds == null) return; // shouldn't happen
compositeRoleIds.remove(childRole.getId());
role.setCompositeRoleIds(compositeRoleIds);
}
@Override
public Set<RoleModel> getComposites() {
return Collections.unmodifiableSet(compositeRoles);
}
@Override
public RoleContainerModel getContainer() {
if (roleContainer == null) {
// Compute it
if (role.getRealmId() != null) {
roleContainer = realm;//new RealmAdapter(session, realm);
} else if (role.getClientId() != null) {
roleContainer = realm.getClientById(role.getClientId());//new ApplicationAdapter(session, realm, appEntity);
} else {
throw new IllegalStateException("Both realmId and applicationId are null for role: " + this);
}
}
return roleContainer;
}
@Override
public boolean hasRole(RoleModel role) {
if (this.equals(role)) return true;
if (!isComposite()) return false;
Set<RoleModel> visited = new HashSet<RoleModel>();
return KeycloakModelUtils.searchFor(role, this, visited);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || !(o instanceof RoleModel)) return false;
RoleModel that = (RoleModel) o;
return that.getId().equals(getId());
}
@Override
public int hashCode() {
return getId().hashCode();
}
}

View file

@ -1,614 +0,0 @@
/*
* Copyright 2015 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.keycloak.models.file.adapter;
import org.keycloak.connections.file.InMemoryModel;
import org.keycloak.models.ClientModel;
import static org.keycloak.models.utils.Pbkdf2PasswordEncoder.getSalt;
import org.keycloak.models.GroupModel;
import org.keycloak.models.ModelDuplicateException;
import org.keycloak.models.OTPPolicy;
import org.keycloak.models.UserConsentModel;
import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserCredentialValueModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.entities.CredentialEntity;
import org.keycloak.models.entities.FederatedIdentityEntity;
import org.keycloak.models.entities.RoleEntity;
import org.keycloak.models.entities.UserEntity;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.models.utils.Pbkdf2PasswordEncoder;
import org.keycloak.common.util.Time;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* UserModel for JSON persistence.
*
* @author Stan Silvert ssilvert@redhat.com (C) 2015 Red Hat Inc.
*/
public class UserAdapter implements UserModel, Comparable {
private final InMemoryModel inMemoryModel;
private final UserEntity user;
private final RealmModel realm;
private final Set<RoleModel> allRoles = new HashSet<RoleModel>();
private final Set<GroupModel> allGroups = new HashSet<GroupModel>();
public UserAdapter(RealmModel realm, UserEntity userEntity, InMemoryModel inMemoryModel) {
this.user = userEntity;
this.realm = realm;
if (userEntity.getFederatedIdentities() == null) {
userEntity.setFederatedIdentities(new ArrayList<FederatedIdentityEntity>());
}
this.inMemoryModel = inMemoryModel;
}
public UserEntity getUserEntity() {
return this.user;
}
@Override
public String getId() {
return user.getId();
}
@Override
public String getUsername() {
return user.getUsername();
}
@Override
public void setUsername(String username) {
username = KeycloakModelUtils.toLowerCaseSafe(username);
if (getUsername() == null) {
user.setUsername(username);
return;
}
if (getUsername().equals(username)) return; // allow setting to same name
if (inMemoryModel.hasUserWithUsername(realm.getId(), username))
throw new ModelDuplicateException("User with username " + username + " already exists in realm.");
user.setUsername(username);
}
@Override
public Long getCreatedTimestamp() {
return user.getCreatedTimestamp();
}
@Override
public void setCreatedTimestamp(Long timestamp) {
user.setCreatedTimestamp(timestamp);
}
@Override
public boolean isEnabled() {
return user.isEnabled();
}
@Override
public void setEnabled(boolean enabled) {
user.setEnabled(enabled);
}
@Override
public String getFirstName() {
return user.getFirstName();
}
@Override
public void setFirstName(String firstName) {
user.setFirstName(firstName);
}
@Override
public String getLastName() {
return user.getLastName();
}
@Override
public void setLastName(String lastName) {
user.setLastName(lastName);
}
@Override
public String getEmail() {
return user.getEmail();
}
@Override
public void setEmail(String email) {
email = KeycloakModelUtils.toLowerCaseSafe(email);
if (email == null) {
user.setEmail(email);
return;
}
if (email.equals(getEmail())) return;
RealmAdapter realmAdapter = (RealmAdapter)realm;
if (realmAdapter.hasUserWithEmail(email)) throw new ModelDuplicateException("User with email address " + email + " already exists.");
user.setEmail(email);
}
@Override
public boolean isEmailVerified() {
return user.isEmailVerified();
}
@Override
public void setEmailVerified(boolean verified) {
user.setEmailVerified(verified);
}
@Override
public void setSingleAttribute(String name, String value) {
if (user.getAttributes() == null) {
user.setAttributes(new HashMap<String, List<String>>());
}
List<String> attrValues = new ArrayList<>();
attrValues.add(value);
user.getAttributes().put(name, attrValues);
}
@Override
public void setAttribute(String name, List<String> values) {
if (user.getAttributes() == null) {
user.setAttributes(new HashMap<String, List<String>>());
}
user.getAttributes().put(name, values);
}
@Override
public void removeAttribute(String name) {
if (user.getAttributes() == null) return;
user.getAttributes().remove(name);
}
@Override
public String getFirstAttribute(String name) {
if (user.getAttributes()==null) return null;
List<String> attrValues = user.getAttributes().get(name);
return (attrValues==null || attrValues.isEmpty()) ? null : attrValues.get(0);
}
@Override
public List<String> getAttribute(String name) {
if (user.getAttributes()==null) return Collections.<String>emptyList();
List<String> attrValues = user.getAttributes().get(name);
return (attrValues == null) ? Collections.<String>emptyList() : Collections.unmodifiableList(attrValues);
}
@Override
public Map<String, List<String>> getAttributes() {
return user.getAttributes()==null ? Collections.<String, List<String>>emptyMap() : Collections.unmodifiableMap((Map) user.getAttributes());
}
@Override
public Set<String> getRequiredActions() {
List<String> requiredActions = user.getRequiredActions();
if (requiredActions == null) requiredActions = new ArrayList<String>();
return new HashSet(requiredActions);
}
@Override
public void addRequiredAction(RequiredAction action) {
String actionName = action.name();
addRequiredAction(actionName);
}
@Override
public void addRequiredAction(String actionName) {
List<String> requiredActions = user.getRequiredActions();
if (requiredActions == null) requiredActions = new ArrayList<>();
if (!requiredActions.contains(actionName)) {
requiredActions.add(actionName);
}
user.setRequiredActions(requiredActions);
}
@Override
public void removeRequiredAction(RequiredAction action) {
String actionName = action.name();
removeRequiredAction(actionName);
}
@Override
public void removeRequiredAction(String actionName) {
List<String> requiredActions = user.getRequiredActions();
if (requiredActions == null) return;
requiredActions.remove(actionName);
user.setRequiredActions(requiredActions);
}
@Override
public boolean isOtpEnabled() {
return user.isTotp();
}
@Override
public void setOtpEnabled(boolean totp) {
user.setTotp(totp);
}
@Override
public void updateCredential(UserCredentialModel cred) {
if (cred.getType().equals(UserCredentialModel.PASSWORD)) {
updatePasswordCredential(cred);
} else if (UserCredentialModel.isOtp(cred.getType())){
updateOtpCredential(cred);
}else {
CredentialEntity credentialEntity = getCredentialEntity(user, cred.getType());
if (credentialEntity == null) {
credentialEntity = setCredentials(user, cred);
credentialEntity.setValue(cred.getValue());
user.getCredentials().add(credentialEntity);
} else {
credentialEntity.setValue(cred.getValue());
}
}
}
private void updateOtpCredential(UserCredentialModel cred) {
CredentialEntity credentialEntity = getCredentialEntity(user, cred.getType());
if (credentialEntity == null) {
credentialEntity = setCredentials(user, cred);
credentialEntity.setValue(cred.getValue());
OTPPolicy otpPolicy = realm.getOTPPolicy();
credentialEntity.setAlgorithm(otpPolicy.getAlgorithm());
credentialEntity.setDigits(otpPolicy.getDigits());
credentialEntity.setCounter(otpPolicy.getInitialCounter());
credentialEntity.setPeriod(otpPolicy.getPeriod());
user.getCredentials().add(credentialEntity);
} else {
credentialEntity.setValue(cred.getValue());
OTPPolicy policy = realm.getOTPPolicy();
credentialEntity.setDigits(policy.getDigits());
credentialEntity.setCounter(policy.getInitialCounter());
credentialEntity.setAlgorithm(policy.getAlgorithm());
credentialEntity.setPeriod(policy.getPeriod());
}
}
private void updatePasswordCredential(UserCredentialModel cred) {
CredentialEntity credentialEntity = getCredentialEntity(user, cred.getType());
if (credentialEntity == null) {
credentialEntity = setCredentials(user, cred);
setValue(credentialEntity, cred);
user.getCredentials().add(credentialEntity);
} else {
int expiredPasswordsPolicyValue = -1;
PasswordPolicy policy = realm.getPasswordPolicy();
if(policy != null) {
expiredPasswordsPolicyValue = policy.getExpiredPasswords();
}
if (expiredPasswordsPolicyValue != -1) {
user.getCredentials().remove(credentialEntity);
credentialEntity.setType(UserCredentialModel.PASSWORD_HISTORY);
user.getCredentials().add(credentialEntity);
List<CredentialEntity> credentialEntities = getCredentialEntities(user, UserCredentialModel.PASSWORD_HISTORY);
if (credentialEntities.size() > expiredPasswordsPolicyValue - 1) {
user.getCredentials().removeAll(credentialEntities.subList(expiredPasswordsPolicyValue - 1, credentialEntities.size()));
}
credentialEntity = setCredentials(user, cred);
setValue(credentialEntity, cred);
user.getCredentials().add(credentialEntity);
} else {
List<CredentialEntity> credentialEntities = getCredentialEntities(user, UserCredentialModel.PASSWORD_HISTORY);
if (credentialEntities != null && credentialEntities.size() > 0) {
user.getCredentials().removeAll(credentialEntities);
}
setValue(credentialEntity, cred);
}
}
}
private CredentialEntity setCredentials(UserEntity user, UserCredentialModel cred) {
CredentialEntity credentialEntity = new CredentialEntity();
credentialEntity.setType(cred.getType());
credentialEntity.setDevice(cred.getDevice());
return credentialEntity;
}
private void setValue(CredentialEntity credentialEntity, UserCredentialModel cred) {
byte[] salt = getSalt();
int hashIterations = 1;
PasswordPolicy policy = realm.getPasswordPolicy();
if (policy != null) {
hashIterations = policy.getHashIterations();
if (hashIterations == -1)
hashIterations = 1;
}
credentialEntity.setCreatedDate(Time.toMillis(Time.currentTime()));
credentialEntity.setValue(new Pbkdf2PasswordEncoder(salt).encode(cred.getValue(), hashIterations));
credentialEntity.setSalt(salt);
credentialEntity.setHashIterations(hashIterations);
}
private CredentialEntity getCredentialEntity(UserEntity userEntity, String credType) {
for (CredentialEntity entity : userEntity.getCredentials()) {
if (entity.getType().equals(credType)) {
return entity;
}
}
return null;
}
private List<CredentialEntity> getCredentialEntities(UserEntity userEntity, String credType) {
List<CredentialEntity> credentialEntities = new ArrayList<CredentialEntity>();
for (CredentialEntity entity : userEntity.getCredentials()) {
if (entity.getType().equals(credType)) {
credentialEntities.add(entity);
}
}
// Avoiding direct use of credSecond.getCreatedDate() - credFirst.getCreatedDate() to prevent Integer Overflow
// Orders from most recent to least recent
Collections.sort(credentialEntities, new Comparator<CredentialEntity>() {
public int compare(CredentialEntity credFirst, CredentialEntity credSecond) {
if (credFirst.getCreatedDate() > credSecond.getCreatedDate()) {
return -1;
} else if (credFirst.getCreatedDate() < credSecond.getCreatedDate()) {
return 1;
} else {
return 0;
}
}
});
return credentialEntities;
}
@Override
public List<UserCredentialValueModel> getCredentialsDirectly() {
List<CredentialEntity> credentials = new ArrayList<CredentialEntity>(user.getCredentials());
List<UserCredentialValueModel> result = new ArrayList<UserCredentialValueModel>();
for (CredentialEntity credEntity : credentials) {
UserCredentialValueModel credModel = new UserCredentialValueModel();
credModel.setType(credEntity.getType());
credModel.setDevice(credEntity.getDevice());
credModel.setCreatedDate(credEntity.getCreatedDate());
credModel.setValue(credEntity.getValue());
credModel.setSalt(credEntity.getSalt());
credModel.setHashIterations(credEntity.getHashIterations());
if (UserCredentialModel.isOtp(credEntity.getType())) {
credModel.setCounter(credEntity.getCounter());
if (credEntity.getAlgorithm() == null) {
// for migration where these values would be null
credModel.setAlgorithm(realm.getOTPPolicy().getAlgorithm());
} else {
credModel.setAlgorithm(credEntity.getAlgorithm());
}
if (credEntity.getDigits() == 0) {
// for migration where these values would be 0
credModel.setDigits(realm.getOTPPolicy().getDigits());
} else {
credModel.setDigits(credEntity.getDigits());
}
if (credEntity.getPeriod() == 0) {
// for migration where these values would be 0
credModel.setPeriod(realm.getOTPPolicy().getPeriod());
} else {
credModel.setPeriod(credEntity.getPeriod());
}
}
result.add(credModel);
}
return result;
}
@Override
public void updateCredentialDirectly(UserCredentialValueModel credModel) {
CredentialEntity credentialEntity = getCredentialEntity(user, credModel.getType());
if (credentialEntity == null) {
credentialEntity = new CredentialEntity();
// credentialEntity.setId(KeycloakModelUtils.generateId());
credentialEntity.setType(credModel.getType());
// credentialEntity.setUser(user);
credModel.setCreatedDate(credModel.getCreatedDate());
user.getCredentials().add(credentialEntity);
}
credentialEntity.setValue(credModel.getValue());
credentialEntity.setSalt(credModel.getSalt());
credentialEntity.setDevice(credModel.getDevice());
credentialEntity.setHashIterations(credModel.getHashIterations());
credentialEntity.setCounter(credModel.getCounter());
credentialEntity.setAlgorithm(credModel.getAlgorithm());
credentialEntity.setDigits(credModel.getDigits());
credentialEntity.setPeriod(credModel.getPeriod());
}
@Override
public Set<GroupModel> getGroups() {
return Collections.unmodifiableSet(allGroups);
}
@Override
public void joinGroup(GroupModel group) {
allGroups.add(group);
}
@Override
public void leaveGroup(GroupModel group) {
if (user == null || group == null) return;
allGroups.remove(group);
}
@Override
public boolean isMemberOf(GroupModel group) {
return KeycloakModelUtils.isMember(getGroups(), group);
}
@Override
public boolean hasRole(RoleModel role) {
Set<RoleModel> roles = getRoleMappings();
return KeycloakModelUtils.hasRole(roles, role);
}
@Override
public void grantRole(RoleModel role) {
allRoles.add(role);
}
@Override
public Set<RoleModel> getRoleMappings() {
return Collections.unmodifiableSet(allRoles);
}
@Override
public Set<RoleModel> getRealmRoleMappings() {
Set<RoleModel> allRoleMappings = getRoleMappings();
// Filter to retrieve just realm roles TODO: Maybe improve to avoid filter programmatically... Maybe have separate fields for realmRoles and appRoles on user?
Set<RoleModel> realmRoles = new HashSet<RoleModel>();
for (RoleModel role : allRoleMappings) {
RoleEntity roleEntity = ((RoleAdapter) role).getRoleEntity();
if (realm.getId().equals(roleEntity.getRealmId())) {
realmRoles.add(role);
}
}
return realmRoles;
}
@Override
public void deleteRoleMapping(RoleModel role) {
if (user == null || role == null) return;
allRoles.remove(role);
}
@Override
public Set<RoleModel> getClientRoleMappings(ClientModel app) {
Set<RoleModel> result = new HashSet<RoleModel>();
for (RoleModel role : allRoles) {
RoleEntity roleEntity = ((RoleAdapter)role).getRoleEntity();
if (app.getId().equals(roleEntity.getClientId())) {
result.add(new RoleAdapter(realm, roleEntity, app));
}
}
return result;
}
@Override
public String getFederationLink() {
return user.getFederationLink();
}
@Override
public void setFederationLink(String link) {
user.setFederationLink(link);
}
@Override
public String getServiceAccountClientLink() {
return user.getServiceAccountClientLink();
}
@Override
public void setServiceAccountClientLink(String clientInternalId) {
user.setServiceAccountClientLink(clientInternalId);
}
@Override
public void addConsent(UserConsentModel consent) {
// TODO
}
@Override
public UserConsentModel getConsentByClient(String clientId) {
// TODO
return null;
}
@Override
public List<UserConsentModel> getConsents() {
// TODO
return null;
}
@Override
public void updateConsent(UserConsentModel consent) {
// TODO
}
@Override
public boolean revokeConsentForClient(String clientId) {
// TODO
return false;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || !(o instanceof UserModel)) return false;
UserModel that = (UserModel) o;
return that.getId().equals(getId());
}
@Override
public int hashCode() {
return getId().hashCode();
}
@Override
public int compareTo(Object user) {
if (this == user) return 0;
return (getUsername().compareTo(((UserModel)user).getUsername()));
}
}

View file

@ -1 +0,0 @@
org.keycloak.models.file.FileRealmProviderFactory

View file

@ -1 +0,0 @@
org.keycloak.models.file.FileUserProviderFactory

View file

@ -29,7 +29,6 @@
<module>invalidation-cache</module>
<module>jpa</module>
<module>mongo</module>
<module>file</module>
<module>sessions-infinispan</module>
</modules>
</project>

11
pom.xml
View file

@ -838,7 +838,7 @@
<groupId>org.keycloak</groupId>
<artifactId>keycloak-wf9-server-subsystem</artifactId>
<version>${project.version}</version>
</dependency>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-subsystem</artifactId>
@ -959,11 +959,6 @@
<artifactId>keycloak-model-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-model-file</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-invalidation-cache-infinispan</artifactId>
@ -1441,7 +1436,7 @@
<groupId>org.wildfly.build</groupId>
<artifactId>wildfly-feature-pack-build-maven-plugin</artifactId>
<version>${wildfly.build-tools.version}</version>
</plugin>
</plugin>
<plugin>
<groupId>org.wildfly.build</groupId>
<artifactId>wildfly-server-provisioning-maven-plugin</artifactId>
@ -1462,7 +1457,7 @@
<requireMavenVersion>
<version>3.1.1</version>
</requireMavenVersion>
</rules>
</rules>
</configuration>
</execution>
</executions>