Jump to content

$user-hasRole() returns sometimes true, sometimes false?


Eltom
 Share

Recommended Posts

Hi all!

if($session->login($username, $pass)) {
     echo ($user->hasRole('clubmember')==1?"yes":"no");
    .......
}
 
The above code snippet prints out "no" at the first login and "yes" at the second login.
The user has the role mentioned in the code, so I'm not seeing, what's happening here.
 
Sorry for all my stupid questions, sometimes it's hard to see the obvious(??).  :(
Link to comment
Share on other sites

Ok, now I discovered that $user isn't right available after login, but changing (redirecting) to another page helps:

if ($session->login($username, $pass)) {
     $session->redirect("/anotherpage");
} ...

On "anotherpage" I can check what I need:

if ($user->isLoggedin() {
   echo ($user->hasRole('clubmember')?"yes":"no"); // "yes" all the time now.
   .....
}

This is a workaround for me, but shouldn't $user be available right after $session->login(); ??

Digging deeper:

Posting $username and $pass (always using the same credentials, given $username = "thomas") twice to the same page lead to confusing results:

$session->login($username, $pass);
echo ( $user->isLoggedin()?"yes":"no" );          // "yes" after every login! Plausible result 
echo ( $user->name);                              // "guest" after the first post, "thomas" after the second post (?)
echo ( $user->hasRole('clubmember')?"yes":"no "); // "no" after first post, "yes" after second post (?)

So there seems to be something I haven't understood from the beginning...

Link to comment
Share on other sites

This is a workaround for me, but shouldn't $user be available right after $session->login(); ??

If there was a way for us to make PW automatically reassign the $user variable after login, we'd do it. It's not technically possible for PW to do that (it's a matter of variable scope). That's why you'd have to do what Adrian suggested and assign the $user variable yourself from the result of login(). However, what Soma was getting at before he gave up was even better because it wouldn't trash the $user variable if the login failed. So something like this might be ideal:

$u = $session->login($username, $pass); 
if($u) {
  $user = $u;
  echo "logged in";
}
  • Like 3
Link to comment
Share on other sites

ProcessWire requires sessions, so it's not something you have to install. Though the database sessions module is an optional install. But $user->isLoggedin(); has to do with the current user only. It cannot tell you if other users (separate from the current session) are logged in or not. 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...