How to prevent some WP users from being able to login to Discourse

There is a wpdc_sso_provider_before_sso_redirect action hook that can be used to bypass SSO. The hook is fired right before the SSO login redirect to Discourse. It is passed the current WordPress user_id and user object as parameters: https://github.com/discourse/wp-discourse/blob/master/lib/sso-provider/discourse-sso.php#L189.

The basic idea is that if a user doesn’t meet the condition you have set for logging into Discourse, you redirect them to some page and then call exit. If the user does meet your condition, do nothing.

add_action( 'wpdc_sso_provider_before_sso_redirect', 'wpdc_custom_check_user_membership', 10, 2 );
function wpdc_custom_check_user_membership( $user_id, $user ) {
    if ( /* Some condition that returns true if the user doesn't meet the membership requirement */ ) {
	    wp_safe_redirect( home_url() );

	    exit;

    }
}

If you have enabled the Create or Sync Discourse Users on Login option, you will also need to prevent WordPress users from being automatically created on Discourse when they login to your WordPress site. As of WP Discourse version 1.6.9 you can do this by hooking into the wpdc_bypass_sync_sso filter. That filter hook is passed three parameters: $bypass_sync (defaults to false), $user_id, and $user (a WordPress user object.) The code for it is here.

To bypass the sync_sso_record function, you need to hook into the filter with a function that will return true for users you would like to not be synced with Discourse.

add_filter( 'wpdc_bypass_sync_sso', 'wpdc_custom_bypass_sync_sso', 10, 3 );
function wpdc_custom_bypass_sync_sso( $bypass_sync, $user_id, $user ) {
    if ( /* Some condition that returns true if the user doesn't meet the membership requirement */  ) {

        $bypass_sync = true;
    }

    return $bypass_sync;
}
8 Likes