Last active
January 16, 2020 05:27
-
-
Save justinledelson/9a784a87be944a26d6e294c22a4395f9 to your computer and use it in GitHub Desktop.
Set WP_User role from Auth0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// ============================================================================= | |
// AUTH0 CONFIG | |
// ============================================================================= | |
function auth0_docs_hook_auth0_user_login( $user_id, $userinfo, $is_new, $id_token, $access_token, $refresh_token ) { | |
// Save role from $userinfo object | |
$wpRole = $userinfo['app_metadata']['wordpress_role']; | |
// $wpRole = $userinfo => app_metadata => wordpress_role; | |
// Fetch the WP_User object of our user. | |
$u = new WP_User( $user_id ); | |
// Update WP_User with Auth0 Role | |
if($wpRole == "member") { | |
$u->set_role( 'member' ); | |
header("Location: https://wordpress-265436-947651.cloudwaysapps.com/member-dashboard/"); | |
header("Connection: close"); | |
exit(0); // Optional, prevents any accidental output | |
} elseif ($wpRole == "vendor") { | |
$u->set_role( 'vendor' ); | |
header("Location: https://wordpress-265436-947651.cloudwaysapps.com/vendor-dashboard/"); | |
header("Connection: close"); | |
exit(0); // Optional, prevents any accidental output | |
} elseif ($wpRole == "teacher") { | |
$u->set_role( 'teacher' ); | |
header("Location: https://wordpress-265436-947651.cloudwaysapps.com/teacher-dashboard/"); | |
header("Connection: close"); | |
exit(0); // Optional, prevents any accidental output | |
} elseif ($wpRole == "designer") { | |
$u->set_role( 'designer' ); | |
header("Location: https://wordpress-265436-947651.cloudwaysapps.com/designer-dashboard/"); | |
header("Connection: close"); | |
exit(0); // Optional, prevents any accidental output | |
} | |
// SAMPLE CODE | |
echo '<strong>WP user ID</strong>:<br>' . $user_id . '<hr>'; | |
echo '<strong>Auth0 Role</strong>:<br>' . $wpRole . '<hr>'; | |
echo '<strong>Auth0 user info</strong>:<br><pre>' . print_r( $userinfo, true ) . '</pre><hr>'; | |
echo '<strong>Added to WP DB?</strong>:<br>' . ( $is_new ? 'yep' : 'nope' ) . '<hr>'; | |
echo '<strong>ID Token</strong>:<br>' . ( $id_token ? $id_token : 'not provided' ) . '<hr>'; | |
echo '<strong>Access Token</strong>:<br>' . ( $access_token ? $access_token : 'not provided' ) . '<hr>'; | |
echo '<strong>Refresh Token</strong>:<br>' . ( $refresh_token ? $refresh_token : 'not provided' ) . '<hr>'; | |
wp_die( 'Login successful! <a href="' . home_url() . '">Home</a>' ); | |
} | |
add_action( 'auth0_user_login', 'auth0_docs_hook_auth0_user_login', 10, 6 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment