/**
 * Attempt to authenticate the current request based on request params and basic auth
 * @param iclicker_controller $cntlr the controller instance
 * @throws ClickerSecurityException if authentication is impossible given the request values
 * @throws ClickerSSLRequiredException if the auth request is bad (requires SSL but SSL not used)
 */
function iclicker_handle_authn($cntlr)
{
    global $CFG;
    // extract the authn params
    $auth_username = optional_param(iclicker_controller::LOGIN, NULL, PARAM_NOTAGS);
    $auth_password = optional_param(iclicker_controller::PASSWORD, NULL, PARAM_NOTAGS);
    if (empty($auth_username) && isset($_SERVER['PHP_AUTH_USER'])) {
        // no username found in normal params so try to get basic auth
        $auth_username = $_SERVER['PHP_AUTH_USER'];
        $auth_password = $_SERVER['PHP_AUTH_PW'];
        if (empty($auth_username)) {
            // attempt to get it from the header as a final try
            list($auth_username, $auth_password) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
        }
    }
    if (iclicker_service::$block_iclicker_sso_enabled && !empty($auth_password)) {
        // when SSO is enabled and the password is set it means this is not actually a user password so we can proceed without requiring SSL
    } else {
        // this is a user password so https must be used if the loginhttps option is enabled
        $ssl_request = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443;
        $ssl_required = isset($CFG->forcehttps) && $CFG->forcehttps == true || isset($CFG->loginhttps) && $CFG->loginhttps == true;
        if ($ssl_required && !$ssl_request) {
            throw new ClickerSSLRequiredException('SSL is required when performing a user login (and sending user passwords)');
        }
    }
    //$session_id = optional_param(iclicker_controller::SESSION_ID, NULL, PARAM_NOTAGS);
    if (!empty($auth_username)) {
        $sso_key = optional_param(iclicker_controller::SSO_KEY, NULL, PARAM_NOTAGS);
        iclicker_service::authenticate_user($auth_username, $auth_password, $sso_key);
        // throws exception if fails
        //} else if ($session_id) {
        //    $valid = FALSE; // validate the session key
        //    if (! $valid) {
        //        throw new SecurityException("Invalid "+iclicker_controller::SESSION_ID+" provided, session may have expired, send new login credentials");
        //    }
    }
    $current_user_id = iclicker_service::get_current_user_id();
    if (isset($current_user_id)) {
        $cntlr->setHeader(iclicker_controller::SESSION_ID, sesskey());
        $cntlr->setHeader('_userId', $current_user_id);
    }
}