From 49be8da9ff30c12d93c6f076c058cd65aa8787e9 Mon Sep 17 00:00:00 2001 From: Silvan Calarco Date: Sat, 16 Nov 2024 15:22:48 +0100 Subject: [PATCH] functions.php: support for OAuth2 authentication with openid-connect with src.openmamba.org --- functions.php | 57 +++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 53 insertions(+), 4 deletions(-) diff --git a/functions.php b/functions.php index f95e67b..a7700a5 100644 --- a/functions.php +++ b/functions.php @@ -452,14 +452,33 @@ function wpb_imagelink_setup() { add_action('admin_init', 'wpb_imagelink_setup', 10); /* Security: restrict access to wp-json */ -function restrict_rest_api_to_localhost() { +function restrict_rest_api_access() { $whitelist = [ '127.0.0.1', "::1", '176.9.120.93', '2a01:4f8:151:7444::1:3' ]; - if( ! in_array($_SERVER['REMOTE_ADDR'], $whitelist ) ){ - die( 'REST API is disabled.' ); + // Allow whitelisted ip addresses + if (in_array($_SERVER['REMOTE_ADDR'], $whitelist) ){ + return; } + + // List of allowed endpoint prefixes (adjust as needed) + $allowed_prefixes = [ + 'openid-connect', // Allow /wp-json/openid-connect/* + // Add other prefixes here if needed + ]; + + // Get the current REST route + $request_uri = $_SERVER['REQUEST_URI']; + + // Check if the request URI matches any allowed prefix + foreach ($allowed_prefixes as $prefix) { + if (strpos($request_uri, '/it/wp-json/' . $prefix) === 0) { + return; // Allow access + } + } + + die( 'REST API is disabled.' ); } -add_action( 'rest_api_init', 'restrict_rest_api_to_localhost', 0 ); +add_action('rest_api_init', 'restrict_rest_api_access', 10, 3 ); /* Security: filter email domains frequently used for spam registrations */ function user_registration_filter($user_id, $email) { @@ -532,3 +551,33 @@ add_filter( 'template_include', function( $template ) { return get_theme_file_path() . '/distroquery.php'; } ); + +// openid-connect filters +function my_oidc_clients() { + if ( ! defined( 'OIDC_CLIENT_ID' ) || ! defined( 'OIDC_CLIENT_KEY' ) ) { + // Please define client id and key in wp-config.php. + return; + } + + return array( + OIDC_CLIENT_ID => array( + 'name' => 'openmamba package sources', + 'secret' => OIDC_CLIENT_KEY, + 'redirect_uri' => 'https://src.openmamba.org/user/oauth2/openmamba/callback', + 'grant_types' => array( 'authorization_code' ), + 'scope' => 'openid profile', + ), + ); +} +add_filter( 'oidc_registered_clients', 'my_oidc_clients' ); + +function my_oidc_capability() { + return 'read'; +} +add_filter( 'oidc_minimal_capability', 'my_oidc_capability' ); + +function my_user_claims($claims, $user) { + $claims['email'] = $user->user_email; + return $claims; +} +add_filter( 'oidc_user_claims', 'my_user_claims', 10, 2 );