Restricting access to content

I’m developing a functionality to let only customers and doctors have access to exam results. But i’m not so sure about the strenght of my code in securing view only to those authorised.

I’ve gotten so far as to create the ‘exam’ post type to handle the information and added the metabox to save doctor and patient info in every exam (doctor and patient are also custom roles for users, with capabilities similar to subscribers).

then i’ve created this function to check if the user trying to view content is entitled to it:

 * Checks if user is logged in and has access to that specific exam
function rm_userauth_check() {
    global $current_user;
      $doctor = get_post_custom_values('doctor');
      $patient = get_post_custom_values('patient');
      $loggeduser = $current_user->user_login;
      $nicename = $current_user->display_name;
      $mainrole = $current_user->roles;

  if ($current_user->data !== null) {

      if ($mainrole[0] == 'doctor' && $loggeduser == $doctor[0]) {
          return true; // this user is a doctor and is assigned to this exam
      } elseif ($mainrole[0] == 'patient' && $loggeduser == $patient[0]) {
          return true; // this user is a patient and is assigned to this exam
      } else {
          return false; // this user is not assigned to this exam
  } else {
      return false; // user is not logged in

and now i’m calling it on my single-exam.php file as

        <?php if (function_exists('rm_userauth_check')) : ?>

        <?php if (rm_userauth_check()) : ?>

        <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>

            <?php get_template_part( 'content', 'single' ); ?>

        <?php endwhile; // end of the loop. ?>
           <?php else : ?>
                       <?php wp_redirect( home_url() ); exit; ?>
           <?php endif; ?>
    <?php endif; ?>

How does it look to you? Am i going the right way here or should i try another method?

Solutions Collecting From Web of "Restricting access to content"

The easiest way is to use if ( current_user_can( 'capability' ) ) // do stuff. You’ll find more about capabilities in the codex. You can also inspect the data some user has attached with normal var_dump() and else. I also got a pretty old plugin for that. But I’m not sure if it still works with the current WP version. If it does, you’ll be presented with close to all user data and some hints & snippets on a new admin page.