Merge pull request #536 from patriot1burke/master

realmId and rroleId
This commit is contained in:
Bill Burke 2014-07-17 16:34:27 -04:00
commit 14af840c3a
18 changed files with 246 additions and 186 deletions

View file

@ -145,8 +145,8 @@ public class ApplicationAdapter extends ClientAdapter implements ApplicationMode
applicationEntity.getRoles().remove(role); applicationEntity.getRoles().remove(role);
applicationEntity.getDefaultRoles().remove(role); applicationEntity.getDefaultRoles().remove(role);
em.createNativeQuery("delete from CompositeRole where childRole = :role").setParameter("role", role).executeUpdate(); em.createNativeQuery("delete from COMPOSITE_ROLE where CHILD_ROLE = :role").setParameter("role", role).executeUpdate();
em.createQuery("delete from " + ScopeMappingEntity.class.getSimpleName() + " where role = :role").setParameter("role", role).executeUpdate(); em.createNamedQuery("deleteScopeMappingByRole").setParameter("role", role).executeUpdate();
role.setApplication(null); role.setApplication(null);
em.flush(); em.flush();
em.remove(role); em.remove(role);

View file

@ -9,12 +9,8 @@ import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.models.UserProvider; import org.keycloak.models.UserProvider;
import org.keycloak.models.jpa.entities.AuthenticationLinkEntity; import org.keycloak.models.jpa.entities.AuthenticationLinkEntity;
import org.keycloak.models.jpa.entities.CredentialEntity;
import org.keycloak.models.jpa.entities.RealmEntity;
import org.keycloak.models.jpa.entities.RoleEntity;
import org.keycloak.models.jpa.entities.SocialLinkEntity; import org.keycloak.models.jpa.entities.SocialLinkEntity;
import org.keycloak.models.jpa.entities.UserEntity; import org.keycloak.models.jpa.entities.UserEntity;
import org.keycloak.models.jpa.entities.UserRoleMappingEntity;
import org.keycloak.models.utils.CredentialValidation; import org.keycloak.models.utils.CredentialValidation;
import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.models.utils.KeycloakModelUtils;
@ -49,8 +45,7 @@ public class JpaUserProvider implements UserProvider {
UserEntity entity = new UserEntity(); UserEntity entity = new UserEntity();
entity.setId(id); entity.setId(id);
entity.setUsername(username); entity.setUsername(username);
RealmEntity realmEntity = em.getReference(RealmEntity.class, realm.getId()); entity.setRealmId(realm.getId());
entity.setRealm(realmEntity);
em.persist(entity); em.persist(entity);
em.flush(); em.flush();
UserModel userModel = new UserAdapter(realm, em, entity); UserModel userModel = new UserAdapter(realm, em, entity);
@ -79,8 +74,7 @@ public class JpaUserProvider implements UserProvider {
public boolean removeUser(RealmModel realm, String name) { public boolean removeUser(RealmModel realm, String name) {
TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserByUsername", UserEntity.class); TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserByUsername", UserEntity.class);
query.setParameter("username", name); query.setParameter("username", name);
RealmEntity realmEntity = em.getReference(RealmEntity.class, realm.getId()); query.setParameter("realmId", realm.getId());
query.setParameter("realm", realmEntity);
List<UserEntity> results = query.getResultList(); List<UserEntity> results = query.getResultList();
if (results.size() == 0) return false; if (results.size() == 0) return false;
removeUser(results.get(0)); removeUser(results.get(0));
@ -88,8 +82,8 @@ public class JpaUserProvider implements UserProvider {
} }
private void removeUser(UserEntity user) { private void removeUser(UserEntity user) {
em.createQuery("delete from " + UserRoleMappingEntity.class.getSimpleName() + " where user = :user").setParameter("user", user).executeUpdate(); em.createNamedQuery("deleteUserRoleMappingsByUser").setParameter("user", user).executeUpdate();
em.createQuery("delete from " + SocialLinkEntity.class.getSimpleName() + " where user = :user").setParameter("user", user).executeUpdate(); em.createNamedQuery("deleteSocialLinkByUser").setParameter("user", user).executeUpdate();
if (user.getAuthenticationLink() != null) { if (user.getAuthenticationLink() != null) {
for (AuthenticationLinkEntity l : user.getAuthenticationLink()) { for (AuthenticationLinkEntity l : user.getAuthenticationLink()) {
em.remove(l); em.remove(l);
@ -101,8 +95,7 @@ public class JpaUserProvider implements UserProvider {
@Override @Override
public void addSocialLink(RealmModel realm, UserModel user, SocialLinkModel socialLink) { public void addSocialLink(RealmModel realm, UserModel user, SocialLinkModel socialLink) {
SocialLinkEntity entity = new SocialLinkEntity(); SocialLinkEntity entity = new SocialLinkEntity();
RealmEntity realmEntity = em.getReference(RealmEntity.class, realm.getId()); entity.setRealmId(realm.getId());
entity.setRealm(realmEntity);
entity.setSocialProvider(socialLink.getSocialProvider()); entity.setSocialProvider(socialLink.getSocialProvider());
entity.setSocialUserId(socialLink.getSocialUserId()); entity.setSocialUserId(socialLink.getSocialUserId());
entity.setSocialUsername(socialLink.getSocialUsername()); entity.setSocialUsername(socialLink.getSocialUsername());
@ -128,57 +121,52 @@ public class JpaUserProvider implements UserProvider {
@Override @Override
public void preRemove(RealmModel realm) { public void preRemove(RealmModel realm) {
RealmEntity realmEntity = em.getReference(RealmEntity.class, realm.getId());
int num = em.createNamedQuery("deleteUserRoleMappingsByRealm") int num = em.createNamedQuery("deleteUserRoleMappingsByRealm")
.setParameter("realm", realmEntity).executeUpdate(); .setParameter("realmId", realm.getId()).executeUpdate();
num = em.createNamedQuery("deleteSocialLinkByRealm") num = em.createNamedQuery("deleteSocialLinkByRealm")
.setParameter("realm", realmEntity).executeUpdate(); .setParameter("realmId", realm.getId()).executeUpdate();
num = em.createNamedQuery("deleteCredentialsByRealm") num = em.createNamedQuery("deleteCredentialsByRealm")
.setParameter("realm", realmEntity).executeUpdate(); .setParameter("realmId", realm.getId()).executeUpdate();
num = em.createNamedQuery("deleteUserAttributesByRealm") num = em.createNamedQuery("deleteUserAttributesByRealm")
.setParameter("realm", realmEntity).executeUpdate(); .setParameter("realmId", realm.getId()).executeUpdate();
num = em.createNamedQuery("deleteAuthenticationLinksByRealm") num = em.createNamedQuery("deleteAuthenticationLinksByRealm")
.setParameter("realm", realmEntity).executeUpdate(); .setParameter("realmId", realm.getId()).executeUpdate();
num = em.createNamedQuery("deleteUsersByRealm") num = em.createNamedQuery("deleteUsersByRealm")
.setParameter("realm", realmEntity).executeUpdate(); .setParameter("realmId", realm.getId()).executeUpdate();
} }
@Override @Override
public void preRemove(RoleModel role) { public void preRemove(RoleModel role) {
RoleEntity roleEntity = em.getReference(RoleEntity.class, role.getId()); em.createNamedQuery("deleteUserRoleMappingsByRole").setParameter("roleId", role.getId()).executeUpdate();
em.createQuery("delete from " + UserRoleMappingEntity.class.getSimpleName() + " where role = :role").setParameter("role", roleEntity).executeUpdate();
} }
@Override @Override
public UserModel getUserById(String id, RealmModel realmModel) { public UserModel getUserById(String id, RealmModel realm) {
TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserById", UserEntity.class); TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserById", UserEntity.class);
query.setParameter("id", id); query.setParameter("id", id);
RealmEntity realm = em.getReference(RealmEntity.class, realmModel.getId()); query.setParameter("realmId", realm.getId());
query.setParameter("realm", realm);
List<UserEntity> entities = query.getResultList(); List<UserEntity> entities = query.getResultList();
if (entities.size() == 0) return null; if (entities.size() == 0) return null;
return new UserAdapter(realmModel, em, entities.get(0)); return new UserAdapter(realm, em, entities.get(0));
} }
@Override @Override
public UserModel getUserByUsername(String username, RealmModel realmModel) { public UserModel getUserByUsername(String username, RealmModel realm) {
TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserByUsername", UserEntity.class); TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserByUsername", UserEntity.class);
query.setParameter("username", username); query.setParameter("username", username);
RealmEntity realm = em.getReference(RealmEntity.class, realmModel.getId()); query.setParameter("realmId", realm.getId());
query.setParameter("realm", realm);
List<UserEntity> results = query.getResultList(); List<UserEntity> results = query.getResultList();
if (results.size() == 0) return null; if (results.size() == 0) return null;
return new UserAdapter(realmModel, em, results.get(0)); return new UserAdapter(realm, em, results.get(0));
} }
@Override @Override
public UserModel getUserByEmail(String email, RealmModel realmModel) { public UserModel getUserByEmail(String email, RealmModel realm) {
TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserByEmail", UserEntity.class); TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserByEmail", UserEntity.class);
query.setParameter("email", email); query.setParameter("email", email);
RealmEntity realm = em.getReference(RealmEntity.class, realmModel.getId()); query.setParameter("realmId", realm.getId());
query.setParameter("realm", realm);
List<UserEntity> results = query.getResultList(); List<UserEntity> results = query.getResultList();
return results.isEmpty() ? null : new UserAdapter(realmModel, em, results.get(0)); return results.isEmpty() ? null : new UserAdapter(realm, em, results.get(0));
} }
@Override @Override
@ -188,8 +176,7 @@ public class JpaUserProvider implements UserProvider {
@Override @Override
public UserModel getUserBySocialLink(SocialLinkModel socialLink, RealmModel realm) { public UserModel getUserBySocialLink(SocialLinkModel socialLink, RealmModel realm) {
TypedQuery<UserEntity> query = em.createNamedQuery("findUserByLinkAndRealm", UserEntity.class); TypedQuery<UserEntity> query = em.createNamedQuery("findUserByLinkAndRealm", UserEntity.class);
RealmEntity realmEntity = em.getReference(RealmEntity.class, realm.getId()); query.setParameter("realmId", realm.getId());
query.setParameter("realm", realmEntity);
query.setParameter("socialProvider", socialLink.getSocialProvider()); query.setParameter("socialProvider", socialLink.getSocialProvider());
query.setParameter("socialUserId", socialLink.getSocialUserId()); query.setParameter("socialUserId", socialLink.getSocialUserId());
List<UserEntity> results = query.getResultList(); List<UserEntity> results = query.getResultList();
@ -211,20 +198,17 @@ public class JpaUserProvider implements UserProvider {
@Override @Override
public int getUsersCount(RealmModel realm) { public int getUsersCount(RealmModel realm) {
RealmEntity realmEntity = em.getReference(RealmEntity.class, realm.getId());
// TODO: named query? // TODO: named query?
Object count = em.createQuery("select count(u) from UserEntity u where u.realm = :realm") Object count = em.createNamedQuery("getRealmUserCount")
.setParameter("realm", realmEntity) .setParameter("realmId", realm.getId())
.getSingleResult(); .getSingleResult();
return ((Number)count).intValue(); return ((Number)count).intValue();
} }
@Override @Override
public List<UserModel> getUsers(RealmModel realm, int firstResult, int maxResults) { public List<UserModel> getUsers(RealmModel realm, int firstResult, int maxResults) {
TypedQuery<UserEntity> query = em.createQuery("select u from UserEntity u where u.realm = :realm order by u.username", UserEntity.class); TypedQuery<UserEntity> query = em.createNamedQuery("getAllUsersByRealm", UserEntity.class);
RealmEntity realmEntity = em.getReference(RealmEntity.class, realm.getId()); query.setParameter("realmId", realm.getId());
query.setParameter("realm", realmEntity);
if (firstResult != -1) { if (firstResult != -1) {
query.setFirstResult(firstResult); query.setFirstResult(firstResult);
} }
@ -244,9 +228,8 @@ public class JpaUserProvider implements UserProvider {
@Override @Override
public List<UserModel> searchForUser(String search, RealmModel realm, int firstResult, int maxResults) { public List<UserModel> searchForUser(String search, RealmModel realm, int firstResult, int maxResults) {
TypedQuery<UserEntity> query = em.createQuery("select u from UserEntity u where u.realm = :realm and ( lower(u.username) like :search or lower(concat(u.firstName, ' ', u.lastName)) like :search or u.email like :search ) order by u.username", UserEntity.class); TypedQuery<UserEntity> query = em.createNamedQuery("searchForUser", UserEntity.class);
RealmEntity realmEntity = em.getReference(RealmEntity.class, realm.getId()); query.setParameter("realmId", realm.getId());
query.setParameter("realm", realmEntity);
query.setParameter("search", "%" + search.toLowerCase() + "%"); query.setParameter("search", "%" + search.toLowerCase() + "%");
if (firstResult != -1) { if (firstResult != -1) {
query.setFirstResult(firstResult); query.setFirstResult(firstResult);
@ -292,8 +275,7 @@ public class JpaUserProvider implements UserProvider {
builder.append(" order by u.username"); builder.append(" order by u.username");
String q = builder.toString(); String q = builder.toString();
TypedQuery<UserEntity> query = em.createQuery(q, UserEntity.class); TypedQuery<UserEntity> query = em.createQuery(q, UserEntity.class);
RealmEntity realmEntity = em.getReference(RealmEntity.class, realm.getId()); query.setParameter("realmId", realm.getId());
query.setParameter("realm", realmEntity);
if (firstResult != -1) { if (firstResult != -1) {
query.setFirstResult(firstResult); query.setFirstResult(firstResult);
} }

View file

@ -548,7 +548,7 @@ public class RealmAdapter implements RealmModel {
return false; return false;
} }
em.remove(applicationEntity); em.remove(applicationEntity);
em.createQuery("delete from " + ScopeMappingEntity.class.getSimpleName() + " where client = :client").setParameter("client", applicationEntity).executeUpdate(); em.createNamedQuery("deleteScopeMappingByClient").setParameter("client", applicationEntity).executeUpdate();
em.flush(); em.flush();
return true; return true;
@ -608,7 +608,7 @@ public class RealmAdapter implements RealmModel {
OAuthClientModel oauth = getOAuthClientById(id); OAuthClientModel oauth = getOAuthClientById(id);
if (oauth == null) return false; if (oauth == null) return false;
OAuthClientEntity client = em.getReference(OAuthClientEntity.class, oauth.getId()); OAuthClientEntity client = em.getReference(OAuthClientEntity.class, oauth.getId());
em.createQuery("delete from " + ScopeMappingEntity.class.getSimpleName() + " where client = :client").setParameter("client", client).executeUpdate(); em.createNamedQuery("deleteScopeMappingByClient").setParameter("client", client).executeUpdate();
em.remove(client); em.remove(client);
return true; return true;
} }
@ -769,8 +769,8 @@ public class RealmAdapter implements RealmModel {
realm.getRoles().remove(role); realm.getRoles().remove(role);
realm.getDefaultRoles().remove(role); realm.getDefaultRoles().remove(role);
em.createNativeQuery("delete from CompositeRole where childRole = :role").setParameter("role", roleEntity).executeUpdate(); em.createNativeQuery("delete from COMPOSITE_ROLE where CHILD_ROLE = :role").setParameter("role", roleEntity).executeUpdate();
em.createQuery("delete from " + ScopeMappingEntity.class.getSimpleName() + " where role = :role").setParameter("role", roleEntity).executeUpdate(); em.createNamedQuery("deleteScopeMappingByRole").setParameter("role", roleEntity).executeUpdate();
em.remove(roleEntity); em.remove(roleEntity);

View file

@ -11,11 +11,11 @@ import org.keycloak.models.UserCredentialValueModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.models.jpa.entities.AuthenticationLinkEntity; import org.keycloak.models.jpa.entities.AuthenticationLinkEntity;
import org.keycloak.models.jpa.entities.CredentialEntity; import org.keycloak.models.jpa.entities.CredentialEntity;
import org.keycloak.models.jpa.entities.RoleEntity;
import org.keycloak.models.jpa.entities.UserAttributeEntity; import org.keycloak.models.jpa.entities.UserAttributeEntity;
import org.keycloak.models.jpa.entities.UserEntity; import org.keycloak.models.jpa.entities.UserEntity;
import org.keycloak.models.jpa.entities.UserRequiredActionEntity; import org.keycloak.models.jpa.entities.UserRequiredActionEntity;
import org.keycloak.models.jpa.entities.UserRoleMappingEntity; import org.keycloak.models.jpa.entities.UserRoleMappingEntity;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.models.utils.Pbkdf2PasswordEncoder; import org.keycloak.models.utils.Pbkdf2PasswordEncoder;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
@ -216,6 +216,7 @@ public class UserAdapter implements UserModel {
if (credentialEntity == null) { if (credentialEntity == null) {
credentialEntity = new CredentialEntity(); credentialEntity = new CredentialEntity();
credentialEntity.setId(KeycloakModelUtils.generateId());
credentialEntity.setType(cred.getType()); credentialEntity.setType(cred.getType());
credentialEntity.setDevice(cred.getDevice()); credentialEntity.setDevice(cred.getDevice());
credentialEntity.setUser(user); credentialEntity.setUser(user);
@ -277,6 +278,7 @@ public class UserAdapter implements UserModel {
if (credentialEntity == null) { if (credentialEntity == null) {
credentialEntity = new CredentialEntity(); credentialEntity = new CredentialEntity();
credentialEntity.setId(KeycloakModelUtils.generateId());
credentialEntity.setType(credModel.getType()); credentialEntity.setType(credModel.getType());
credentialEntity.setUser(user); credentialEntity.setUser(user);
em.persist(credentialEntity); em.persist(credentialEntity);
@ -305,8 +307,7 @@ public class UserAdapter implements UserModel {
protected TypedQuery<UserRoleMappingEntity> getUserRoleMappingEntityTypedQuery(RoleModel role) { protected TypedQuery<UserRoleMappingEntity> getUserRoleMappingEntityTypedQuery(RoleModel role) {
TypedQuery<UserRoleMappingEntity> query = em.createNamedQuery("userHasRole", UserRoleMappingEntity.class); TypedQuery<UserRoleMappingEntity> query = em.createNamedQuery("userHasRole", UserRoleMappingEntity.class);
query.setParameter("user", getUser()); query.setParameter("user", getUser());
RoleEntity roleEntity = em.getReference(RoleEntity.class, role.getId()); query.setParameter("roleId", role.getId());
query.setParameter("role", roleEntity);
return query; return query;
} }
@ -315,8 +316,7 @@ public class UserAdapter implements UserModel {
if (hasRole(role)) return; if (hasRole(role)) return;
UserRoleMappingEntity entity = new UserRoleMappingEntity(); UserRoleMappingEntity entity = new UserRoleMappingEntity();
entity.setUser(getUser()); entity.setUser(getUser());
RoleEntity roleEntity = em.getReference(RoleEntity.class, role.getId()); entity.setRoleId(role.getId());
entity.setRole(roleEntity);
em.persist(entity); em.persist(entity);
em.flush(); em.flush();
em.detach(entity); em.detach(entity);

View file

@ -1,10 +1,12 @@
package org.keycloak.models.jpa.entities; package org.keycloak.models.jpa.entities;
import javax.persistence.CascadeType; import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType; import javax.persistence.FetchType;
import javax.persistence.JoinTable; import javax.persistence.JoinTable;
import javax.persistence.OneToMany; import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@ -15,16 +17,23 @@ import java.util.Collection;
@Entity @Entity
public class ApplicationEntity extends ClientEntity { public class ApplicationEntity extends ClientEntity {
@Column(name="SURROGATE_AUTH_REQUIRED")
private boolean surrogateAuthRequired; private boolean surrogateAuthRequired;
@Column(name="BASE_URL")
private String baseUrl; private String baseUrl;
@Column(name="MANAGEMENT_URL")
private String managementUrl; private String managementUrl;
@Column(name="BEARER_ONLY")
private boolean bearerOnly; private boolean bearerOnly;
@OneToMany(fetch = FetchType.EAGER, cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "application") @OneToMany(fetch = FetchType.EAGER, cascade ={CascadeType.REMOVE}, orphanRemoval = true, mappedBy = "application")
Collection<RoleEntity> roles = new ArrayList<RoleEntity>(); Collection<RoleEntity> roles = new ArrayList<RoleEntity>();
@OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true) @OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true)
@JoinTable(name="ApplicationDefaultRoles") @JoinTable(name="APPLICATION_DEFAULT_ROLES")
Collection<RoleEntity> defaultRoles = new ArrayList<RoleEntity>(); Collection<RoleEntity> defaultRoles = new ArrayList<RoleEntity>();
public boolean isSurrogateAuthRequired() { public boolean isSurrogateAuthRequired() {

View file

@ -1,5 +1,6 @@
package org.keycloak.models.jpa.entities; package org.keycloak.models.jpa.entities;
import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType; import javax.persistence.FetchType;
import javax.persistence.Id; import javax.persistence.Id;
@ -9,20 +10,24 @@ import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries; import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery; import javax.persistence.NamedQuery;
import javax.persistence.OneToMany; import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.io.Serializable; import java.io.Serializable;
/** /**
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
*/ */
@NamedQueries({ @NamedQueries({
@NamedQuery(name="deleteAuthenticationLinksByRealm", query="delete from AuthenticationLinkEntity authLink where authLink.user IN (select u from UserEntity u where realm=:realm)") @NamedQuery(name="deleteAuthenticationLinksByRealm", query="delete from AuthenticationLinkEntity authLink where authLink.user IN (select u from UserEntity u where u.realmId=:realmId)")
}) })
@Table(name="AUTHENTICATION_LINK")
@Entity @Entity
@IdClass(AuthenticationLinkEntity.Key.class) @IdClass(AuthenticationLinkEntity.Key.class)
public class AuthenticationLinkEntity { public class AuthenticationLinkEntity {
@Id @Id
@Column(name="AUTH_PROVIDER")
protected String authProvider; protected String authProvider;
@Column(name="AUTH_USER_ID")
protected String authUserId; protected String authUserId;
// NOTE: @OnetoOne creates a constraint race condition if the join column is on AuthenticationLinkEntity. // NOTE: @OnetoOne creates a constraint race condition if the join column is on AuthenticationLinkEntity.
@ -30,7 +35,7 @@ public class AuthenticationLinkEntity {
// a @ManyToOne on both sides. Broken yes, but, I think we're going to replace AuthenticationLinkEntity anyways. // a @ManyToOne on both sides. Broken yes, but, I think we're going to replace AuthenticationLinkEntity anyways.
@Id @Id
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="userId") @JoinColumn(name="USER_ID")
protected UserEntity user; protected UserEntity user;
public String getAuthProvider() { public String getAuthProvider() {

View file

@ -18,23 +18,27 @@ import java.util.Map;
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
*/ */
@Entity @Entity
@Table(name="AuthProviderEntity") @Table(name="AUTH_PROVIDER_ENTITY")
@IdClass(AuthenticationProviderEntity.Key.class) @IdClass(AuthenticationProviderEntity.Key.class)
public class AuthenticationProviderEntity { public class AuthenticationProviderEntity {
@Id @Id
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "REALM_ID")
protected RealmEntity realm; protected RealmEntity realm;
@Id @Id
@Column(name="PROVIDER_NAME")
private String providerName; private String providerName;
@Column(name="PASSWORD_UPDATE_SUPPORTED")
private boolean passwordUpdateSupported; private boolean passwordUpdateSupported;
@Column(name="PRIORITY")
private int priority; private int priority;
@ElementCollection @ElementCollection
@MapKeyColumn(name="name") @MapKeyColumn(name="name")
@Column(name="value") @Column(name="value")
@CollectionTable(name="AuthProviderEntity_cfg") @CollectionTable(name="AUTH_PROVIDER_CONFIG")
private Map<String, String> config; private Map<String, String> config;
public RealmEntity getRealm() { public RealmEntity getRealm() {

View file

@ -21,28 +21,34 @@ import java.util.Set;
*/ */
@Entity @Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE) @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"realm", "name"})}) @Table(name="CLIENT", uniqueConstraints = {@UniqueConstraint(columnNames = {"REALM_ID", "NAME"})})
public abstract class ClientEntity { public abstract class ClientEntity {
@Id @Id
@Column(length = 36) @Column(name="ID", length = 36)
private String id; private String id;
@Column(name = "name") @Column(name = "NAME")
private String name; private String name;
@Column(name="ENABLED")
private boolean enabled; private boolean enabled;
@Column(name="SECRET")
private String secret; private String secret;
@Column(name="ALLOWED_CLAIMS_MASK")
private long allowedClaimsMask; private long allowedClaimsMask;
@Column(name="NOT_BEFORE")
private int notBefore; private int notBefore;
@Column(name="PUBLIC_CLIENT")
private boolean publicClient; private boolean publicClient;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "realm") @JoinColumn(name = "REALM_ID")
protected RealmEntity realm; protected RealmEntity realm;
@ElementCollection @ElementCollection
@CollectionTable @CollectionTable(name = "WEB_ORIGINS")
protected Set<String> webOrigins = new HashSet<String>(); protected Set<String> webOrigins = new HashSet<String>();
@ElementCollection @ElementCollection
@CollectionTable @CollectionTable(name = "REDIRECT_URIS")
protected Set<String> redirectUris = new HashSet<String>(); protected Set<String> redirectUris = new HashSet<String>();
public RealmEntity getRealm() { public RealmEntity getRealm() {

View file

@ -1,5 +1,6 @@
package org.keycloak.models.jpa.entities; package org.keycloak.models.jpa.entities;
import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType; import javax.persistence.FetchType;
import javax.persistence.Id; import javax.persistence.Id;
@ -8,6 +9,7 @@ import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries; import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery; import javax.persistence.NamedQuery;
import javax.persistence.Table;
import java.io.Serializable; import java.io.Serializable;
/** /**
@ -16,25 +18,39 @@ import java.io.Serializable;
*/ */
@NamedQueries({ @NamedQueries({
@NamedQuery(name="credentialByUserAndType", query="select cred from CredentialEntity cred where cred.user = :user and cred.type = :type"), @NamedQuery(name="credentialByUserAndType", query="select cred from CredentialEntity cred where cred.user = :user and cred.type = :type"),
@NamedQuery(name="deleteCredentialsByRealm", query="delete from CredentialEntity cred where cred.user IN (select u from UserEntity u where realm=:realm)") @NamedQuery(name="deleteCredentialsByRealm", query="delete from CredentialEntity cred where cred.user IN (select u from UserEntity u where u.realmId=:realmId)")
}) })
@Table(name="CREDENTIAL")
@Entity @Entity
@IdClass(CredentialEntity.Key.class)
public class CredentialEntity { public class CredentialEntity {
@Id @Id
@Column(length = 36)
protected String id;
@Column(name="TYPE")
protected String type; protected String type;
@Column(name="VALUE")
protected String value; protected String value;
@Column(name="DEVICE")
protected String device; protected String device;
@Column(name="SALT")
protected byte[] salt; protected byte[] salt;
@Column(name="HASH_ITERATIONS")
protected int hashIterations; protected int hashIterations;
@Id
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="userId") @JoinColumn(name="USER_ID")
protected UserEntity user; protected UserEntity user;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue() { public String getValue() {
return value; return value;
} }
@ -82,48 +98,4 @@ public class CredentialEntity {
public void setHashIterations(int hashIterations) { public void setHashIterations(int hashIterations) {
this.hashIterations = hashIterations; this.hashIterations = hashIterations;
} }
public static class Key implements Serializable {
protected UserEntity user;
protected String type;
public Key() {
}
public Key(UserEntity user, String type) {
this.user = user;
this.type = type;
}
public UserEntity getUser() {
return user;
}
public String getType() {
return type;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Key key = (Key) o;
if (type != null ? !type.equals(key.type) : key.type != null) return false;
if (user != null ? !user.getId().equals(key.user != null ? key.user.getId() : null) : key.user != null) return false;
return true;
}
@Override
public int hashCode() {
int result = user != null ? user.getId().hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
return result;
}
}
} }

View file

@ -1,6 +1,8 @@
package org.keycloak.models.jpa.entities; package org.keycloak.models.jpa.entities;
import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries; import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery; import javax.persistence.NamedQuery;
@ -15,6 +17,7 @@ import javax.persistence.NamedQuery;
}) })
@Entity @Entity
public class OAuthClientEntity extends ClientEntity { public class OAuthClientEntity extends ClientEntity {
@Column(name="DIRECT_GRANTS_ONLY")
protected boolean directGrantsOnly; protected boolean directGrantsOnly;
public boolean isDirectGrantsOnly() { public boolean isDirectGrantsOnly() {

View file

@ -8,12 +8,14 @@ import javax.persistence.ElementCollection;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType; import javax.persistence.FetchType;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable; import javax.persistence.JoinTable;
import javax.persistence.MapKeyColumn; import javax.persistence.MapKeyColumn;
import javax.persistence.NamedQueries; import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery; import javax.persistence.NamedQuery;
import javax.persistence.OneToMany; import javax.persistence.OneToMany;
import javax.persistence.OneToOne; import javax.persistence.OneToOne;
import javax.persistence.Table;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
@ -26,6 +28,7 @@ import java.util.Set;
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $ * @version $Revision: 1 $
*/ */
@Table(name="REALM")
@Entity @Entity
@NamedQueries({ @NamedQueries({
@NamedQuery(name="getAllRealms", query="select realm from RealmEntity realm"), @NamedQuery(name="getAllRealms", query="select realm from RealmEntity realm"),
@ -33,59 +36,85 @@ import java.util.Set;
}) })
public class RealmEntity { public class RealmEntity {
@Id @Id
@Column(length = 36) @Column(name="ID", length = 36)
protected String id; protected String id;
@Column(unique = true) @Column(name="NAME", unique = true)
protected String name; protected String name;
@Column(name="ENABLED")
protected boolean enabled; protected boolean enabled;
@Column(name="SSL_NOT_REQUIRED")
protected boolean sslNotRequired; protected boolean sslNotRequired;
@Column(name="REGISTRATION_ALLOWED")
protected boolean registrationAllowed; protected boolean registrationAllowed;
@Column(name="PASSWORD_CRED_GRANT_ALLOWED")
protected boolean passwordCredentialGrantAllowed; protected boolean passwordCredentialGrantAllowed;
@Column(name="VERIFY_EMAIL")
protected boolean verifyEmail; protected boolean verifyEmail;
@Column(name="RESET_PASSWORD_ALLOWED")
protected boolean resetPasswordAllowed; protected boolean resetPasswordAllowed;
@Column(name="SOCIAL")
protected boolean social; protected boolean social;
@Column(name="REMEMBER_ME")
protected boolean rememberMe; protected boolean rememberMe;
//--- brute force settings //--- brute force settings
@Column(name="BRUTE_FORCE_PROTECTED")
protected boolean bruteForceProtected; protected boolean bruteForceProtected;
@Column(name="MAX_FAILURE_WAIT")
protected int maxFailureWaitSeconds; protected int maxFailureWaitSeconds;
@Column(name="MINIMUM_QUICK_LOGIN_WAIT")
protected int minimumQuickLoginWaitSeconds; protected int minimumQuickLoginWaitSeconds;
@Column(name="WAIT_INCREMENT_SECONDS")
protected int waitIncrementSeconds; protected int waitIncrementSeconds;
@Column(name="QUICK_LOGIN_CHECK")
protected long quickLoginCheckMilliSeconds; protected long quickLoginCheckMilliSeconds;
@Column(name="MAX_DELTA_TIME")
protected int maxDeltaTimeSeconds; protected int maxDeltaTimeSeconds;
@Column(name="FAILURE_FACTOR")
protected int failureFactor; protected int failureFactor;
//--- end brute force settings //--- end brute force settings
@Column(name="updateProfileOnInitSocLogin") @Column(name="UPDATE_PROFILE_ON_SOC_LOGIN")
protected boolean updateProfileOnInitialSocialLogin; protected boolean updateProfileOnInitialSocialLogin;
@Column(name="PASSWORD_POLICY")
protected String passwordPolicy; protected String passwordPolicy;
@Column(name="SSO_IDLE_TIMEOUT")
private int ssoSessionIdleTimeout; private int ssoSessionIdleTimeout;
@Column(name="SSO_MAX_LIFESPAN")
private int ssoSessionMaxLifespan; private int ssoSessionMaxLifespan;
@Column(name="ACCESS_TOKEN_LIFESPAN")
protected int accessTokenLifespan; protected int accessTokenLifespan;
@Column(name="ACCESS_CODE_LIFESPAN")
protected int accessCodeLifespan; protected int accessCodeLifespan;
@Column(name="USER_ACTION_LIFESPAN")
protected int accessCodeLifespanUserAction; protected int accessCodeLifespanUserAction;
@Column(name="NOT_BEFORE")
protected int notBefore; protected int notBefore;
@Column(length = 2048) @Column(name="PUBLIC_KEY", length = 2048)
protected String publicKeyPem; protected String publicKeyPem;
@Column(length = 2048) @Column(name="PRIVATE_KEY", length = 2048)
protected String privateKeyPem; protected String privateKeyPem;
@Column(name="LOGIN_THEME")
protected String loginTheme; protected String loginTheme;
@Column(name="ACCOUNT_THEME")
protected String accountTheme; protected String accountTheme;
@Column(name="ADMIN_THEME")
protected String adminTheme; protected String adminTheme;
@Column(name="EMAIL_THEME")
protected String emailTheme; protected String emailTheme;
@OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true) @OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true)
@JoinTable(name="User_RequiredCreds") @JoinTable(name="USER_REQUIRED_CREDS")
Collection<RequiredCredentialEntity> requiredCredentials = new ArrayList<RequiredCredentialEntity>(); Collection<RequiredCredentialEntity> requiredCredentials = new ArrayList<RequiredCredentialEntity>();
@OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true) @OneToMany(cascade ={CascadeType.REMOVE}, orphanRemoval = true)
@JoinTable(name="AuthProviders") @JoinTable(name="AUTH_PROVIDERS")
List<AuthenticationProviderEntity> authenticationProviders = new ArrayList<AuthenticationProviderEntity>(); List<AuthenticationProviderEntity> authenticationProviders = new ArrayList<AuthenticationProviderEntity>();
@OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true) @OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true)
@ -97,32 +126,36 @@ public class RealmEntity {
@ElementCollection @ElementCollection
@MapKeyColumn(name="name") @MapKeyColumn(name="name")
@Column(name="value") @Column(name="value")
@CollectionTable @CollectionTable(name="REALM_SMTP_CONFIG")
protected Map<String, String> smtpConfig = new HashMap<String, String>(); protected Map<String, String> smtpConfig = new HashMap<String, String>();
@ElementCollection @ElementCollection
@MapKeyColumn(name="name") @MapKeyColumn(name="name")
@Column(name="value") @Column(name="value")
@CollectionTable @CollectionTable(name="REALM_SOCIAL_CONFIG")
protected Map<String, String> socialConfig = new HashMap<String, String>(); protected Map<String, String> socialConfig = new HashMap<String, String>();
@ElementCollection @ElementCollection
@MapKeyColumn(name="name") @MapKeyColumn(name="name")
@Column(name="value") @Column(name="value")
@CollectionTable @CollectionTable(name="REALM_LDAP_CONFIG")
protected Map<String, String> ldapServerConfig = new HashMap<String, String>(); protected Map<String, String> ldapServerConfig = new HashMap<String, String>();
@OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true) @OneToMany(fetch = FetchType.LAZY, cascade ={CascadeType.REMOVE}, orphanRemoval = true)
@JoinTable(name="RealmDefaultRoles") @JoinTable(name="REALM_DEFAULT_ROLES")
protected Collection<RoleEntity> defaultRoles = new ArrayList<RoleEntity>(); protected Collection<RoleEntity> defaultRoles = new ArrayList<RoleEntity>();
@Column(name="AUDIT_ENABLED")
protected boolean auditEnabled; protected boolean auditEnabled;
@Column(name="AUDIT_EXPIRATION")
protected long auditExpiration; protected long auditExpiration;
@ElementCollection @ElementCollection
@CollectionTable(name="REALM_AUDIT_LISTENERS")
protected Set<String> auditListeners= new HashSet<String>(); protected Set<String> auditListeners= new HashSet<String>();
@OneToOne @OneToOne
@JoinColumn(name="MASTER_ADMIN_APP")
protected ApplicationEntity masterAdminApp; protected ApplicationEntity masterAdminApp;
public String getId() { public String getId() {

View file

@ -1,30 +1,37 @@
package org.keycloak.models.jpa.entities; package org.keycloak.models.jpa.entities;
import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType; import javax.persistence.FetchType;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.IdClass; import javax.persistence.IdClass;
import javax.persistence.JoinColumn; import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.Table;
import java.io.Serializable; import java.io.Serializable;
/** /**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $ * @version $Revision: 1 $
*/ */
@Table(name="REALM_REQUIRED_CREDENTIAL")
@Entity @Entity
@IdClass(RequiredCredentialEntity.Key.class) @IdClass(RequiredCredentialEntity.Key.class)
public class RequiredCredentialEntity { public class RequiredCredentialEntity {
@Id @Id
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "realm") @JoinColumn(name = "REALM_ID")
protected RealmEntity realm; protected RealmEntity realm;
@Id @Id
@Column(name = "TYPE")
protected String type; protected String type;
@Column(name = "INPUT")
protected boolean input; protected boolean input;
@Column(name = "SECRET")
protected boolean secret; protected boolean secret;
@Column(name = "FORM_LABEL")
protected String formLabel; protected String formLabel;
public RealmEntity getRealm() { public RealmEntity getRealm() {

View file

@ -20,8 +20,8 @@ import java.util.Collection;
* @version $Revision: 1 $ * @version $Revision: 1 $
*/ */
@Entity @Entity
@Table(uniqueConstraints = { @Table(name="KEYCLOAK_ROLE", uniqueConstraints = {
@UniqueConstraint(columnNames = { "name", "appRealmConstraint" }) @UniqueConstraint(columnNames = { "NAME", "APP_REALM_CONSTRAINT" })
}) })
@NamedQueries({ @NamedQueries({
@NamedQuery(name="getAppRoleByName", query="select role from RoleEntity role where role.name = :name and role.application = :application"), @NamedQuery(name="getAppRoleByName", query="select role from RoleEntity role where role.name = :name and role.application = :application"),
@ -33,29 +33,32 @@ public class RoleEntity {
@Column(name="id", length = 36) @Column(name="id", length = 36)
private String id; private String id;
@Column(name = "NAME")
private String name; private String name;
@Column(name = "DESCRIPTION")
private String description; private String description;
// hax! couldn't get constraint to work properly // hax! couldn't get constraint to work properly
@Column(name = "REALM_ID")
private String realmId; private String realmId;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "realm") @JoinColumn(name = "REALM")
private RealmEntity realm; private RealmEntity realm;
@Column(name="applicationRole") @Column(name="APPLICATION_ROLE")
private boolean applicationRole; private boolean applicationRole;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "application") @JoinColumn(name = "APPLICATION")
private ApplicationEntity application; private ApplicationEntity application;
// Hack to ensure that either name+application or name+realm are unique. Needed due to MS-SQL as it don't allow multiple NULL values in the column, which is part of constraint // Hack to ensure that either name+application or name+realm are unique. Needed due to MS-SQL as it don't allow multiple NULL values in the column, which is part of constraint
@Column(length = 36) @Column(name="APP_REALM_CONSTRAINT", length = 36)
private String appRealmConstraint; private String appRealmConstraint;
@ManyToMany(fetch = FetchType.LAZY, cascade = {}) @ManyToMany(fetch = FetchType.LAZY, cascade = {})
@JoinTable(name = "CompositeRole", joinColumns = @JoinColumn(name = "composite"), inverseJoinColumns = @JoinColumn(name = "childRole")) @JoinTable(name = "COMPOSITE_ROLE", joinColumns = @JoinColumn(name = "COMPOSITE"), inverseJoinColumns = @JoinColumn(name = "CHILD_ROLE"))
private Collection<RoleEntity> compositeRoles = new ArrayList<RoleEntity>(); private Collection<RoleEntity> compositeRoles = new ArrayList<RoleEntity>();
public String getId() { public String getId() {

View file

@ -1,5 +1,6 @@
package org.keycloak.models.jpa.entities; package org.keycloak.models.jpa.entities;
import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType; import javax.persistence.FetchType;
import javax.persistence.Id; import javax.persistence.Id;
@ -8,6 +9,7 @@ import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries; import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery; import javax.persistence.NamedQuery;
import javax.persistence.Table;
import java.io.Serializable; import java.io.Serializable;
/** /**
@ -17,19 +19,23 @@ import java.io.Serializable;
@NamedQueries({ @NamedQueries({
@NamedQuery(name="hasScope", query="select m from ScopeMappingEntity m where m.client = :client and m.role = :role"), @NamedQuery(name="hasScope", query="select m from ScopeMappingEntity m where m.client = :client and m.role = :role"),
@NamedQuery(name="clientScopeMappings", query="select m from ScopeMappingEntity m where m.client = :client"), @NamedQuery(name="clientScopeMappings", query="select m from ScopeMappingEntity m where m.client = :client"),
@NamedQuery(name="clientScopeMappingIds", query="select m.role.id from ScopeMappingEntity m where m.client = :client") @NamedQuery(name="clientScopeMappingIds", query="select m.role.id from ScopeMappingEntity m where m.client = :client"),
@NamedQuery(name="deleteScopeMappingByRole", query="delete from ScopeMappingEntity where role = :role"),
@NamedQuery(name="deleteScopeMappingByClient", query="delete from ScopeMappingEntity where client = :client")
}) })
@Table(name="SCOPE_MAPPING")
@Entity @Entity
@IdClass(ScopeMappingEntity.Key.class) @IdClass(ScopeMappingEntity.Key.class)
public class ScopeMappingEntity { public class ScopeMappingEntity {
@Id @Id
@ManyToOne(fetch= FetchType.LAZY) @ManyToOne(fetch= FetchType.LAZY)
@JoinColumn(name = "CLIENT_ID")
protected ClientEntity client; protected ClientEntity client;
@Id @Id
@ManyToOne(fetch= FetchType.LAZY) @ManyToOne(fetch= FetchType.LAZY)
@JoinColumn(name="roleId") @JoinColumn(name="ROLE_ID")
protected RoleEntity role; protected RoleEntity role;
public ClientEntity getClient() { public ClientEntity getClient() {

View file

@ -1,12 +1,15 @@
package org.keycloak.models.jpa.entities; package org.keycloak.models.jpa.entities;
import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType; import javax.persistence.FetchType;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.IdClass; import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries; import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery; import javax.persistence.NamedQuery;
import javax.persistence.Table;
import java.io.Serializable; import java.io.Serializable;
/** /**
@ -16,23 +19,29 @@ import java.io.Serializable;
@NamedQueries({ @NamedQueries({
@NamedQuery(name="findSocialLinkByUser", query="select link from SocialLinkEntity link where link.user = :user"), @NamedQuery(name="findSocialLinkByUser", query="select link from SocialLinkEntity link where link.user = :user"),
@NamedQuery(name="findSocialLinkByUserAndProvider", query="select link from SocialLinkEntity link where link.user = :user and link.socialProvider = :socialProvider"), @NamedQuery(name="findSocialLinkByUserAndProvider", query="select link from SocialLinkEntity link where link.user = :user and link.socialProvider = :socialProvider"),
@NamedQuery(name="findUserByLinkAndRealm", query="select link.user from SocialLinkEntity link where link.realm = :realm and link.socialProvider = :socialProvider and link.socialUserId = :socialUserId"), @NamedQuery(name="findUserByLinkAndRealm", query="select link.user from SocialLinkEntity link where link.realmId = :realmId and link.socialProvider = :socialProvider and link.socialUserId = :socialUserId"),
@NamedQuery(name="deleteSocialLinkByRealm", query="delete from SocialLinkEntity social where social.user IN (select u from UserEntity u where realm=:realm)") @NamedQuery(name="deleteSocialLinkByRealm", query="delete from SocialLinkEntity social where social.user IN (select u from UserEntity u where realmId=:realmId)"),
@NamedQuery(name="deleteSocialLinkByUser", query="delete from SocialLinkEntity social where social.user = :user")
}) })
@Table(name="USER_SOCIAL_LINK")
@Entity @Entity
@IdClass(SocialLinkEntity.Key.class) @IdClass(SocialLinkEntity.Key.class)
public class SocialLinkEntity { public class SocialLinkEntity {
@Id @Id
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "USER_ID")
private UserEntity user; private UserEntity user;
@ManyToOne(fetch = FetchType.LAZY) @Column(name = "REALM_ID")
protected RealmEntity realm; protected String realmId;
@Id @Id
@Column(name = "SOCIAL_PROVIDER")
protected String socialProvider; protected String socialProvider;
@Column(name = "SOCIAL_USER_ID")
protected String socialUserId; protected String socialUserId;
@Column(name = "SOCIAL_USERNAME")
protected String socialUsername; protected String socialUsername;
public UserEntity getUser() { public UserEntity getUser() {
@ -67,12 +76,12 @@ public class SocialLinkEntity {
this.socialUsername = socialUsername; this.socialUsername = socialUsername;
} }
public RealmEntity getRealm() { public String getRealmId() {
return realm; return realmId;
} }
public void setRealm(RealmEntity realm) { public void setRealmId(String realmId) {
this.realm = realm; this.realmId = realmId;
} }
public static class Key implements Serializable { public static class Key implements Serializable {

View file

@ -1,12 +1,15 @@
package org.keycloak.models.jpa.entities; package org.keycloak.models.jpa.entities;
import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType; import javax.persistence.FetchType;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.IdClass; import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries; import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery; import javax.persistence.NamedQuery;
import javax.persistence.Table;
import java.io.Serializable; import java.io.Serializable;
/** /**
@ -14,18 +17,22 @@ import java.io.Serializable;
* @version $Revision: 1 $ * @version $Revision: 1 $
*/ */
@NamedQueries({ @NamedQueries({
@NamedQuery(name="deleteUserAttributesByRealm", query="delete from UserAttributeEntity attr where attr.user IN (select u from UserEntity u where realm=:realm)") @NamedQuery(name="deleteUserAttributesByRealm", query="delete from UserAttributeEntity attr where attr.user IN (select u from UserEntity u where u.realmId=:realmId)")
}) })
@Table(name="USER_ATTRIBUTE")
@Entity @Entity
@IdClass(UserAttributeEntity.Key.class) @IdClass(UserAttributeEntity.Key.class)
public class UserAttributeEntity { public class UserAttributeEntity {
@Id @Id
@ManyToOne(fetch= FetchType.LAZY) @ManyToOne(fetch= FetchType.LAZY)
@JoinColumn(name = "USER_ID")
protected UserEntity user; protected UserEntity user;
@Id @Id
@Column(name = "NAME")
protected String name; protected String name;
@Column(name = "VALUE")
protected String value; protected String value;
public String getName() { public String getName() {

View file

@ -31,37 +31,47 @@ import java.util.Set;
* @version $Revision: 1 $ * @version $Revision: 1 $
*/ */
@NamedQueries({ @NamedQueries({
@NamedQuery(name="getRealmUserById", query="select u from UserEntity u where u.id = :id and u.realm = :realm"), @NamedQuery(name="getAllUsersByRealm", query="select u from UserEntity u where u.realmId = :realmId order by u.username"),
@NamedQuery(name="getRealmUserByUsername", query="select u from UserEntity u where u.username = :username and u.realm = :realm"), @NamedQuery(name="searchForUser", query="select u from UserEntity u where u.realmId = :realmId and ( lower(u.username) like :search or lower(concat(u.firstName, ' ', u.lastName)) like :search or u.email like :search ) order by u.username"),
@NamedQuery(name="getRealmUserByEmail", query="select u from UserEntity u where u.email = :email and u.realm = :realm"), @NamedQuery(name="getRealmUserById", query="select u from UserEntity u where u.id = :id and u.realmId = :realmId"),
@NamedQuery(name="getRealmUserByLastName", query="select u from UserEntity u where u.lastName = :lastName and u.realm = :realm"), @NamedQuery(name="getRealmUserByUsername", query="select u from UserEntity u where u.username = :username and u.realmId = :realmId"),
@NamedQuery(name="getRealmUserByFirstLastName", query="select u from UserEntity u where u.firstName = :first and u.lastName = :last and u.realm = :realm"), @NamedQuery(name="getRealmUserByEmail", query="select u from UserEntity u where u.email = :email and u.realmId = :realmId"),
@NamedQuery(name="deleteUsersByRealm", query="delete from UserEntity u where u.realm = :realm") @NamedQuery(name="getRealmUserByLastName", query="select u from UserEntity u where u.lastName = :lastName and u.realmId = :realmId"),
@NamedQuery(name="getRealmUserByFirstLastName", query="select u from UserEntity u where u.firstName = :first and u.lastName = :last and u.realmId = :realmId"),
@NamedQuery(name="getRealmUserCount", query="select count(u) from UserEntity u where u.realmId = :realmId"),
@NamedQuery(name="deleteUsersByRealm", query="delete from UserEntity u where u.realmId = :realmId")
}) })
@Entity @Entity
@Table(uniqueConstraints = { @Table(name="USER", uniqueConstraints = {
@UniqueConstraint(columnNames = { "realm", "username" }), @UniqueConstraint(columnNames = { "REALM_ID", "USERNAME" }),
@UniqueConstraint(columnNames = { "realm", "emailConstraint" }) @UniqueConstraint(columnNames = { "REALM_ID", "EMAIL_CONSTRAINT" })
}) })
public class UserEntity { public class UserEntity {
@Id @Id
@Column(length = 36) @Column(name="ID", length = 36)
protected String id; protected String id;
@Column(name = "USERNAME")
protected String username; protected String username;
@Column(name = "FIRST_NAME")
protected String firstName; protected String firstName;
@Column(name = "LAST_NAME")
protected String lastName; protected String lastName;
@Column(name = "EMAIL")
protected String email; protected String email;
@Column(name = "ENABLED")
protected boolean enabled; protected boolean enabled;
@Column(name = "TOTP")
protected boolean totp; protected boolean totp;
@Column(name = "EMAIL_VERIFIED")
protected boolean emailVerified; protected boolean emailVerified;
// Hack just to workaround the fact that on MS-SQL you can't have unique constraint with multiple NULL values TODO: Find better solution (like unique index with 'where' but that's proprietary) // Hack just to workaround the fact that on MS-SQL you can't have unique constraint with multiple NULL values TODO: Find better solution (like unique index with 'where' but that's proprietary)
@Column(name = "EMAIL_CONSTRAINT")
protected String emailConstraint = KeycloakModelUtils.generateId(); protected String emailConstraint = KeycloakModelUtils.generateId();
@ManyToOne(fetch = FetchType.LAZY) @Column(name = "REALM_ID")
@JoinColumn(name = "realm") protected String realmId;
protected RealmEntity realm;
@OneToMany(cascade = CascadeType.REMOVE, orphanRemoval = true, mappedBy="user") @OneToMany(cascade = CascadeType.REMOVE, orphanRemoval = true, mappedBy="user")
protected Collection<UserAttributeEntity> attributes = new ArrayList<UserAttributeEntity>(); protected Collection<UserAttributeEntity> attributes = new ArrayList<UserAttributeEntity>();
@ -164,12 +174,12 @@ public class UserEntity {
this.requiredActions = requiredActions; this.requiredActions = requiredActions;
} }
public RealmEntity getRealm() { public String getRealmId() {
return realm; return realmId;
} }
public void setRealm(RealmEntity realm) { public void setRealmId(String realmId) {
this.realm = realm; this.realmId = realmId;
} }
public Collection<CredentialEntity> getCredentials() { public Collection<CredentialEntity> getCredentials() {

View file

@ -1,5 +1,6 @@
package org.keycloak.models.jpa.entities; package org.keycloak.models.jpa.entities;
import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType; import javax.persistence.FetchType;
import javax.persistence.Id; import javax.persistence.Id;
@ -8,6 +9,7 @@ import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries; import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery; import javax.persistence.NamedQuery;
import javax.persistence.Table;
import java.io.Serializable; import java.io.Serializable;
/** /**
@ -15,25 +17,27 @@ import java.io.Serializable;
* @version $Revision: 1 $ * @version $Revision: 1 $
*/ */
@NamedQueries({ @NamedQueries({
@NamedQuery(name="userHasRole", query="select m from UserRoleMappingEntity m where m.user = :user and m.role = :role"), @NamedQuery(name="userHasRole", query="select m from UserRoleMappingEntity m where m.user = :user and m.roleId = :roleId"),
@NamedQuery(name="userRoleMappings", query="select m from UserRoleMappingEntity m where m.user = :user"), @NamedQuery(name="userRoleMappings", query="select m from UserRoleMappingEntity m where m.user = :user"),
@NamedQuery(name="userRoleMappingIds", query="select m.role.id from UserRoleMappingEntity m where m.user = :user"), @NamedQuery(name="userRoleMappingIds", query="select m.roleId from UserRoleMappingEntity m where m.user = :user"),
@NamedQuery(name="deleteUserRoleMappingsByRealm", query="delete from UserRoleMappingEntity mapping where mapping.user IN (select u from UserEntity u where realm=:realm)") @NamedQuery(name="deleteUserRoleMappingsByRealm", query="delete from UserRoleMappingEntity mapping where mapping.user IN (select u from UserEntity u where u.realmId=:realmId)"),
@NamedQuery(name="deleteUserRoleMappingsByRole", query="delete from UserRoleMappingEntity m where m.roleId = :roleId"),
@NamedQuery(name="deleteUserRoleMappingsByUser", query="delete from UserRoleMappingEntity m where m.user = :user")
}) })
@Table(name="USER_ROLE_MAPPING")
@Entity @Entity
@IdClass(UserRoleMappingEntity.Key.class) @IdClass(UserRoleMappingEntity.Key.class)
public class UserRoleMappingEntity { public class UserRoleMappingEntity {
@Id @Id
@ManyToOne(fetch= FetchType.LAZY) @ManyToOne(fetch= FetchType.LAZY)
@JoinColumn(name="userId") @JoinColumn(name="USER_ID")
protected UserEntity user; protected UserEntity user;
@Id @Id
@ManyToOne(fetch= FetchType.LAZY) @Column(name = "ROLE_ID")
@JoinColumn(name="roleId") protected String roleId;
protected RoleEntity role;
public UserEntity getUser() { public UserEntity getUser() {
return user; return user;
@ -43,34 +47,35 @@ public class UserRoleMappingEntity {
this.user = user; this.user = user;
} }
public RoleEntity getRole() { public String getRoleId() {
return role; return roleId;
} }
public void setRole(RoleEntity role) { public void setRoleId(String roleId) {
this.role = role; this.roleId = roleId;
} }
public static class Key implements Serializable { public static class Key implements Serializable {
protected UserEntity user; protected UserEntity user;
protected RoleEntity role; protected String roleId;
public Key() { public Key() {
} }
public Key(UserEntity user, RoleEntity role) { public Key(UserEntity user, String roleId) {
this.user = user; this.user = user;
this.role = role; this.roleId = roleId;
} }
public UserEntity getUser() { public UserEntity getUser() {
return user; return user;
} }
public RoleEntity getRole() { public String getRoleId() {
return role; return roleId;
} }
@Override @Override
@ -80,18 +85,17 @@ public class UserRoleMappingEntity {
Key key = (Key) o; Key key = (Key) o;
if (role != null ? !role.getId().equals(key.role != null ? key.role.getId() : null) : key.role != null) return false; if (!roleId.equals(key.roleId)) return false;
if (user != null ? !user.getId().equals(key.user != null ? key.user.getId() : null) : key.user != null) return false; if (!user.equals(key.user)) return false;
return true; return true;
} }
@Override @Override
public int hashCode() { public int hashCode() {
int result = user != null ? user.getId().hashCode() : 0; int result = user.hashCode();
result = 31 * result + (role != null ? role.getId().hashCode() : 0); result = 31 * result + roleId.hashCode();
return result; return result;
} }
} }
} }