Files
wordpress-sso/openflyers-sso.php
Lucas HENRY 952607a112 OpenFlyers SSO WordPress plugin 1.1.1
Import of the 1.1.0 archive plus a CLI guard on the two test scripts:
served over HTTP from wp-content/plugins they would delete the plugin
settings and create test accounts on the site.
2026-09-11 20:10:27 +02:00

608 lines
19 KiB
PHP

<?php
/**
* Plugin Name: OpenFlyers SSO
* Plugin URI: https://openflyers.com
* Description: Authentification des membres d'un espace prive WordPress avec leurs identifiants OpenFlyers (OAuth 2.0, mTLS et signature HTTP). Aucun mot de passe OpenFlyers n'est stocke sur le site.
* Version: 1.1.1
* Author: OpenFlyers
* License: GPL-2.0-or-later
* Text Domain: openflyers-sso
*
* @package OpenFlyers_SSO
*
* @link https://doc4-fr.openflyers.com/Plugin-WordPress Documentation publique
* @link https://work.openflyers.com/OF4-WordPress-SSO-plugin Fiche interne
*/
// Prevent direct access.
if (!defined('ABSPATH')) {
exit;
}
define('OF_SSO_VERSION', '1.1.1');
define('OF_SSO_FILE', __FILE__);
define('OF_SSO_PATH', plugin_dir_path(__FILE__));
define('OF_SSO_OPTION', 'of_sso_settings');
define('OF_SSO_USER_META', 'of_sso_user_id');
/**
* Class OF_SSO_Logger
*
* Minimal logger. Writes through error_log() so nothing lands in a publicly readable file.
*/
class OF_SSO_Logger
{
/**
* Log a message when debug mode is enabled in the plugin settings.
*
* @param string $message Message to log.
* @return void
*/
public static function log($message)
{
$settings = of_sso_get_settings();
if (empty($settings['debug'])) {
return;
}
error_log('[OpenFlyers SSO] ' . $message);
}
}
/**
* Return the plugin settings, merged with their defaults.
*
* @return array
*/
function of_sso_get_settings()
{
$defaults = array(
'base_url' => 'https://openflyers.com',
'platform' => '',
'client_id' => '',
'client_secret' => '',
'cert_dir' => '',
'auth_cert' => '',
'auth_key' => '',
'sign_cert' => '',
'sign_key' => '',
'ca_cert' => '',
'server_sign_cert' => '',
'key_passphrase' => '',
'redirect_uri' => '',
'send_x_ssl_cert' => 0,
'auto_create' => 0,
'default_role' => 'subscriber',
'redirect_after_login' => '',
'show_login_button' => 1,
'debug' => 0,
);
$settings = get_option(OF_SSO_OPTION, array());
return wp_parse_args(is_array($settings) ? $settings : array(), $defaults);
}
/**
* Return the callback URL that must be registered as the redirect URL in OpenFlyers.
*
* @return string
*/
function of_sso_get_redirect_uri()
{
$settings = of_sso_get_settings();
if (!empty($settings['redirect_uri'])) {
return $settings['redirect_uri'];
}
return home_url('/?of_sso=callback');
}
/**
* Conventional file names inside the certificate folder, as delivered by OpenFlyers.
*
* @return array Setting key => expected file name.
*/
function of_sso_cert_file_names()
{
return array(
'auth_cert' => 'auth_cert.crt',
'auth_key' => 'auth.key',
'sign_cert' => 'sign_cert.crt',
'sign_key' => 'sign.key',
'ca_cert' => 'ca.crt',
'server_sign_cert' => 'sign_cert_server.crt',
);
}
/**
* Resolve the six certificate paths.
*
* A single folder is enough when the files carry their standard names; any file stored elsewhere,
* or under another name, can still be pointed at individually in the advanced settings.
*
* @param array|null $settings Settings to resolve, current ones when omitted.
* @return array Setting key => absolute path (empty string when neither source provides one).
*/
function of_sso_resolve_cert_paths($settings = null)
{
$settings = is_array($settings) ? $settings : of_sso_get_settings();
$folder = isset($settings['cert_dir']) ? rtrim(trim($settings['cert_dir']), '/\\') : '';
$paths = array();
foreach (of_sso_cert_file_names() as $key => $fileName) {
$explicit = isset($settings[$key]) ? trim($settings[$key]) : '';
if ($explicit !== '') {
$paths[$key] = $explicit;
continue;
}
$derived = ($folder === '') ? '' : $folder . DIRECTORY_SEPARATOR . $fileName;
// ca.crt is optional: it overrides the CA bundle used to verify the OpenFlyers server.
// When the folder does not hold one, fall back to the system bundle rather than failing.
if ($key === 'ca_cert' and $derived !== '' and !is_readable($derived)) {
$derived = '';
}
$paths[$key] = $derived;
}
return $paths;
}
/**
* Build a configured protocol client, or false when the plugin is not fully configured.
*
* @return OF_SSO_Client|false
*/
function of_sso_get_client()
{
$settings = of_sso_get_settings();
if (empty($settings['client_id']) or empty($settings['base_url'])) {
return false;
}
// Hosted platforms live under a code (openflyers.com/mon-club/oauth). A dedicated or local
// install answers at the domain root instead, and then the code is simply left empty.
$root = untrailingslashit($settings['base_url']);
if (!empty($settings['platform'])) {
$root .= '/' . trim($settings['platform'], '/');
}
$root .= '/oauth';
$config = array(
'client_id' => $settings['client_id'],
'client_secret' => $settings['client_secret'],
'authorize_uri' => $root . '/authorize.php',
'token_uri' => $root . '/access_token.php',
'resource_uri' => $root . '/resources.php',
'revoke_uri' => $root . '/revoke.php',
'key_passphrase' => $settings['key_passphrase'],
'send_x_ssl_cert' => $settings['send_x_ssl_cert'],
);
$config += of_sso_resolve_cert_paths($settings);
return new OF_SSO_Client(apply_filters('of_sso_client_config', $config));
}
/**
* Return the URL that starts an OpenFlyers login.
*
* @param string $redirectTo Where the member should land once logged in.
* @return string
*/
function of_sso_login_url($redirectTo = '')
{
$args = array('of_sso' => 'login');
if (!empty($redirectTo)) {
$args['redirect_to'] = rawurlencode($redirectTo);
}
return add_query_arg($args, home_url('/'));
}
/**
* Tell whether the current user is logged in through OpenFlyers.
*
* @return bool
*/
function of_sso_is_member()
{
if (!is_user_logged_in()) {
return false;
}
return (bool) get_user_meta(get_current_user_id(), OF_SSO_USER_META, true);
}
require_once OF_SSO_PATH . 'includes/class-of-sso-client.php';
require_once OF_SSO_PATH . 'includes/class-of-sso-admin.php';
/**
* Class OF_SSO_Auth
*
* Drives the authorization code flow and maps OpenFlyers members onto WordPress users.
*/
class OF_SSO_Auth
{
/**
* Lifetime, in seconds, of a pending authorization request.
*/
const STATE_TTL = 600;
/**
* Register the hooks.
*
* @return void
*/
public static function init()
{
add_action('init', array(__CLASS__, 'route'));
add_action('login_form', array(__CLASS__, 'renderLoginButton'));
add_filter('login_message', array(__CLASS__, 'renderLoginError'));
add_shortcode('openflyers_login', array(__CLASS__, 'shortcodeLoginButton'));
add_shortcode('openflyers_membre', array(__CLASS__, 'shortcodeMemberOnly'));
}
/**
* Dispatch the plugin's own front-end URLs.
*
* @return void
*/
public static function route()
{
$action = isset($_GET['of_sso']) ? sanitize_key(wp_unslash($_GET['of_sso'])) : '';
if ($action === 'login') {
self::startLogin();
} elseif ($action === 'callback') {
self::handleCallback();
}
}
/**
* Start the authorization code flow: store the PKCE material, then redirect to OpenFlyers.
*
* @return void
*/
public static function startLogin()
{
$client = of_sso_get_client();
if (!$client) {
self::fail(__('Le module OpenFlyers SSO n\'est pas configure.', 'openflyers-sso'));
}
$state = bin2hex(random_bytes(16));
$codeVerifier = OF_SSO_Client::generateCodeVerifier();
$redirectTo = isset($_GET['redirect_to']) ? esc_url_raw(rawurldecode(wp_unslash($_GET['redirect_to']))) : '';
// The state is the key: it links the callback back to this pending request.
set_transient(
'of_sso_state_' . $state,
array(
'code_verifier' => $codeVerifier,
'redirect_to' => $redirectTo,
),
self::STATE_TTL
);
$url = $client->getAuthorizeUrl(
of_sso_get_redirect_uri(),
$state,
OF_SSO_Client::computeCodeChallenge($codeVerifier),
apply_filters('of_sso_scope', 'default.login')
);
wp_redirect($url);
exit;
}
/**
* Handle the return from OpenFlyers: validate the state, exchange the code, log the member in.
*
* @return void
*/
public static function handleCallback()
{
$client = of_sso_get_client();
if (!$client) {
self::fail(__('Le module OpenFlyers SSO n\'est pas configure.', 'openflyers-sso'));
}
// OpenFlyers reports a refused authorization with an error parameter.
if (isset($_GET['error'])) {
OF_SSO_Logger::log('Authorization refused: ' . sanitize_text_field(wp_unslash($_GET['error'])));
self::fail(__('La connexion a ete refusee par OpenFlyers.', 'openflyers-sso'));
}
$state = isset($_GET['state']) ? sanitize_text_field(wp_unslash($_GET['state'])) : '';
$code = isset($_GET['code']) ? sanitize_text_field(wp_unslash($_GET['code'])) : '';
if (empty($state) or empty($code)) {
self::fail(__('Reponse incomplete d\'OpenFlyers.', 'openflyers-sso'));
}
$pending = get_transient('of_sso_state_' . $state);
delete_transient('of_sso_state_' . $state);
// An unknown or expired state means the flow was tampered with, or simply took too long.
if (!is_array($pending) or empty($pending['code_verifier'])) {
self::fail(__('Session de connexion expiree ou invalide. Merci de reessayer.', 'openflyers-sso'));
}
$token = $client->exchangeCode($code, $pending['code_verifier'], of_sso_get_redirect_uri());
if (!is_array($token) or empty($token['access_token'])) {
OF_SSO_Logger::log('Token exchange failed: ' . $client->getLastError());
self::fail(__('Impossible d\'obtenir le jeton d\'acces aupres d\'OpenFlyers.', 'openflyers-sso'));
}
$ofUserId = $client->getUserId($token);
if (!$ofUserId) {
OF_SSO_Logger::log('User identifier retrieval failed: ' . $client->getLastError());
self::fail(__('Impossible de recuperer l\'identifiant du membre aupres d\'OpenFlyers.', 'openflyers-sso'));
}
$user = self::resolveUser($ofUserId, $token, $client);
if (is_wp_error($user)) {
self::fail($user->get_error_message());
}
wp_set_current_user($user->ID);
wp_set_auth_cookie($user->ID, false);
do_action('wp_login', $user->user_login, $user);
update_user_meta($user->ID, 'of_sso_last_login', time());
do_action('of_sso_after_login', $user, $ofUserId, $token);
$settings = of_sso_get_settings();
$redirectTo = !empty($pending['redirect_to'])
? $pending['redirect_to']
: (!empty($settings['redirect_after_login']) ? $settings['redirect_after_login'] : home_url('/'));
wp_safe_redirect($redirectTo);
exit;
}
/**
* Find, or optionally create, the WordPress user matching an OpenFlyers member.
*
* @param int $ofUserId OpenFlyers user identifier.
* @param array $token Token array, passed to the profile filter.
* @param OF_SSO_Client $client Configured client, passed to the profile filter.
* @return WP_User|WP_Error
*/
private static function resolveUser($ofUserId, array $token, OF_SSO_Client $client)
{
$settings = of_sso_get_settings();
$existing = get_users(
array(
'meta_key' => OF_SSO_USER_META,
'meta_value' => (string) $ofUserId,
'number' => 1,
'fields' => 'all',
)
);
// Extra data (name, e-mail, membership status) is not exposed by the 'default.login' scope.
// Sites needing it hook this filter and feed it from an OpenFlyers report.
$profile = apply_filters('of_sso_user_profile', array(), $ofUserId, $token, $client);
if (!empty($existing)) {
$user = $existing[0];
self::applyProfile($user->ID, $profile);
return $user;
}
if (empty($settings['auto_create'])) {
OF_SSO_Logger::log('No WordPress user linked to OpenFlyers id ' . $ofUserId);
return new WP_Error(
'of_sso_no_account',
__('Aucun compte de ce site n\'est associe a votre compte OpenFlyers. Merci de contacter le club.', 'openflyers-sso')
);
}
$login = 'of-' . $ofUserId;
$email = !empty($profile['user_email']) ? $profile['user_email'] : '';
$userId = wp_insert_user(
array(
'user_login' => $login,
'user_pass' => wp_generate_password(32, true, true),
'user_email' => $email,
'display_name' => !empty($profile['display_name']) ? $profile['display_name'] : $login,
'role' => $settings['default_role'],
)
);
if (is_wp_error($userId)) {
OF_SSO_Logger::log('User creation failed: ' . $userId->get_error_message());
return $userId;
}
update_user_meta($userId, OF_SSO_USER_META, (string) $ofUserId);
self::applyProfile($userId, $profile);
return get_user_by('id', $userId);
}
/**
* Copy the optional profile fields onto the WordPress user.
*
* @param int $userId WordPress user identifier.
* @param array $profile Profile data returned by the 'of_sso_user_profile' filter.
* @return void
*/
private static function applyProfile($userId, array $profile)
{
$fields = array_intersect_key(
$profile,
array_flip(array('user_email', 'display_name', 'first_name', 'last_name'))
);
if (empty($fields)) {
return;
}
$fields['ID'] = $userId;
wp_update_user($fields);
}
/**
* Stop the flow and send the member back to the login page with a message.
*
* @param string $message Message to display.
* @return void
*/
private static function fail($message)
{
set_transient('of_sso_error_' . self::visitorKey(), $message, 120);
wp_safe_redirect(add_query_arg('of_sso_error', '1', wp_login_url()));
exit;
}
/**
* Build a key identifying the current visitor, to store a one-shot error message.
*
* @return string
*/
private static function visitorKey()
{
$ip = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : '';
$agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '';
return md5($ip . $agent);
}
/**
* Display the pending error message on the WordPress login page.
*
* @param string $message Existing login page message.
* @return string
*/
public static function renderLoginError($message)
{
if (!isset($_GET['of_sso_error'])) {
return $message;
}
$error = get_transient('of_sso_error_' . self::visitorKey());
delete_transient('of_sso_error_' . self::visitorKey());
if (empty($error)) {
$error = __('La connexion via OpenFlyers a echoue.', 'openflyers-sso');
}
return $message . '<div id="login_error">' . esc_html($error) . '</div>';
}
/**
* Add an OpenFlyers button to the standard WordPress login form.
*
* @return void
*/
public static function renderLoginButton()
{
$settings = of_sso_get_settings();
if (empty($settings['show_login_button'])) {
return;
}
echo '<p style="margin-bottom:16px">' . self::buttonHtml(__('Se connecter avec OpenFlyers', 'openflyers-sso'), '') . '</p>';
}
/**
* Shortcode [openflyers_login] : login button, or a short message once logged in.
*
* @param array $atts Shortcode attributes.
* @return string
*/
public static function shortcodeLoginButton($atts)
{
$atts = shortcode_atts(
array(
'label' => __('Se connecter avec OpenFlyers', 'openflyers-sso'),
'redirect' => '',
),
$atts,
'openflyers_login'
);
if (is_user_logged_in()) {
$user = wp_get_current_user();
return '<p>' . sprintf(
/* translators: %s: display name of the logged in member. */
esc_html__('Connecte en tant que %s.', 'openflyers-sso'),
esc_html($user->display_name)
) . ' <a href="' . esc_url(wp_logout_url(home_url('/'))) . '">' . esc_html__('Se deconnecter', 'openflyers-sso') . '</a></p>';
}
return self::buttonHtml($atts['label'], $atts['redirect']);
}
/**
* Shortcode [openflyers_membre] : content reserved to members logged in through OpenFlyers.
*
* @param array $atts Shortcode attributes.
* @param string $content Enclosed content.
* @return string
*/
public static function shortcodeMemberOnly($atts, $content = '')
{
$atts = shortcode_atts(
array(
'message' => __('Cet espace est reserve aux membres du club.', 'openflyers-sso'),
),
$atts,
'openflyers_membre'
);
if (of_sso_is_member()) {
return do_shortcode($content);
}
return '<div class="of-sso-restricted"><p>' . esc_html($atts['message']) . '</p>'
. self::buttonHtml(__('Se connecter avec OpenFlyers', 'openflyers-sso'), '') . '</div>';
}
/**
* Render the login button markup.
*
* @param string $label Button label.
* @param string $redirect Where to land after login.
* @return string
*/
private static function buttonHtml($label, $redirect)
{
$target = !empty($redirect) ? $redirect : (is_singular() ? get_permalink() : '');
return '<a class="button button-primary of-sso-button" href="' . esc_url(of_sso_login_url($target)) . '">'
. esc_html($label) . '</a>';
}
}
OF_SSO_Auth::init();
OF_SSO_Admin::init();