I’m looking to implement Discourse/WP SSO as a way to allow users to login to my WordPress site with Discourse accounts that they already have. In that process I was hoping to be able to bring along information (group, trust level) and store that in WordPress to allow them to view/hide certain content. Is this currently possible?
The wp-discourse plugin isn’t doing this yet, but it’s something that people have been asking for. What I think could be done in the near future would be to bring that information across from Discourse to WordPress and store it as user metadata. It would be up to a site’s developer to make use of the information.
That is exactly the sort of functionality I would be looking for. Just store that information as user meta data and then the WP features can check against it.
So if this isn’t standard right now, can anyone point me in the right direction of where to go toward implementing it?
You can use something like this and hook it into the wp_login
action (remove the public
keyword.)
public function lookup_discourse_user( $username, $wp_user ) {
$base_url = $this->options['url'];
$api_key = $this->options['api-key'];
$api_username = $this->options['publish-username'];
if ( empty( $base_url ) || empty( $api_key ) || empty( $api_username ) ) {
return new \WP_Error( 'discourse_configuration_error', 'The WP Discourse plugin has not been properly configured.' );
}
// Try to get the user by external_id.
$external_user_url = esc_url_raw( $base_url . "/users/by-external/$wp_user->ID.json" );
$external_user_url = add_query_arg( array(
'api_key' => $api_key,
'api_username' => $api_username,
), $external_user_url );
$response = wp_remote_get( $external_user_url );
if ( ! DiscourseUtilities::validate( $response ) ) {
return new \WP_Error( 'discourse_response_error', 'There has been an error in retrieving the user data from Discourse.' );
}
$user_data = json_decode( wp_remote_retrieve_body( $response ), true );
return $user_data;
}
You can get the options in your theme or a plugin by calling $options = WPDiscourse\Utilities\Utilities::get_options()
. You can use the validate
method by calling WPDiscourse\Utilities\Utilities::validate( $response )
.
In the next update to the plugin, I might be able to add an option to sync user_data on login. It probably won’t sync all the data that you’re looking for, but an action could be added that would let you access the user_data.