<?php

/**
 * Class: StudipAuthSimpleSamlPHP
 * author: Rene Ceska <ceskar2001@gmail.com>
 * This class is used to authenticate users through SimpleSAMLphp.
 * This code was inspired by other Stud.IP auth plugins.
 *
 * @since Stud.IP 6.0
 */
class StudipAuthSimpleSamlPHP extends StudipAuthSSO
{
    // Name of the SimpleSAMLphp SP
    public string $sp_name;

    // Name of attribute that contains username (if empty it will use NameID as username)
    public ?string $username_attribute = null;

    public ?string $path_to_simple_saml_php = null;

    public ?array $userdata = null;
    public SimpleSAML\Auth\Simple $as;

    /**
     * Constructor: read auth information from remote SP.
     */
    public function __construct($config = [])
    {
        parent::__construct($config);

        if(!isset($this->path_to_simple_saml_php)){
            require_once('/var/simplesamlphp/src/_autoload.php');
        }else{
            require_once($this->path_to_simple_saml_php );
        }

        if (!isset($this->plugin_fullname)) {
            $this->plugin_fullname = _('SAML');
        }
        if (!isset($this->login_description)) {
            $this->login_description = _('für Single Sign On mit SAML');
        }

        // check if user chosen to login through this plugin
        if (Request::get('sso') === $this->plugin_name) {
            $this->as = new SimpleSAML\Auth\Simple($this->sp_name);
        }
    }

    /**
     * Return the current username.
     */
    public function getUser()
    {
        return $this->getUserData('username');
    }

    /**
     * Validate the username passed to the auth plugin.
     * Note: This triggers authentication if needed.
     */
    public function verifyUsername($username)
    {
        if (isset($this->userdata)) {
            // use cached user information
            return $this->getUser();
        }

        // check if user is already authenticated and if not, authenticate them
        if (!$this->as->isAuthenticated()) {
            $this->as->requireAuth();
        }

        $this->userdata = [];

        // get username
        if (empty($this->username_attribute)) {
            $this->userdata['username'] =  $this->as->getAuthData('saml:sp:NameID')->getValue();
        } else {
            $this->userdata['username'] =  $this->as->getAttributes()[$this->username_attribute];
        }

        // get other user attributes
        $this->userdata = array_merge($this->userdata, $this->as->getAttributes());

        // cleanup session so it does not interfere with Stud.IP session
        SimpleSAML\Session::getSessionFromRequest()->cleanup();

        return $this->getUser();
    }

    /**
     * Callback that can be used in user_data_mapping array.
     */
    public function getUserData($key)
    {
        return $this->userdata[$key];
    }

    /**
     * Logout the user.
     */
    public function logout(): void
    {
        $auth = new \SimpleSAML\Auth\Simple($this->sp_name);
        $auth->Logout();
    }

}