I have a User entity on my project.
Each page load, I bother to recover the user with a query in the database.
My goal is to put it in session variable directly after it has logged in to simply get it back when I want.
In my code, if I test this:
$user = $this->checkBDD($mail,$fredurne,$nomComplet);
dump($user);
$this->session->set('user',$user);
$user = $this->session->get('user');
dump($user);
I have :
So, the session seems work.
Now, I put it into application. I create a function:
$user = $this->getUtilisateur($mail,$fredurne,$nomComplet);
dump($user);
With
public function getUtilisateur($mail,$fredurne,$nomComplet)
{
if(!$this->session->has('user'))
{
dump("user not in session");
$user = $this->checkBDD($mail,$fredurne,$nomComplet);
$this->session->set('user',$user);
}
else
{
dump("user in session");
$user = $this->session->get('user');
}
return $user;
}
And I have :
So, I don't understand what's the problem
Problem :
Doctrine entity is stored on session but needs to be refreshed
But when you retrieve the entity from session : Doctrine unit of work does not know it have to handle this entity
After that you should have some issues with Doctrine lazy loading.
Session is not good to store an entity.
A better solution is :
Inject Doctrine entity manager in your service
Only store id on session
On getUtilisateur method retrieve the user with id if not already done
Related
Odd issue here, I have a view content.home that relies on the authenticated user's User model to resolve and be passed to it.
Before the User model is ready, I have a simple function in which I pass a name to the authenticated user's User model.
That code is below, including the view return:
public function name()
{
$input = Input::all();
$name = $input['name'];
if(strlen($name)>2) //some validation
{
$user = User::where('id',Auth::id())->first();
$user->name = $name;
$user->save();
return view('content.home')->with('user', Auth::user());
}
}
My problem is, when I return the view I don't have the user's name. As soon as I refresh the page, it appears. Other user data provided by Auth::user() is there, but not the name. How can that be when I just saved it? It isn't NULL, again if I refresh the page right away it shows up.
I'm getting the name in the blade view like so:
{{$user->name}}
Is save() async? I don't think so. Is there some latency?
How can I make sure that the model being passed is properly resolved?
Thank you!
Answering this in case someone has a similar issue:
The reason this failed without a refresh is that there is some kind of cache on Auth::user().
When I pass the $user I saved to rather than the Auth::user(), even though it is the same user, it works.
So change return view('content.home')->with('user', Auth::user());
to
return view('content.home')->with('user', $user);
As follow user sessions in Symfony2 , as is the way of working with sessions?
I need to keep the user session by Symfony2 for example, use their name, or that I have some data stored in a database . As recommended me to work ?
im using symfony 2.4
thanks
In your controller, you can access session via
$session = $this->getRequest()->getSession();
$session->set("username", $username);
// ... later
$username = $session->get("username")
A more real-life example is one I use to show a banner only once per visit.
public function bannerWidgetController(Request $request)
{
$session = $request->getSession();
if ($session->get('banner-visited', false))
{
return new Response();
}
$session->set('banner-visited', true);
return $this->render('widget/banner.html.twig');
}
Then I include this in my TWIG via the "renderController" method.
As your question is a bit hard to understand I don't know if it is exactly what you want but there is already a mechanism included in Symfony2 to store sessions in database.
There is a simple guide you can follow here :
http://symfony.com/doc/2.4/cookbook/configuration/pdo_session_storage.html
I do have a UserController and User Model in my Laravel 5 source.
Also there is one AuthController is also Present (shipped prebuilt with laravel source).
I would like to query data from db in my blades making use of Eloquent Models.
However, Neither in my User Model (Eloquent ) nor in any of the controller, the user() method is defined. even then, I could use it in my blade by accessing it from Auth class. why?
For example,
in my blade, {{ Auth::user()->fname }} works. it retrieve the data fnamefrom my users table and echo it.
What is the logic behind it, and can i emulate the same for other db tables such as tasks?
Whenever you do it automatically or manually some like this
if (Auth::attempt(['email' => $email, 'password' => $password]))
{
}
The selected User's Data will be stored in the storage/framework/sessions
It will have data something like
a:4:{s:6:"_token";s:40:"PEKGoLhoXMl1rUDNNq2besE1iSTtSKylFFIhuoZu";s:9:"_previous";a:1:{s:3:"url";s:43:"http://localhost/Learnings/laravel5/laravel";}s:9:"_sf2_meta";a:3:{s:1:"u";i:1432617607;s:1:"c";i:1432617607;s:1:"l";s:1:"0";}s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}
The above sessions file doesn't have any data and it will have the data such as user's id, url, token in json format.
Then whenever you call the {{ Auth::user()->fname }} Laravel recognises that you're trying to fetch the logged in user's fname then laravel will fetch the file and get the user's primary key and refer it from the user's table from your database. and you can do it for all coloumns of the users table that you have.
You can learn more about it here
This user function is defined under
vendor/laravel/framework/src/Illuminate/Auth/Guard.php
with following content :
/**
* Get the currently authenticated user.
*
* #return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function user()
{
if ($this->loggedOut) return;
// If we have already retrieved the user for the current request we can just
// return it back immediately. We do not want to pull the user data every
// request into the method because that would tremendously slow an app.
if ( ! is_null($this->user))
{
return $this->user;
}
$id = $this->session->get($this->getName());
// First we will try to load the user using the identifier in the session if
// one exists. Otherwise we will check for a "remember me" cookie in this
// request, and if one exists, attempt to retrieve the user using that.
$user = null;
if ( ! is_null($id))
{
$user = $this->provider->retrieveById($id);
}
// If the user is null, but we decrypt a "recaller" cookie we can attempt to
// pull the user data on that cookie which serves as a remember cookie on
// the application. Once we have a user we can return it to the caller.
$recaller = $this->getRecaller();
if (is_null($user) && ! is_null($recaller))
{
$user = $this->getUserByRecaller($recaller);
if ($user)
{
$this->updateSession($user->getAuthIdentifier());
$this->fireLoginEvent($user, true);
}
}
return $this->user = $user;
}
this Guard.php has more functions defined in it which we use every now and then without even knowing where they are coming from
It works because Laravel comes with decent authentication.
Auth is the authentication library and has plenty of features like this, check out the documentation!
I am building my first Laravel 4 Application (PHP).
I find myself needing to call somthing like this often in most of my Models and Controllers...
$this->user = Auth::user();
So my question is, is calling this several times in the application, hitting the Database several times, or is it smart enough to cache it somewhere for the remainder of the request/page build?
Or do I need to do it differently myself? I glanced over the Auth class but didnt have time to inspect every file (16 files for Auth)
Here is the code for the method Auth::user().
// vendor/laravel/framework/src/Illuminate/Auth/Guard.php
/**
* Get the currently authenticated user.
*
* #return \Illuminate\Auth\UserInterface|null
*/
public function user()
{
if ($this->loggedOut) return;
// If we have already retrieved the user for the current request we can just
// return it back immediately. We do not want to pull the user data every
// request into the method becaue that would tremendously slow the app.
if ( ! is_null($this->user))
{
return $this->user;
}
$id = $this->session->get($this->getName());
// First we will try to load the user using the identifier in the session if
// one exists. Otherwise we will check for a "remember me" cookie in this
// request, and if one exists, attempt to retrieve the user using that.
$user = null;
if ( ! is_null($id))
{
$user = $this->provider->retrieveByID($id);
}
// If the user is null, but we decrypt a "recaller" cookie we can attempt to
// pull the user data on that cookie which serves as a remember cookie on
// the application. Once we have a user we can return it to the caller.
$recaller = $this->getRecaller();
if (is_null($user) and ! is_null($recaller))
{
$user = $this->provider->retrieveByID($recaller);
}
return $this->user = $user;
}
To me, it looks like it will get the user from the database only once per request. So, you can call it as many times as you want. It will only hit the DB once.
Auth::user() only hits the DB once, so it's not a problem invokes it many times. Btw, you can cache useful information of the user that you want to access frequently.
From my application view I need to programmatically logout current user and login another one right after that.
I want to login the second user into his own different CHttpSession (with another sessionID and so on). I need it for a security reasons.
How to implement this in Yii framework ?
Code below
$oSession->destroy();
$oSession->open();
doesn't work as expected..
looks like you are trying to impersonate users:
Create a function in your UserIdentity that would alow you to login as another known user:
protected function logInUser($user)
{
if($user)
{
$this->_user = $user;
$this->_id=$this->_user->id;
$this->setState('name', $this->_user->name);
$this->errorCode=self::ERROR_NONE;
}
}
In your controller, call this function to get the UserIdentity object and then use the Yii's CWebUser login
$ui = null;
$user = User::model()->findByPk($userId);
if($user)
{
$ui = new UserIdentity($user->email, "");
$ui->logInUser($user);
}
Yii::app()->user->login($ui, 0);
Remember to protect this controller's action from non authorized users.
A possible tricky way (tested):
session_unset();
Yii::app()->user->id = $the_new_id;
When the above code is executed, nothing visible happens on the page so you may want to redirect the browser:
$this->redirect('somewhere');
Upon the next page load, the user with the $the_new_id will be logged in