SimplePasswordPolicy.java

/*
 * Copyright 2018 Global Crop Diversity Trust
 *
 * 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.genesys.blocks.security.service.impl;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.genesys.blocks.security.service.PasswordPolicy;
import org.springframework.stereotype.Component;

/**
 * Simple password policy.
 */
@Component
public class SimplePasswordPolicy implements PasswordPolicy {

	/** The min length. */
	private final int minLength = 8;

	/** The max length. */
	private final int maxLength = Integer.MAX_VALUE;

	/** The min digits. */
	private final int minDigits = 1;

	/** The min special chars. */
	private final int minSpecialChars = 1;

	/** The Constant DIGITS. */
	private static final Pattern DIGITS = Pattern.compile("[0-9]");

	/** The Constant SPECIAL. */
	private static final Pattern SPECIAL = Pattern.compile("[^0-9a-zA-Z]");

	/**
	 * Check that password follows defined policy.
	 *
	 * @param password the password
	 * @throws PasswordPolicyException the password policy exception
	 */
	@Override
	public void assureGoodPassword(final String password) throws PasswordPolicyException {
		if (password == null) {
			throw new PasswordPolicyException("Password cannot be null");
		}
		if (password.length() < minLength) {
			throw new PasswordPolicyException("Password must be at least " + minLength + " characters");
		}
		if (password.length() > maxLength) {
			throw new PasswordPolicyException("Password must be at most " + maxLength + " characters");
		}

		int digitsCount = 0;
		Matcher matcher = DIGITS.matcher(password);
		while (matcher.find()) {
			digitsCount++;
		}
		if (digitsCount < minDigits) {
			throw new PasswordPolicyException("Password must have at least " + minDigits + " number(s)");
		}

		int specialCount = 0;
		matcher = SPECIAL.matcher(password);
		while (matcher.find()) {
			specialCount++;
		}
		if (specialCount < minSpecialChars) {
			throw new PasswordPolicyException("Password must have at least " + minSpecialChars + " special character(s)");
		}
	}
}