<?php
###############################################################################
# Login.php
#
#
# @author Anil Kumar <akumar@codepunch.com>
# @link   https://codepunch.com
#
############################################################################### 

namespace 	CodePunch\UI\Modules;

use 		CodePunch\Base\Util as UTIL;

###############################################################################

class Login  {
	
	###########################################################################
	
	public function get($auth) 
	{		
		if($auth) {
			$primaryAuth = $auth->getPrimaryAuthentication();
			if($primaryAuth != null && class_exists($primaryAuth)) {
				return $primaryAuth->get($auth);
			}
			
			// Is SAML mandatory?
			$ssoname = "";
			if(\CodePunch\Config\SAML\SAML::getStatus($auth, $ssoname)) {
				$usesaml = false;
				$setup = new \CodePunch\Config\Settings($auth);
				$samlidp = $setup->getOption("saml_idp", "");
				if($samlidp != "") {
					$class = "\\CodePunch\\Config\\SAML\\" . $samlidp;
					if(class_exists($class)) 
						$usesaml = $setup->getBoolean("saml_force", false);
				}
				if($usesaml) {
					if(UTIL::is_request_key_set("logout")) {
						$auth->processLogout();
						// We don't want to close the SAML session 
						// we will only close SED session
						// So, just show a logged out message 
						$url = UTIL::get_root_url() . "saml.php?lo";
						header("Location: $url");
						exit;
					}
					// Allow use of ?native to force non-saml
					if(!UTIL::is_request_key_set("native")) {
						$url = UTIL::get_root_url() . "saml.php";
						header("Location: $url");
						exit;
					}
				}
			}
			
			if(UTIL::is_request_key_set("2fa") || UTIL::is_request_key_set("duo_code")) {
				$secondary = $auth->getSecondaryAuthentication();
				if($secondary != null && class_exists($secondary)) {
					$sc = new $secondary($auth);
					if($sc->isEnabled()) 
						return $sc->get();
					else {
						$username = UTIL::get_from_array($_SESSION[\CodePunch\Config\Auth::USERNAME], "");
						$auth->processSecondaryLogin($username, false);
					}
				}
			}
		}
		return array('template'=>'login');
	}
	
	###########################################################################
}
