Search code examples
lithium

Accessing auth session data (Lithium + MongoDB)


Okay, so hopefully I am asking this question correctly:

I set up my user model & controller, as well as my session model and controller... but I want to render some of the session info onto a page.

for example
If I were to login to a page, it would read "Brian" (or whatever my username is that I used for my login)

I hope I am not asking a repeated question -- I have searched this question pretty extensively and haven't found a solution yet. Thanks a lot!


Solution

  • If your session (set in a config/bootstrap file) is called "default" then just run check ...

    $user = Auth::check('default');
    

    Then $user will have an array of the user data in the session, so if you have a first_name field in your database/session you could do:

    echo $user["first_name"];
    

    I created a helper to clean this up a little, I called it: extensions/helper/Login.php

    <?php
    
    namespace app\extensions\helper;
    use lithium\security\Auth;
    
    class Login extends \lithium\template\Helper {
    
        public function user() {
    
            $user = Auth::check('default');
    
            return $user;
        }
    
        public function fullName() {
    
            $user = self::user();
    
            return $user["first_name"] . " " . $user["last_name"];
        }
    
    }
    
    ?>
    

    Then in my Views I used it like ...

    <?=$this->login->fullName(); ?>