functions.php: support for OAuth2 authentication with openid-connect with src.openmamba.org

This commit is contained in:
Silvan Calarco 2024-11-16 15:22:48 +01:00
parent 166247ed5e
commit 49be8da9ff

View File

@ -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 );