<?php
//
// Shibboleth authentication for Icinga.
// Based on HTTPBasicAuthenticationModel.
//
// Usage:
// Icinga-web login page must use a Shibboleth-SP lazy session,
// this module must be activated in your conf.d/auth.xml,
// then call https://yourserver.example.org/Shibboleth.sso/Login?target=https://yourserver.example.org/icinga-web/
//
//
// Manuel Haim, 12-Dec-2012


class AppKit_Auth_Provider_Shib2Model extends AppKitAuthProviderBaseModel implements AppKitIAuthProvider {


    protected $parameters_default = array(
                                        self::AUTH_MODE => self::MODE_SILENT
                                    );



    private $auth_name = null;


    public function doAuthenticate(NsmUser $user, $password, $username=null, $authid=null) {
        if(!isset($_SERVER['orgunit-dn']) || strpos($_SERVER['orgunit-dn'],'ou=HRZ,')===false) {
          $this->log('Auth.Provider.Shib2: Access denied', AgaviLogger::DEBUG);
          return false;
        }
        $tuser = $this->loadUserByDQL($user->user_name);
        $username = $user->user_name;
        $authname = $this->getAuthName();
        if($this->getParameter('auth_lowercase_username',false) == true) {
            $username = strtolower($username);
            $authname = strtolower($authname);
        }
        if ($tuser && $tuser instanceof NsmUser && $username == $authname) {
            return true;
        }

        return false;
    }

    public function isAvailable($uid, $authid=null) {
        if(!isset($_SERVER['orgunit-dn']) || strpos($_SERVER['orgunit-dn'],'ou=HRZ,')===false) {
          $this->log('Auth.Provider.Shib2: Access denied 2', AgaviLogger::DEBUG);
          return false;
        }
        return true;
    }

    public function getUserdata($uid, $authid=false) {
        return array(
                   'user_firstname' => $_SERVER['givenName'],
                   'user_lastname'      => $_SERVER['sn'],
                   'user_name'          => $uid,
                   'user_email'          => $_SERVER['mail'],
                   'user_authsrc'       => $this->getProviderName(),
                   'user_disabled'      => 0
               );
    }


    //haimm: Get uid from Shibboleth session.
    public function  determineUsername() {
        if(!isset($_SERVER['orgunit-dn']) || strpos($_SERVER['orgunit-dn'],'ou=HRZ,')===false) {
          $this->log('Auth.Provider.Shib2: Access denied 1', AgaviLogger::DEBUG);
          return false;
        }
        if(isset($_SERVER['uid'])) {
            $this->auth_name = $_SERVER['uid'];
            $this->log('Auth.Provider.Shib2: Got data (uid=%s)', $this->auth_name, AgaviLogger::DEBUG);
        }
        return $this->auth_name;
    }

    public function getAuthName() {
        return $this->auth_name;
    }

}

?>