how laravel get the user id from session? - laravel

Ok, now I know that if I use file driver for session, the sessions are going to be stored in /storage/framework/sessions , when I echo the Session::getId() I get the session Id that is stored in the storage.
when I open that session, it look like something like this:
a:7:{s:6:"_token";s:40:"hgG3c6DQ5XHEvwK7925CmfGUK54dhFPIWB2kFCUz";s:3:"url";a:0:{}s:9:"_previous";a:1:{s:3:"url";s:27:"http://e-learning.local/p2p";}s:6:"_flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}s:50:"login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d";i:6;s:3:"key";s:8:"smothing";s:22:"PHPDEBUGBAR_STACK_DATA";a:0:{}}
This is localhost development so no warry to publish the session
I wounder, there is no user id or user name at all !, how laravel get the auth user from this session !
what is the value needed to be matched in order to know the user ?
e.g Auth::id() get the user id from session, but how ! if there is no indicator in the session about the user id or something :\
furthermore, if I have the session id for the user, and I can't use Auth::id() to get the user id (due to fact that I'm building another app using another framework inside laravel, but they should have the same users) , can i get the user from the session ?

In my application i have found user_id listed as value for this dynamic key "login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d"
This is what i run to get sessions of all users & identify their session id, along with user id:
foreach (glob(base_path()."/storage/framework/sessions/*") as $filename) {
foreach (unserialize( file_get_contents($filename) ) as $key => $value) {
if(substr_count($key, 'login_web') > 0){
echo "Session ID: " . basename($filename) . " - User ID: ".$value."<br>";
}
}
}

Related

Laravel Email Greeting show Name instead of ID

Hello I wanted to ask regarding the Email Notification on Laravel, I have made a Status Notification wher I added this code
public function toMail($notifiable)
{
$leaveStatus=$this->leave->status;
if($leaveStatus==1){
$leaveNotify=" approved ";
}
else{
$leaveNotify=" declined ";
}
return (new MailMessage)
->subject('Leave Status')
->greeting('Hello '.$this->leave->user_id)
->line('I hope you are doing well')
->line('Your requested leave of' . $this->leave->type. ' type has been ' .$leaveNotify)
->line('Leave type: ' .$this->leave->type)
->line('From dt :' .$this->leave->from)
->line('To dt :' .$this->leave->to);
}
This works very well the email is being sent in each change on a Leave Application so what I am looking for is the part of the greeting , the
greeting('Hello '.$this->leave->user_id)
It shows the ID of the user instead of the first_name(which is a filed for the name) I have tried adding a ->first_name after the user_id but then it returns an error, the user_id doesn't have a foreign key that connects it with the users table its just a field which stores the id of each authenticated users but it works all the way here so im not sure that is the problem
You can use the notifiable variable passed into the function, which is the user the email is being sent to.
->greeting('Hello '.$notifiable->first_name)
You need to add relation for user in that model. See https://laravel.com/docs/7.x/eloquent-relationships . After that call it via $this->leave->user->first_name

How to create laravel cache facade based on user specific session

I have integrated redis cache driver in laravel. My app is social and music. So the authenticated user can access the app, I have to cache the data based on the logged in user. How can I implement this? Can anyone please help out?
Here is the code that I am using right now. Below is the code that fetches the logged in user's posts based on user id. In the code below, I am creating a cache tag tfeedsposts that will set the post data if the cache is not already set.
Is it the best practice to use the same cache tag for every logged in user?
Because I am thinking the same tag will not work for every logged in user, as the user will have different data, so storing the data in the same cache tag will not show the actual data to the user.
If there is an effective way to achieve this, then please let me know.
$cachename = 'tfeeds-offset:'.$this->offset.'-limit:'.$this->limit;
$cached = Cache::tags(['tfeedsposts'])->has($cachename);
if ($cached) {
$posts = Cache::tags(['tfeedsposts'])->get($cachename);
} else {
$posts = Post::whereRaw("visibility_id = 1 and user_id IN($friendsids_string) or visibility_id = 2 and user_id IN($follwingids_string) or visibility_id = 3 and user_id IN($follwingids_string) or visibility_id = 3 and user_id IN($friendsids_string)")->orWhere('user_id', $id)->with(['users_liked','users_viewed','shares', 'user','parentpost', 'comments','comments.user', 'comments.comments_liked', 'comments.replies', 'comments.replies.user', 'comments.replies.comments_liked','users_tagged' , 'notifications_user'])->latest()->paginate(Setting::get('items_page'));
Cache::tags(['tfeedsposts'])->put($cachename, $posts, $this->cachettl);
}

