<?php
/*
* Copyright (c) 2009-2010 ATMAIL. All rights reserved
* See http://atmail.com/license.php for license agreement
*/

class Atmail_Auth_Adapter_Http_Resolver_DbTable implements Zend_Auth_Adapter_Http_Resolver_Interface
{
	private $_config;
	    
	public function __construct( $configArray = array() ) {
	
		if( count($configArray) > 0 )
			$this->_config = $configArray;

    }

    public function resolve( $username, $realm ) {
        if (empty($username))            
			throw new Zend_Auth_Adapter_Http_Resolver_Exception('Username is required');
        else if (!ctype_print($username) || strpos($username, ':') !== false)
            throw new Zend_Auth_Adapter_Http_Resolver_Exception('Username must consist only of printable characters, '
                                                              . 'excluding the colon');
        if (empty($realm))
            throw new Zend_Auth_Adapter_Http_Resolver_Exception('Realm is required');
        else if (!ctype_print($realm) || strpos($realm, ':') !== false)
            throw new Zend_Auth_Adapter_Http_Resolver_Exception('Realm must consist only of printable characters, '
                                                              . 'excluding the colon.');
        $dbAdapter = Zend_Registry::get('dbAdapter');
        //TODO: upgrade query to handle disabled accounts etc.
        if( isset($this->_config['type']) && $this->_config['type'] == 'admin' ) 
		{
		
			$q = 'SELECT * FROM AdminUsers WHERE Username = \'' . $username . '\'';
		    $rows = $dbAdapter->fetchAll($q);
	        if(count($rows) == 1) 
			{
				//if exactly 1 row returned 
				return $rows[0]['Password']; 
        		        				
			}
			
		} 
		else
		{
			
			$q = 'SELECT * FROM UserSession WHERE Account = \'' . $username . '\'';
	        $rows = $dbAdapter->fetchAll($q);
	        if(count($rows) == 1) 
			{

				//if exactly 1 row returned 
				$row = $rows[0];
				return MD5($row['Account'] . ':' . $realm . ':' . $row['Password']); 

			}
			//return 'fde17b91c3a510ecbaf7dbd37f59d4f8'; // valid someUser:Some Realm:somePassword hash
			//return '00000000000000000000000000000000'; // bogus hash for testing
			
		} 
    }
}