ValidateWithDomainWhitelist.java

/***************************************************************************
   Copyright 2013 Emily Estes

   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 net.metanotion.formsauth;


import net.metanotion.util.SecureString;
import net.metanotion.web.RequestObject;

/** Assuming usernames are in the form of an email address, this validator takes a white list
	of domain names and checks that the domain of the username matches one of the domain
	names on the white list. */
public final class ValidateWithDomainWhitelist implements Validate {
	private final Iterable<String> domains;

	/** Create a new validation test accepting only the list of domain names provided.
		@param domains A collection of domains for the white list.
	*/
	public ValidateWithDomainWhitelist(final Iterable<String> domains) { this.domains = domains; }

	@Override public void validate(final String username, final SecureString password, final RequestObject ro) {
		final String userDomain = username.substring(username.indexOf('@') + 1);
		if(userDomain.length() == 0) { throw new NewAccountValidationException(); }
		for(final String domain: domains) {
			if(domain.equalsIgnoreCase(userDomain)) { return; }
		}
		throw new NewAccountValidationException();
	}
}