Auth::user() returns null across domain, in a laravel application

i have a laravel application hosted on a server a.com, and this application handles all the authentications for other laravel applications setup on other servers, Server 1 - app.com - does the authentication/user management for the system and stores it in a cookie to be sent across to servers 2,3 and 4,
server 2. mail.app.com
server 3. fms.app.com
server 4. dod.app.com
There is an initialize function on servers 2,3 and 4 that tries to decode the cookies sent across the domains from server 1. which looks something like this.
public function initialize(){
$mail = json_decode($logged_in_user_cookie)->email;
$user = User::where('email', $mail)->first();
if(!$user){
$user = new User;
$user->email = $mail;
$user->save();
}
Auth::login($user);
if(Auth::check()){
//dd($user); - works fine..
return redirect()->route('dashboard');
}else{
echo 'user not logged in ';
}
}
Servers 2, 3, and 4 also has users table but without a password, so if a cookie hits any of these servers, the system reads the cookie and extracts the user object from the cookie and checks if any user does exists, creates the user and then uses the [ Auth::login($user) ] to login the user into the current system, and if the user already exists.. it automatically logs in the user..
now the problem we are having is, on this line
return redirect()->route('dashboard'); It redirects you to the dashboard page of the application, and dd(Auth::user()) - it returns null,
and we are not able to figure out why it is working that way. since the Auth::user(), should be available across the entire application, Just think of it like how google works,
google.com, - one login controls every application including youtube
drive.google.com, mail.google.com, play.google.com, news.google.com, plus.google.com, youtube.com - that is what we are trying to do.
Go to your config/session.php and rename this 'cookie' => 'laravel_session' to your session name. For example 'cookie'=>'foo_session'. This should work.

Check existence of joomla session

I have tried to check sessions existence till user login in Joomla with JFactory::getSession(); but it's not working.
Also JFactory::getUser(); this method shows user ID after session lifetime expired.
Please let me know if any solutions are there to validate Joomla sessions.
You can use the following to get the Joomla session
$Jsession = JFactory::getSession();
$session = $Jsession->get('myVar');
and then perform a check if you wish, like so:
if($session) {
// session exists
}
else {
// session doesn't exist
}
As for showing the user ID, the ID will only show if the users is logged in as getUser() retrieves the current user object.

CakePHP 2.0 Automatic Login after Account Activation

I'm just working on the user management-component of our new project.
The plan is:
User registers on the page with minimal amount of account data (username, pass, email)
User gets an email with an activation link to activate the account
User clicks on the link and activates his account
The system logs in the user after automatically after activation and redirects him to kind of a dashboard with account information (last login, hi "username", etc.)
But there are some problems with the auto login. this is the part of the code i use:
<?php
...
// set userstatus to "active" and delete meta information "activation_key"
// then automatically login
$this->User->id = $id;
$this->User->saveField('modified', date('Y-m-d H:i:s') );
$this->User->saveField('status', 1 );
// $this->User->deleteActivationKey ....
$this->Auth->login($this->User->read());
$this->Session->setFlash(__('Successfully activated account. You are now logged in.'));
$this->User->saveField('last_login', date('Y-m-d H:i:s') );
$this->redirect(array('controller' => 'pages'));
...
This works so far, until you want to get information about the logged in user with the user() function of the Auth Component.
We're using this in AppController->beforeRender, to have user information application wide:
$this->set('auth', $this->Auth->user());
but after that auto login action, i'm getting undefined index notices. (e.g. by accessing $auth['id'] in a view). print_r() shows me only the username and hashed password of the current user.
If you login manually, everything works fine. it must be something with the automatic login after the account activation.
Seems to be a problem with the session? What am i doing wrong?
Found a solution after testing many variations.
Works now with:
$user = $this->User->findById($id);
$user = $user['User'];
$this->Auth->login($user);
Don't know why, i thought i tried this way already and that did not work.
Have you tried this? (CakePHP 2.x)
public function signup() {
if (!empty($this->request->data)) {
// Registration stuff
// Auto login
if ($this->Auth->login()) {
$this->redirect('/');
}
}
}
That simple!

Resources