/*
 * Licensed to Jasig under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Jasig licenses this file to you 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 the following location:
 *
 *   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 edu.fsu.cas.authentication.handler;

import java.io.IOException;

import javax.validation.constraints.NotNull;

import org.jasig.cas.adaptors.jdbc.AbstractJdbcUsernamePasswordAuthenticationHandler;
import org.jasig.cas.authentication.handler.AuthenticationException;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.springframework.dao.IncorrectResultSizeDataAccessException;

import blackboard.platform.authentication.password.MD5ValidationAlgorithm;
import blackboard.platform.authentication.password.SSHAValidationAlgorithm;
import blackboard.platform.security.authentication.validators.PasswordValidator;

/**
 * Class that if provided a query that returns a password (parameter of query
 * must be username) will compare that password to a translated version of the
 * password provided by the user. If they match, then authentication succeeds.
 * Default password translator is plaintext translator.
 *org.jasig.cas.authentication.handler.
 * @author Scott Battaglia
 * @author Dmitriy Kopylenko
 * @author Marvin S. Addison
 *
 * @since 3.0
 */
public class BBDBAuthenticationHandler extends AbstractJdbcUsernamePasswordAuthenticationHandler {

    @NotNull
    private String sql;

    protected final boolean authenticateUsernamePasswordInternal(final UsernamePasswordCredentials credentials) throws AuthenticationException {
        final String username = getPrincipalNameTransformer().transform(credentials.getUsername());
        final String password = credentials.getPassword();
        String encryptedPassword = password;
        try {
        	
        	String dbPassword = getJdbcTemplate().queryForObject(this.sql, String.class, username);
        	//Begins custom code for encrypting via MD5 unsalted or SHA512 salted hashing
        	final String[] bbPasswordFields = dbPassword.split(":");

        	if (bbPasswordFields.length == 1) {
        		//md5
        		return new MD5ValidationAlgorithm().validatePassword(encryptedPassword, dbPassword);
        	} else {
        		//ssha
        		return new SSHAValidationAlgorithm().validatePassword(encryptedPassword, dbPassword);
        	}
        } catch (final IncorrectResultSizeDataAccessException e) {
            // this means the username was not found.
            return false;
        } catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return false;
    }

    /**
     * @param sql The sql to set.
     */
    public void setSql(final String sql) {
        this.sql = sql;
    }
    
    public static void main(String[] args) throws IOException {
    	// This is Derek's fancy test, so if it stops working, he'd LOVE TO HEAR ABOUT IT!
    	try {
    		String passwordFromDb = "{SSHA}HmacSHA512:SHA-512:3000:yz9LhydJ7Bq93rl+OtXTTxsddQSRPbyJ61ZayYh4qCa2hgMV/UvXH0rgclcbyB/le6ztF6sYQToTzj9OuEEB1Q==:SCK0SQmTOADQbhS6BzmdnXSigxswjI5ZX6TasiV9ffY+CCdwUX7pZmcn0apSE1EwRPrk1LupRkq6RQA7Ro3hMA==";
    		System.out.println(new SSHAValidationAlgorithm().validatePassword("blackboard", passwordFromDb));
    		String dbPassword = "3f78011271f4e20d7dab7093b42eac47";
    		System.out.println(new MD5ValidationAlgorithm().validatePassword("blackboard", dbPassword));
    		String encryptedPassword = "3f78011271f4e20d7dab7093b42eac47";
    		System.out.println(dbPassword.equals(encryptedPassword));
    	} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}