richerlariviere
richerlariviere

Reputation: 809

CakePHP 3: How to properly check if a user is logged in

In CakePHP 3, I found two ways to find if a user is logged in.

1st solution

if(!is_null($this->Auth->user('id'))){
        // Logged in
}

2nd solution

if (!is_null($this->request->session()->read('Auth.User.id'))) {
    // Logged in
}

I think the first one is better because it's short and concise.

Is there a better way to verify if a user is logged in?

I'm not looking for speed necessarily. I want a clean and expressive way to write it.

Upvotes: 6

Views: 9997

Answers (3)

Carlos Espinoza
Carlos Espinoza

Reputation: 1175

In my applications, I always use a login method like this:

public function login() {
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {
            $this->Auth->setUser($user);
            return $this->redirect($this->Auth->redirectUrl());
        }
        $this->Flash->error('Your username/password is not valid');
    }elseif ($this->Auth->user()) {
        return $this->redirect($this->Auth->redirectUrl());
    }
}

With this, if a user is logged ( $this->Auth->user() ) and the request is not a POST one, I redirect to a default URL.

Upvotes: 0

Faisal
Faisal

Reputation: 4765

You can do this using session() helper.

$loggeduser = $this->request->session()->read('Auth.User');
if(!$loggeduser) {
    $userID = $loggeduser['id'];
    $firstName = $loggeduser['first_name'];
}

Upvotes: 2

Kamoris
Kamoris

Reputation: 505

I think the best way is just:

if ($this->Auth->user()) {...}

Upvotes: 18

Related Questions