OF-1139: User-to-provider mapping

This commit introduces a new AuthProvider and UserProvider that, similar to the
HybridAuthProvider and -UserProvider can be configured to use more than one backend
store. Where the Hybrids iterate over all of their providers in an attempt to
fulfill a request, these new 'Mapped' variants will first determine what provider
is to be used for a particular user, and will then operate on only that provider.
This is useful where particular users are required to be restricted to specific
backends.
parent 9df61650
/*
* Copyright 2016 IgniteRealtime.org
*
* 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.jivesoftware.openfire.auth;
import java.util.Set;
import java.util.SortedSet;
/**
* Implementations are used to determine what AuthProvider is to be used for a particular username.
*
* Implementation must have a no-argument constructor.
*
* @author Guus der Kinderen, guus@goodbytes.nl
* @see MappedAuthProvider
*/
public interface AuthProviderMapper
{
/**
* Finds a suitable AuthProvider for the user. Returns null when no AuthProvider can be found for the particular
* user.
*
* @param username A user identifier (cannot be null or empty).
* @return An AuthProvider for the user (possibly null).
*/
AuthProvider getAuthProvider( String username );
/**
* Returns all providers that are used by this instance.
*
* The returned collection should have a consistent, predictable iteration order.
*
* @return all providers (never null).
*/
Set<AuthProvider> getAuthProviders();
}
/*
* Copyright 2016 IgniteRealtime.org
*
* 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.jivesoftware.openfire.auth;
import org.jivesoftware.openfire.admin.AdminManager;
import org.jivesoftware.util.ClassUtils;
import org.jivesoftware.util.JiveGlobals;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* A {@link AuthProviderMapper} that can be used to draw administrative users from another source than the regular, non-
* administrative users.
*
* This implementation uses {@link AdminManager} to determine if a particular user is an administrative user. When a
* user is not recognized, it is deemed a regular, non-administrative user.
*
* To configure this provider, the both system properties from the example below <em>must</em> be defined. Their value
* must reference the classname of an {@link AuthProvider}.
*
* <ul>
* <li><tt>authorizationBasedAuthMapper.adminProvider.className = org.jivesoftware.openfire.auth.DefaultAuthProvider</tt></li>
* <li><tt>authorizationBasedAuthMapper.userProvider.className = org.jivesoftware.openfire.auth.NativeAuthProvider</tt></li>
* </ul>
*
* @author Guus der Kinderen, guus@goodbytes.nl
*/
public class AuthorizationBasedAuthProviderMapper implements AuthProviderMapper
{
/**
* Name of the property of which the value is expected to be the classname of the AuthProvider which will serve the
* administrative users.
*/
public static final String PROPERTY_ADMINPROVIDER_CLASSNAME = "authorizationBasedAuthMapper.adminProvider.className";
/**
* Name of the property of which the value is expected to be the classname of the AuthProvider which will serve the
* regular, non-administrative users.
*/
public static final String PROPERTY_USERPROVIDER_CLASSNAME = "authorizationBasedAuthMapper.userProvider.className";
/**
* Serves the administrative users.
*/
protected final AuthProvider adminProvider;
/**
* Serves the regular, non-administrative users.
*/
protected final AuthProvider userProvider;
public AuthorizationBasedAuthProviderMapper()
{
// Migrate properties.
JiveGlobals.migrateProperty( PROPERTY_ADMINPROVIDER_CLASSNAME );
JiveGlobals.migrateProperty( PROPERTY_USERPROVIDER_CLASSNAME );
// Instantiate providers.
adminProvider = instantiateProvider( PROPERTY_ADMINPROVIDER_CLASSNAME );
userProvider = instantiateProvider( PROPERTY_USERPROVIDER_CLASSNAME );
}
protected static AuthProvider instantiateProvider( String propertyName )
{
final String className = JiveGlobals.getProperty( propertyName );
if ( className == null )
{
throw new IllegalStateException( "A class name must be specified via openfire.xml or the system properties." );
}
try
{
final Class c = ClassUtils.forName( className );
return (AuthProvider) c.newInstance();
}
catch ( Exception e )
{
throw new IllegalStateException( "Unable to create new instance of AuthProvider: " + className, e );
}
}
@Override
public AuthProvider getAuthProvider( String username )
{
// TODO add optional caching, to prevent retrieving the administrative users upon every invocation.
final boolean isAdmin = AdminManager.getAdminProvider().getAdmins().contains( username );
if ( isAdmin )
{
return adminProvider;
} else
{
return userProvider;
}
}
@Override
public SortedSet<AuthProvider> getAuthProviders()
{
final SortedSet<AuthProvider> result = new TreeSet<>();
result.add( adminProvider );
result.add( userProvider );
return result;
}
}
...@@ -39,6 +39,10 @@ import org.slf4j.LoggerFactory; ...@@ -39,6 +39,10 @@ import org.slf4j.LoggerFactory;
* <li>If the tertiary provider is defined, attempt authentication. * <li>If the tertiary provider is defined, attempt authentication.
* </ol> * </ol>
* *
* This class related to, but is distinct from {@link MappedAuthProvider}. The Hybrid variant of the provider iterates
* over providers, operating on the first applicable instance. The Mapped variant, however, maps each user to exactly
* one provider.
*
* To enable this provider, set the <tt>provider.auth.className</tt> system property to * To enable this provider, set the <tt>provider.auth.className</tt> system property to
* <tt>org.jivesoftware.openfire.auth.HybridAuthProvider</tt>. * <tt>org.jivesoftware.openfire.auth.HybridAuthProvider</tt>.
* *
...@@ -77,7 +81,7 @@ import org.slf4j.LoggerFactory; ...@@ -77,7 +81,7 @@ import org.slf4j.LoggerFactory;
*/ */
public class HybridAuthProvider implements AuthProvider { public class HybridAuthProvider implements AuthProvider {
private static final Logger Log = LoggerFactory.getLogger(HybridAuthProvider.class); private static final Logger Log = LoggerFactory.getLogger(HybridAuthProvider.class);
private AuthProvider primaryProvider; private AuthProvider primaryProvider;
private AuthProvider secondaryProvider; private AuthProvider secondaryProvider;
......
/*
* Copyright 2016 IgniteRealtime.org
*
* 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.jivesoftware.openfire.auth;
import org.jivesoftware.openfire.user.UserNotFoundException;
import org.jivesoftware.util.ClassUtils;
import org.jivesoftware.util.JiveGlobals;
/**
* A {@link AuthProvider} that delegates to a user-specific AuthProvider.
*
* This class related to, but is distinct from {@link HybridAuthProvider}. The Hybrid variant of the provider iterates
* over providers, operating on the first applicable instance. This Mapped variant, however, maps each user to exactly
* one provider.
*
* To use this provider, use the following system property definition:
*
* <ul>
* <li><tt>provider.auth.className = org.jivesoftware.openfire.user.MappedAuthProvider</tt></li>
* </ul>
*
* To be usable, a {@link AuthProviderMapper} must be configured using the <tt>mappedAuthProvider.mapper.className</tt>
* system property. It is of importance to note that most AuthProviderMapper implementations will require additional
* configuration.
*
* @author Guus der Kinderen, guus@goodbytes.nl
*/
public class MappedAuthProvider implements AuthProvider
{
/**
* Name of the property of which the value is expected to be the classname of the AuthProviderMapper instance to be
* used by instances of this class.
*/
public static final String PROPERTY_MAPPER_CLASSNAME = "mappedAuthProvider.mapper.className";
/**
* Used to determine what provider is to be used to operate on a particular user.
*/
protected final AuthProviderMapper mapper;
public MappedAuthProvider()
{
// Migrate properties.
JiveGlobals.migrateProperty( PROPERTY_MAPPER_CLASSNAME );
// Instantiate mapper.
final String mapperClass = JiveGlobals.getProperty( PROPERTY_MAPPER_CLASSNAME );
if ( mapperClass == null )
{
throw new IllegalStateException( "A mapper must be specified via openfire.xml or the system properties." );
}
try
{
final Class c = ClassUtils.forName( mapperClass );
mapper = (AuthProviderMapper) c.newInstance();
}
catch ( Exception e )
{
throw new IllegalStateException( "Unable to create new instance of AuthProviderMapper class: " + mapperClass, e );
}
}
@Override
public void authenticate( String username, String password ) throws UnauthorizedException, ConnectionException, InternalUnauthenticatedException
{
final AuthProvider provider = mapper.getAuthProvider( username );
if ( provider == null )
{
throw new UnauthorizedException();
}
provider.authenticate( username, password );
}
@Override
public String getPassword( String username ) throws UserNotFoundException, UnsupportedOperationException
{
final AuthProvider provider = mapper.getAuthProvider( username );
if ( provider == null )
{
throw new UserNotFoundException();
}
return provider.getPassword( username );
}
@Override
public void setPassword( String username, String password ) throws UserNotFoundException, UnsupportedOperationException
{
final AuthProvider provider = mapper.getAuthProvider( username );
if ( provider == null )
{
throw new UserNotFoundException();
}
provider.setPassword( username, password );
}
@Override
public boolean supportsPasswordRetrieval()
{
// TODO Make calls concurrent for improved throughput.
for ( final AuthProvider provider : mapper.getAuthProviders() )
{
// If at least one provider supports password retrieval, so does this proxy.
if ( provider.supportsPasswordRetrieval() )
{
return true;
}
}
return false;
}
@Override
public boolean isScramSupported()
{
// TODO Make calls concurrent for improved throughput.
for ( final AuthProvider provider : mapper.getAuthProviders() )
{
// If at least one provider supports SCRAM, so does this proxy.
if ( provider.isScramSupported() )
{
return true;
}
}
return false;
}
}
/*
* Copyright 2016 IgniteRealtime.org
*
* 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.jivesoftware.openfire.user;
import org.jivesoftware.openfire.admin.AdminManager;
import org.jivesoftware.util.JiveGlobals;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* A {@link UserProviderMapper} that can be used to draw administrative users from another source than the regular, non-
* administrative users.
*
* This implementation uses {@link AdminManager} to determine if a particular user is an administrative user. When a
* user is not recognized, it is deemed a regular, non-administrative user.
*
* To configure this provider, the both system properties from the example below <em>must</em> be defined. Their value
* must reference the classname of an {@link UserProvider}.
*
* <ul>
* <li><tt>authorizationBasedUserMapper.adminProvider.className = org.jivesoftware.openfire.auth.DefaultUserProvider</tt></li>
* <li><tt>authorizationBasedUserMapper.userProvider.className = org.jivesoftware.openfire.auth.NativeUserProvider</tt></li>
* </ul>
*
* @author Guus der Kinderen, guus@goodbytes.nl
*/
public class AuthorizationBasedUserProviderMapper implements UserProviderMapper
{
/**
* Name of the property of which the value is expected to be the classname of the UserProvider which will serve the
* administrative users.
*/
public static final String PROPERTY_ADMINPROVIDER_CLASSNAME = "authorizationBasedUserMapper.adminProvider.className";
/**
* Name of the property of which the value is expected to be the classname of the UserProvider which will serve the
* regular, non-administrative users.
*/
public static final String PROPERTY_USERPROVIDER_CLASSNAME = "authorizationBasedUserMapper.userProvider.className";
/**
* Serves the administrative users.
*/
protected final UserProvider adminProvider;
/**
* Serves the regular, non-administrative users.
*/
protected final UserProvider userProvider;
public AuthorizationBasedUserProviderMapper()
{
// Migrate properties.
JiveGlobals.migrateProperty( PROPERTY_ADMINPROVIDER_CLASSNAME );
JiveGlobals.migrateProperty( PROPERTY_USERPROVIDER_CLASSNAME );
// Instantiate providers.
adminProvider = UserMultiProvider.instantiate( PROPERTY_ADMINPROVIDER_CLASSNAME );
if ( adminProvider == null )
{
throw new IllegalStateException( "A class name for the admin provider must be specified via openfire.xml or the system properties using property: " + PROPERTY_ADMINPROVIDER_CLASSNAME );
}
userProvider = UserMultiProvider.instantiate( PROPERTY_USERPROVIDER_CLASSNAME );
if ( userProvider == null )
{
throw new IllegalStateException( "A class name for the user provider must be specified via openfire.xml or the system properties using property: " + PROPERTY_USERPROVIDER_CLASSNAME );
}
}
@Override
public UserProvider getUserProvider( String username )
{
// TODO add optional caching, to prevent retrieving the administrative users upon every invocation.
final boolean isAdmin = AdminManager.getAdminProvider().getAdmins().contains( username );
if ( isAdmin )
{
return adminProvider;
} else
{
return userProvider;
}
}
@Override
public SortedSet<UserProvider> getUserProviders()
{
final SortedSet<UserProvider> result = new TreeSet<>();
result.add( adminProvider );
result.add( userProvider );
return result;
}
}
/* /*
* Copyright (C) 2004-2009 Jive Software. All rights reserved. * Copyright 2016 IgniteRealtime.org
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* */
*/
package org.jivesoftware.openfire.user;
package org.jivesoftware.openfire.user;
import org.jivesoftware.util.JiveGlobals;
import java.util.ArrayList; import org.slf4j.Logger;
import java.util.Collection; import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.HashSet; import java.util.ArrayList;
import java.util.List; import java.util.Date;
import java.util.Set; import java.util.List;
import org.jivesoftware.util.ClassUtils; /**
import org.jivesoftware.util.JiveGlobals; * Delegate UserProvider operations among up to three configurable provider implementation classes.
import org.slf4j.Logger; *
import org.slf4j.LoggerFactory; * This class related to, but is distinct from {@link MappedUserProvider}. The Hybrid variant of the provider iterates
* over providers, operating on the first applicable instance. The Mapped variant, however, maps each user to exactly
/** * one provider.
* Delegate UserProvider operations among up to three configurable provider implementation classes. *
* * @author Marc Seeger
* @author Marc Seeger * @author Chris Neasbitt
* @author Chris Neasbitt * @author Tom Evans
* @author Tom Evans * @author Guus der Kinderen
*/ */
public class HybridUserProvider extends UserMultiProvider
public class HybridUserProvider implements UserProvider { {
private static final Logger Log = LoggerFactory.getLogger( HybridUserProvider.class );
private static final Logger Log = LoggerFactory.getLogger(HybridUserProvider.class);
private final List<UserProvider> userProviders = new ArrayList<>();
private List<UserProvider> userproviders = null;
public HybridUserProvider()
public HybridUserProvider() { {
// Migrate user provider properties
// Migrate user provider properties JiveGlobals.migrateProperty( "hybridUserProvider.primaryProvider.className" );
JiveGlobals.migrateProperty("hybridUserProvider.primaryProvider.className"); JiveGlobals.migrateProperty( "hybridUserProvider.secondaryProvider.className" );
JiveGlobals.migrateProperty("hybridUserProvider.secondaryProvider.className"); JiveGlobals.migrateProperty( "hybridUserProvider.tertiaryProvider.className" );
JiveGlobals.migrateProperty("hybridUserProvider.tertiaryProvider.className");
// Load primary, secondary, and tertiary user providers.
userproviders = new ArrayList<>(); final UserProvider primary = instantiate( "hybridUserProvider.primaryProvider.className" );
if ( primary != null )
// Load primary, secondary, and tertiary user providers. {
String primaryClass = JiveGlobals.getProperty("hybridUserProvider.primaryProvider.className"); userProviders.add( primary );
if (primaryClass == null) { }
Log.error("A primary UserProvider must be specified via openfire.xml or the system properties"); final UserProvider secondary = instantiate( "hybridUserProvider.secondaryProvider.className" );
return; if ( secondary != null )
} {
try { userProviders.add( secondary );
Class c = ClassUtils.forName(primaryClass); }
UserProvider primaryProvider = (UserProvider) c.newInstance(); final UserProvider tertiary = instantiate( "hybridUserProvider.tertiaryProvider.className" );
userproviders.add(primaryProvider); if ( tertiary != null )
Log.debug("Primary user provider: " + primaryClass); {
} catch (Exception e) { userProviders.add( tertiary );
Log.error("Unable to load primary user provider: " + primaryClass + }
". Users in this provider will be disabled.", e);
return; // Verify that there's at least one provider available.
} if ( userProviders.isEmpty() )
String secondaryClass = JiveGlobals.getProperty("hybridUserProvider.secondaryProvider.className"); {
if (secondaryClass != null) { Log.error( "At least one UserProvider must be specified via openfire.xml or the system properties!" );
try { }
Class c = ClassUtils.forName(secondaryClass); }
UserProvider secondaryProvider = (UserProvider) c.newInstance();
userproviders.add(secondaryProvider); @Override
Log.debug("Secondary user provider: " + secondaryClass); protected List<UserProvider> getUserProviders()
} catch (Exception e) { {
Log.error("Unable to load secondary user provider: " + secondaryClass, e); return userProviders;
} }
}
String tertiaryClass = JiveGlobals.getProperty("hybridUserProvider.tertiaryProvider.className"); /**
if (tertiaryClass != null) { * Creates a new user in the first non-read-only provider.
try { *
Class c = ClassUtils.forName(tertiaryClass); * @param username the username.
UserProvider tertiaryProvider = (UserProvider) c.newInstance(); * @param password the plain-text password.
userproviders.add(tertiaryProvider); * @param name the user's name, which can be <tt>null</tt>, unless isNameRequired is set to true.
Log.debug("Tertiary user provider: " + tertiaryClass); * @param email the user's email address, which can be <tt>null</tt>, unless isEmailRequired is set to true.
} catch (Exception e) { * @return The user that was created.
Log.error("Unable to load tertiary user provider: " + tertiaryClass, e); * @throws UserAlreadyExistsException
} */
} @Override
} public User createUser( String username, String password, String name, String email ) throws UserAlreadyExistsException
{
// create the user (first writable provider wins)
@Override for ( final UserProvider provider : getUserProviders() )
public User createUser(String username, String password, String name, String email) throws UserAlreadyExistsException { {
if ( provider.isReadOnly() )
User returnvalue = null; {
continue;
// create the user (first writable provider wins) }
for (UserProvider provider : userproviders) { return provider.createUser( username, password, name, email );
if (provider.isReadOnly()) { }
continue;
} // all providers are read-only
returnvalue = provider.createUser(username, password, name, email); throw new UnsupportedOperationException();
if (returnvalue != null) { }
break;
} /**
} * Removes a user from all non-read-only providers.
*
if (returnvalue == null) { * @param username the username to delete.
throw new UnsupportedOperationException(); */
} @Override
return returnvalue; public void deleteUser( String username )
} {
// all providers are read-only
if ( isReadOnly() )
@Override {
public void deleteUser(String username) { throw new UnsupportedOperationException();
}
boolean isDeleted = false;
for ( final UserProvider provider : getUserProviders() )
for (UserProvider provider : userproviders) { {
if (provider.isReadOnly()) { if ( provider.isReadOnly() )
continue; {
} continue;
provider.deleteUser(username); }
isDeleted = true; provider.deleteUser( username );
} }
}
// all providers are read-only
if (!isDeleted) { /**
throw new UnsupportedOperationException(); * Returns the first provider that contains the user, or the first provider that is not read-only when the user
} * does not exist in any provider.
} *
* @param username the username (cannot be null or empty).
* @return The user provider (never null)
@Override */
public Collection<User> findUsers(Set<String> fields, String query) throws UnsupportedOperationException { public UserProvider getUserProvider( String username )
{
List<User> userList = new ArrayList<>(); UserProvider nonReadOnly = null;
boolean isUnsupported = false; for ( final UserProvider provider : getUserProviders() )
{
for (UserProvider provider : userproviders) { try
{
// validate search fields for each provider provider.loadUser( username );
Set<String> validFields = provider.getSearchFields(); return provider;
for (String field : fields) { }
if (!validFields.contains(field)) { catch ( UserNotFoundException unfe )
continue; {
} if ( Log.isDebugEnabled() )
} {
Log.debug( "User {} not found by UserProvider {}", username, provider.getClass().getName() );
try { }
userList.addAll(provider.findUsers(fields, query));
} catch (UnsupportedOperationException uoe) { if ( nonReadOnly == null && !provider.isReadOnly() )
Log.warn("UserProvider.findUsers is not supported by this UserProvider: " + provider.getClass().getName()); {
isUnsupported = true; nonReadOnly = provider;
} }
} }
}
if (isUnsupported && userList.size() == 0) {
throw new UnsupportedOperationException(); // User does not exist. Return a provider suitable for creating users.
} if ( nonReadOnly == null )
return userList; {
} throw new UnsupportedOperationException();
}
@Override return nonReadOnly;
public Collection<User> findUsers(Set<String> fields, String query, int startIndex, int numResults) throws UnsupportedOperationException { }
List<User> userList = new ArrayList<>(); /**
boolean isUnsupported = false; * Loads a user from the first provider that contains the user.
int totalMatchedUserCount = 0; *
* @param username the username (cannot be null or empty).
for (UserProvider provider : userproviders) { * @return The user (never null).
* @throws UserNotFoundException When none of the providers contains the user.
// validate search fields for each provider */
Set<String> validFields = provider.getSearchFields(); @Override
for (String field : fields) { public User loadUser( String username ) throws UserNotFoundException
if (!validFields.contains(field)) { {
continue; for ( UserProvider provider : userProviders )
} {
} try
{
try { return provider.loadUser( username );
Collection<User> providerResults = provider.findUsers(fields, query); }
totalMatchedUserCount += providerResults.size(); catch ( UserNotFoundException unfe )
if (startIndex >= totalMatchedUserCount) { {
continue; if ( Log.isDebugEnabled() )
} {
int providerStartIndex = Math.max(0, startIndex - totalMatchedUserCount); Log.debug( "User {} not found by UserProvider {}", username, provider.getClass().getName() );
int providerResultMax = numResults - userList.size(); }
List<User> providerList = providerResults instanceof List<?> ? }
(List<User>) providerResults : new ArrayList<>(providerResults); }
userList.addAll(providerList.subList(providerStartIndex, providerResultMax)); //if we get this far, no provider was able to load the user
if (userList.size() >= numResults) { throw new UserNotFoundException();
break; }
}
} catch (UnsupportedOperationException uoe) { /**
Log.warn("UserProvider.findUsers is not supported by this UserProvider: " + provider.getClass().getName()); * Changes the creation date of a user in the first provider that contains the user.
isUnsupported = true; *
} * @param username the username.
} * @param creationDate the date the user was created.
* @throws UserNotFoundException when the user was not found in any provider.
if (isUnsupported && userList.size() == 0) { * @throws UnsupportedOperationException when the provider is read-only.
throw new UnsupportedOperationException(); */
} @Override
return userList; public void setCreationDate( String username, Date creationDate ) throws UserNotFoundException
} {
getUserProvider( username ).setCreationDate( username, creationDate );
}
@Override
public Set<String> getSearchFields() throws UnsupportedOperationException { /**
* Changes the modification date of a user in the first provider that contains the user.
Set<String> returnvalue = new HashSet<>(); *
* @param username the username.
for (UserProvider provider : userproviders) { * @param modificationDate the date the user was (last) modified.
returnvalue.addAll(provider.getSearchFields()); * @throws UserNotFoundException when the user was not found in any provider.
} * @throws UnsupportedOperationException when the provider is read-only.
*/
// no search fields were returned @Override
if (returnvalue.size() == 0) { public void setModificationDate( String username, Date modificationDate ) throws UserNotFoundException
throw new UnsupportedOperationException(); {
} getUserProvider( username ).setCreationDate( username, modificationDate );
return returnvalue; }
}
/**
* Changes the full name of a user in the first provider that contains the user.
@Override *
public int getUserCount() { * @param username the username.
int count = 0; * @param name the new full name a user.
for (UserProvider provider : userproviders) { * @throws UserNotFoundException when the user was not found in any provider.
count += provider.getUserCount(); * @throws UnsupportedOperationException when the provider is read-only.
} */
return count; @Override
} public void setName( String username, String name ) throws UserNotFoundException
{
@Override getUserProvider( username ).setEmail( username, name );
public Collection<String> getUsernames() { }
List<String> returnvalue = new ArrayList<>(); /**
* Changes the email address of a user in the first provider that contains the user.
for (UserProvider provider : userproviders){ *
returnvalue.addAll(provider.getUsernames()); * @param username the username.
} * @param email the new email address of a user.
return returnvalue; * @throws UserNotFoundException when the user was not found in any provider.
} * @throws UnsupportedOperationException when the provider is read-only.
*/
@Override
@Override public void setEmail( String username, String email ) throws UserNotFoundException
public Collection<User> getUsers() { {
List<User> returnvalue = new ArrayList<>(); getUserProvider( username ).setEmail( username, email );
}
for (UserProvider provider : userproviders){ }
returnvalue.addAll(provider.getUsers());
}
return returnvalue;
}
@Override
public Collection<User> getUsers(int startIndex, int numResults) {
List<User> userList = new ArrayList<>();
int totalUserCount = 0;
for (UserProvider provider : userproviders) {
int providerStartIndex = Math.max((startIndex - totalUserCount), 0);
totalUserCount += provider.getUserCount();
if (startIndex >= totalUserCount) {
continue;
}
int providerResultMax = numResults - userList.size();
userList.addAll(provider.getUsers(providerStartIndex, providerResultMax));
if (userList.size() >= numResults) {
break;
}
}
return userList;
}
@Override
public boolean isReadOnly() {
return false;
}
@Override
public boolean isNameRequired() {
return false;
}
@Override
public boolean isEmailRequired() {
return false;
}
@Override
public User loadUser(String username) throws UserNotFoundException {
for (UserProvider provider : userproviders) {
try {
return provider.loadUser(username);
}
catch (UserNotFoundException unfe) {
if (Log.isDebugEnabled()) {
Log.debug("User " + username + " not found by UserProvider " + provider.getClass().getName());
}
}
}
//if we get this far, no provider was able to load the user
throw new UserNotFoundException();
}
@Override
public void setCreationDate(String username, Date creationDate) throws UserNotFoundException {
boolean isUnsupported = false;
for (UserProvider provider : userproviders) {
try {
provider.setCreationDate(username, creationDate);
return;
}
catch (UnsupportedOperationException uoe) {
Log.warn("UserProvider.setCreationDate is not supported by this UserProvider: " + provider.getClass().getName());
isUnsupported = true;
}
catch (UserNotFoundException unfe) {
if (Log.isDebugEnabled()) {
Log.debug("User " + username + " not found by UserProvider " + provider.getClass().getName());
}
}
}
if (isUnsupported) {
throw new UnsupportedOperationException();
}
else {
throw new UserNotFoundException();
}
}
@Override
public void setEmail(String username, String email) throws UserNotFoundException {
boolean isUnsupported = false;
for (UserProvider provider : userproviders) {
try {
provider.setEmail(username, email);
return;
}
catch (UnsupportedOperationException uoe) {
Log.warn("UserProvider.setEmail is not supported by this UserProvider: " + provider.getClass().getName());
isUnsupported = true;
}
catch (UserNotFoundException unfe) {
if (Log.isDebugEnabled()) {
Log.debug("User " + username + " not found by UserProvider " + provider.getClass().getName());
}
}
}
if (isUnsupported) {
throw new UnsupportedOperationException();
}
else {
throw new UserNotFoundException();
}
}
@Override
public void setModificationDate(String username, Date modificationDate) throws UserNotFoundException {
boolean isUnsupported = false;
for (UserProvider provider : userproviders) {
try {
provider.setModificationDate(username, modificationDate);
return;
}
catch (UnsupportedOperationException uoe) {
Log.warn("UserProvider.setModificationDate is not supported by this UserProvider: " + provider.getClass().getName());
isUnsupported = true;
}
catch (UserNotFoundException unfe) {
if (Log.isDebugEnabled()) {
Log.debug("User " + username + " not found by UserProvider " + provider.getClass().getName());
}
}
}
if (isUnsupported) {
throw new UnsupportedOperationException();
}
else {
throw new UserNotFoundException();
}
}
@Override
public void setName(String username, String name) throws UserNotFoundException {
boolean isUnsupported = false;
for (UserProvider provider : userproviders) {
try {
provider.setName(username, name);
return;
}
catch (UnsupportedOperationException uoe) {
Log.warn("UserProvider.setName is not supported by this UserProvider: " + provider.getClass().getName());
isUnsupported = true;
}
catch (UserNotFoundException unfe) {
if (Log.isDebugEnabled()) {
Log.debug("User " + username + " not found by UserProvider " + provider.getClass().getName());
}
}
}
if (isUnsupported) {
throw new UnsupportedOperationException();
}
else {
throw new UserNotFoundException();
}
}
}
/*
* Copyright 2016 IgniteRealtime.org
*
* 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.jivesoftware.openfire.user;
import org.jivesoftware.util.ClassUtils;
import org.jivesoftware.util.JiveGlobals;
import java.util.Collection;
import java.util.Date;
/**
* A {@link UserProvider} that delegates to a user-specific UserProvider.
*
* This class related to, but is distinct from {@link HybridUserProvider}. The Hybrid variant of the provider iterates
* over providers, operating on the first applicable instance. This Mapped variant, however, maps each user to exactly
* one provider.
*
* To use this provider, use the following system property definition:
*
* <ul>
* <li><tt>provider.user.className = org.jivesoftware.openfire.user.MappedUserProvider</tt></li>
* </ul>
*
* To be usable, a {@link UserProviderMapper} must be configured using the <tt>mappedUserProvider.mapper.className</tt>
* system property. It is of importance to note that most UserProviderMapper implementations will require additional
* configuration.
*
* @author Guus der Kinderen, guus@goodbytes.nl
* @see org.jivesoftware.openfire.auth.MappedAuthProvider
*/
public class MappedUserProvider extends UserMultiProvider
{
/**
* Name of the property of which the value is expected to be the classname of the UserProviderMapper instance to be
* used by instances of this class.
*/
public static final String PROPERTY_MAPPER_CLASSNAME = "mappedUserProvider.mapper.className";
/**
* Used to determine what provider is to be used to operate on a particular user.
*/
protected final UserProviderMapper mapper;
public MappedUserProvider()
{
// Migrate properties.
JiveGlobals.migrateProperty( PROPERTY_MAPPER_CLASSNAME );
// Instantiate mapper.
final String mapperClass = JiveGlobals.getProperty( PROPERTY_MAPPER_CLASSNAME );
if ( mapperClass == null )
{
throw new IllegalStateException( "A mapper must be specified via openfire.xml or the system properties." );
}
try
{
final Class c = ClassUtils.forName( mapperClass );
mapper = (UserProviderMapper) c.newInstance();
}
catch ( Exception e )
{
throw new IllegalStateException( "Unable to create new instance of UserProviderMapper class: " + mapperClass, e );
}
}
@Override
public Collection<UserProvider> getUserProviders()
{
return mapper.getUserProviders();
}
@Override
public UserProvider getUserProvider( String username )
{
return mapper.getUserProvider( username );
}
@Override
public User loadUser( String username ) throws UserNotFoundException
{
final UserProvider userProvider;
try{
userProvider = getUserProvider( username );
} catch (RuntimeException e){
throw new UserNotFoundException("Unable to identify user provider for username "+username, e);
}
return userProvider.loadUser( username );
}
@Override
public User createUser( String username, String password, String name, String email ) throws UserAlreadyExistsException
{
return getUserProvider( username ).createUser( username, password, name, email );
}
@Override
public void deleteUser( String username )
{
getUserProvider( username ).deleteUser( username );
}
@Override
public void setName( String username, String name ) throws UserNotFoundException
{
getUserProvider( username ).setName( username, name );
}
@Override
public void setEmail( String username, String email ) throws UserNotFoundException
{
getUserProvider( username ).setEmail( username, email );
}
@Override
public void setCreationDate( String username, Date creationDate ) throws UserNotFoundException
{
getUserProvider( username ).setCreationDate( username, creationDate );
}
@Override
public void setModificationDate( String username, Date modificationDate ) throws UserNotFoundException
{
getUserProvider( username ).setModificationDate( username, modificationDate );
}
}
/*
* Copyright 2016 IgniteRealtime.org
*
* 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.jivesoftware.openfire.user;
import org.jivesoftware.util.ClassUtils;
import org.jivesoftware.util.JiveGlobals;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* A {@link UserProvider} that delegates to one or more 'backing' UserProvider.
*
* @author GUus der Kinderen, guus@goodbytes.nl
*/
public abstract class UserMultiProvider implements UserProvider
{
private final static Logger Log = LoggerFactory.getLogger( UserMultiProvider.class );
/**
* Instantiates a UserProvider based on a property value (that is expected to be a class name). When the property
* is not set, this method returns null. When the property is set, but an exception occurs while instantiating
* the class, this method logs the error and returns null.
*
* UserProvider classes are required to have a public, no-argument constructor.
*
* @param propertyName A property name (cannot ben ull).
* @return A user provider (can be null).
*/
public static UserProvider instantiate( String propertyName )
{
final String className = JiveGlobals.getProperty( propertyName );
if ( className == null )
{
Log.debug( "Property '{}' is undefined. Skipping.", propertyName );
return null;
}
Log.debug( "About to to instantiate an UserProvider '{}' based on the value of property '{}'.", className, propertyName );
try
{
final Class c = ClassUtils.forName( className );
final UserProvider provider = (UserProvider) c.newInstance();
Log.debug( "Instantiated UserProvider '{}'", className );
return provider;
}
catch ( Exception e )
{
Log.error( "Unable to load UserProvider '{}'. Users in this provider will be disabled.", className, e );
return null;
}
}
/**
* Returns all UserProvider instances that serve as 'backing' providers.
*
* @return A collection of providers (never null).
*/
abstract Collection<UserProvider> getUserProviders();
/**
* Returns the 'backing' provider that serves the provided user. Note that the user need not exist.
*
* Finds a suitable UserProvider for the user.
*
* Note that the provided username need not reflect a pre-existing user (the instance might be used to determine in
* which provider a new user is to be created).
*
* Implementations are expected to be able to find a UserProvider for any username. If an implementation fails to do
* so, such a failure is assumed to be the result of a problem in implementation or configuration.
*
* @param username A user identifier (cannot be null or empty).
* @return A UserProvider for the user (never null).
*/
abstract UserProvider getUserProvider( String username );
@Override
public int getUserCount()
{
int total = 0;
// TODO Make calls concurrent for improved throughput.
for ( final UserProvider provider : getUserProviders() )
{
total += provider.getUserCount();
}
return total;
}
@Override
public Collection<User> getUsers()
{
final Collection<User> result = new ArrayList<>();
for ( final UserProvider provider : getUserProviders() )
{
// TODO Make calls concurrent for improved throughput.
result.addAll( provider.getUsers() );
}
return result;
}
@Override
public Collection<String> getUsernames()
{
final Collection<String> result = new ArrayList<>();
for ( final UserProvider provider : getUserProviders() )
{
// TODO Make calls concurrent for improved throughput.
result.addAll( provider.getUsernames() );
}
return result;
}
@Override
public Collection<User> getUsers( int startIndex, int numResults )
{
final List<User> userList = new ArrayList<>();
int totalUserCount = 0;
for ( final UserProvider provider : getUserProviders() )
{
final int providerStartIndex = Math.max( ( startIndex - totalUserCount ), 0 );
totalUserCount += provider.getUserCount();
if ( startIndex >= totalUserCount )
{
continue;
}
final int providerResultMax = numResults - userList.size();
userList.addAll( provider.getUsers( providerStartIndex, providerResultMax ) );
if ( userList.size() >= numResults )
{
break;
}
}
return userList;
}
/**
* Searches for users based on a set of fields and a query string. The fields must be taken from the values
* returned by {@link #getSearchFields()}. The query can include wildcards. For example, a search on the field
* "Name" with a query of "Ma*" might return user's with the name "Matt", "Martha" and "Madeline".
*
* This method throws an UnsupportedOperationException when none of the backing providers support search.
*
* When fields are provided that are not supported by a particular provider, those fields are ignored by that
* provider (but can still be used by other providers).
*
* @param fields the fields to search on.
* @param query the query string.
* @return a Collection of users that match the search.
* @throws UnsupportedOperationException When none of the providers support search.
*/
@Override
public Collection<User> findUsers( Set<String> fields, String query ) throws UnsupportedOperationException
{
final List<User> userList = new ArrayList<>();
int supportSearch = getUserProviders().size();
// TODO Make calls concurrent for improved throughput.
for ( final UserProvider provider : getUserProviders() )
{
try
{
// Use only those fields that are supported by the provider.
final Set<String> supportedFields = new HashSet<>( fields );
supportedFields.retainAll( provider.getSearchFields() );
userList.addAll( provider.findUsers( supportedFields, query ) );
}
catch ( UnsupportedOperationException uoe )
{
Log.warn( "UserProvider.findUsers is not supported by this UserProvider: {}. Its users are not returned as part of search queries.", provider.getClass().getName() );
supportSearch--;
}
}
if ( supportSearch == 0 )
{
throw new UnsupportedOperationException( "None of the backing providers support this operation." );
}
return userList;
}
/**
* Searches for users based on a set of fields and a query string. The fields must be taken from the values
* returned by {@link #getSearchFields()}. The query can include wildcards. For example, a search on the field
* "Name" with a query of "Ma*" might return user's with the name "Matt", "Martha" and "Madeline".
*
* This method throws an UnsupportedOperationException when none of the backing providers support search.
*
* When fields are provided that are not supported by a particular provider, those fields are ignored by that
* provider (but can still be used by other providers).
*
* The startIndex and numResults parameters are used to page through search results. For example, if the startIndex
* is 0 and numResults is 10, the first 10 search results will be returned. Note that numResults is a request for
* the number of results to return and that the actual number of results returned may be fewer.
*
* @param fields the fields to search on.
* @param query the query string.
* @param startIndex the starting index in the search result to return.
* @param numResults the number of users to return in the search result.
* @return a Collection of users that match the search.
* @throws UnsupportedOperationException When none of the providers support search.
*/
@Override
public Collection<User> findUsers( Set<String> fields, String query, int startIndex, int numResults ) throws UnsupportedOperationException
{
final List<User> userList = new ArrayList<>();
int supportSearch = getUserProviders().size();
int totalMatchedUserCount = 0;
for ( final UserProvider provider : getUserProviders() )
{
try
{
// Use only those fields that are supported by the provider.
final Set<String> supportedFields = new HashSet<>( fields );
supportedFields.retainAll( provider.getSearchFields() );
// Query the provider for sub-results.
final Collection<User> providerResults = provider.findUsers( fields, query );
// Keep track of how many hits we have had so far.
totalMatchedUserCount += providerResults.size();
// Check if this sub-result contains the start of the page of data that is searched for.
if ( startIndex >= totalMatchedUserCount )
{
continue;
}
// From the sub-results, take those that are of interest.
final int providerStartIndex = Math.max( 0, startIndex - totalMatchedUserCount );
final int providerResultMax = numResults - userList.size();
final List<User> providerList = providerResults instanceof List<?> ?
(List<User>) providerResults : new ArrayList<>( providerResults );
userList.addAll( providerList.subList( providerStartIndex, providerResultMax ) );
// Check if we have enough results.
if ( userList.size() >= numResults )
{
break;
}
}
catch ( UnsupportedOperationException uoe )
{
Log.warn( "UserProvider.findUsers is not supported by this UserProvider: " + provider.getClass().getName() );
supportSearch--;
}
}
if ( supportSearch == 0 )
{
throw new UnsupportedOperationException( "None of the backing providers support this operation." );
}
return userList;
}
/**
* Returns the combination of search fields supported by the backing providers. Note that the returned fields might
* not be supported by every backing provider.
*
* @throws UnsupportedOperationException If no search fields are returned, or when at least one of the providers throws UnsupportedOperationException when its #getSearchField() is invoked.
*/
@Override
public Set<String> getSearchFields() throws UnsupportedOperationException
{
int supportSearch = getUserProviders().size();
final Set<String> result = new HashSet<>();
// TODO Make calls concurrent for improved throughput.
for ( final UserProvider provider : getUserProviders() )
{
try
{
result.addAll( provider.getSearchFields() );
}
catch ( UnsupportedOperationException uoe )
{
Log.warn( "getSearchFields is not supported by this UserProvider: " + provider.getClass().getName() );
supportSearch--;
}
}
if ( supportSearch == 0 )
{
throw new UnsupportedOperationException( "None of the backing providers support this operation." );
}
return result;
}
/**
* Returns whether <em>all</em> backing providers are read-only. When read-only, users can not be created, deleted,
* or modified. If at least one provider is not read-only, this method returns false.
*
* @return true when all backing providers are read-only, otherwise false.
*/
@Override
public boolean isReadOnly()
{
// TODO Make calls concurrent for improved throughput.
for ( final UserProvider provider : getUserProviders() )
{
// If at least one provider is not readonly, neither is this proxy.
if ( !provider.isReadOnly() )
{
return false;
}
}
return true;
}
/**
* Returns whether <em>all</em> backing providers require a name to be set on User objects. If at least one proivder
* does not, this method returns false.
*
* @return true when all backing providers require a name to be set on User objects, otherwise false.
*/
@Override
public boolean isNameRequired()
{
// TODO Make calls concurrent for improved throughput.
for ( final UserProvider provider : getUserProviders() )
{
// If at least one provider does not require a name, neither is this proxy.
if ( !provider.isNameRequired() )
{
return false;
}
}
return true;
}
/**
* Returns whether <em>all</em> backing providers require an email address to be set on User objects. If at least
* one proivder does not, this method returns false.
*
* @return true when all backing providers require an email address to be set on User objects, otherwise false.
*/
@Override
public boolean isEmailRequired()
{
// TODO Make calls concurrent for improved throughput.
for ( final UserProvider provider : getUserProviders() )
{
// If at least one provider does not require an email, neither is this proxy.
if ( !provider.isEmailRequired() )
{
return false;
}
}
return true;
}
}
/*
* Copyright 2016 IgniteRealtime.org
*
* 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.jivesoftware.openfire.user;
import java.util.Set;
import java.util.SortedSet;
/**
* Implementations are used to determine what UserProvider is to be used for a particular username.
*
* Note that the provided username need not reflect a pre-existing user (the instance might be used to determine in
* which provider a new user is to be created).
*
* Implementation must have a no-argument constructor.
*
* @author Guus der Kinderen, guus@goodbytes.nl
* @see MappedUserProvider
*/
public interface UserProviderMapper
{
/**
* Finds a suitable UserProvider for the user.
*
* Note that the provided username need not reflect a pre-existing user (the instance might be used to determine in
* which provider a new user is to be created).
*
* Implementations are expected to be able to find a UserProvider for any username. If an implementation fails to do
* so, such a failure is assumed to be the result of a problem in implementation or configuration.
*
* @param username A user identifier (cannot be null or empty).
* @return A UserProvider for the user (never null).
*/
UserProvider getUserProvider( String username );
/**
* Returns all providers that are used by this instance.
*
* The returned collection should have a consistent, predictable iteration order.
*
* @return all providers (never null).
*/
Set<UserProvider> getUserProviders();
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment