• I encountered heaps of issues with getting the current user if they’re logged in using JWT. With some help from someone else on here I use this solution.

    Maybe you could incorporate a similar function into the plugin.

    e.g.

    function get_current_user_id() {
      if (class_exists('Jwt_Auth_Public')) {
          $jwt = new \Jwt_Auth_Public('jwt-auth', '1.1.0');
          $token = $jwt->validate_token(false);
          if (\is_wp_error($token)) {
              return false;
          }
    
          return $token->data->user->id;
      } else {
          return false;
      }
    }
Viewing 5 replies - 1 through 5 (of 5 total)
  • God job. For readability: (and UNIX coding style…)

    
    function get_current_user_id() {
      if (!class_exists('Jwt_Auth_Public'))
          return false;
     
     $jwt = new \Jwt_Auth_Public('jwt-auth', '1.1.0');
     $token = $jwt->validate_token(false);
     if (\is_wp_error($token))
              return false;
     return $token->data->user->id;
    }
    Thread Starter botoxparty

    (@adamhammad)

    @mullibahr Nice one! Thanks!

    I have added the following code in functions.php to hold the User_id, avatar, role

    function jwt_auth_function($data, $user) { 
    	$data['user_role'] = $user->roles; 
    	$data['user_id'] = $user->ID; 
    	$data['avatar']= get_avatar_url($user->ID);
    	return $data; 
    } 
    	add_filter( 'jwt_auth_token_before_dispatch', 'jwt_auth_function', 10, 2 );

    If you want to use the token then please use this code for the same.

    function add_extra_para($data, $user)
    {
       
         $data = array(
          'success' => true,
          'token'    => $data['token'],
          'user_email' => $user->data->user_email,
          'user_nicename' => $user->data->user_nicename,
          'user_display_name' => $user->data->display_name,
          'user_id' => $user->data->ID,
        );
    
         return $data;
    }
    add_filter('jwt_auth_token_before_dispatch', 'add_extra_para', 10, 2);
    
    • This reply was modified 5 years, 6 months ago by Riddhi Mehta.

    Simply use the Access Token with a GET request to /wp/v2/users/me after getting your access token. (Rather like validating the new token)

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Feature Request: get_current_user_id’ is closed to new replies.