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

class Atmail_HttpAuth 
{ 
	public function authenticated( $requiredLevel = null, $requiredUser = null, $requiredGroup = null, $requiredResourceAccessAuthority = null ) {
	 	$front = Zend_Controller_Front::getInstance(); 
        $request = $front->getRequest();
		$response = $front->getResponse();
	    //if $requiredGroup == 'admin' then we auth against a different source with basic auth only (this type of auth will only be used with API, and api can currently only handle basic auth)
		if( $requiredGroup == 'admin' ) {
			
			$config = array( 
			    'accept_schemes' => 'basic', 
			    'realm' => 'Atmail', 
			    'digest_domains' => '/', 
			    'nonce_timeout' => 3600 
			);
			$adapter = new Zend_Auth_Adapter_Http($config); 
			
			$basicResolver = new Atmail_Auth_Adapter_Http_Resolver_DbTable( array('type' => $requiredGroup) ); 
			$adapter->setBasicResolver($basicResolver); 
			$adapter->setRequest($request); 
	    	$adapter->setResponse($response); 
	    	$result = $adapter->authenticate(); 
			
			//if($result->isValid()) {
				//get other user data and log in session for use
			//}
			
		} else {
		
			$config = array( 
			    'accept_schemes' => 'digest', 
			    'realm' => 'Atmail', 
			    'digest_domains' => '/', 
			    'nonce_timeout' => 3600 
			); 
			$adapter = new Zend_Auth_Adapter_Http($config); 
			$digestResolver = new Atmail_Auth_Adapter_Http_Resolver_DbTable( array('type' => $requiredGroup) );
			$adapter->setDigestResolver($digestResolver); 
			
			$adapter->setRequest($request); 
	    	$adapter->setResponse($response); 
	    	$result = $adapter->authenticate();
			//$result = $auth->authenticate($adapter);

            //if($result->isValid()) {
				//get other user data and log in session for use
			//}
			
		} 
		    
		//consider forcing old userdata to null on fail/try log in as other user (not doing so would leave current user logged in)
	    //TODO: impliment matching matched credentials against required minimum credentials and respond accordingly
		return $result->isValid(); 
	}
}