I want to access to profile of the current user across the application (read/write). The user profile is an in instance of User
model. Is it possible to store it on session as a service? If not, what is best practice? Here is my login code. (ajax-based login)
function loginAction()
{
$this->view->disable();
{
$request = (array)$this->request->getJsonRawBody();
$user = User::findFirstByUsername($request['username']);
if (password_verify($request['password'], $user->password)) {
$userModel = User::findFirst('username="'.$request['username'].'"');
$this->getDI()['session']->set('auth', $user->id);
$this->user = $user;
jsonResponse($user);
} else {
http_response_code(401);
jsonResponse(['message' => 'invalid']);
}
}
}
There is several ways to achieve that. Let me share with you the one I've used in my own project...
First I've created a Component to deal with authentication related stuff such as checking the current session status (guest, user, admin), storing the current user specs, authentication procedures, etc.
namespace MyApp\Components;
use Phalcon\Mvc\User\Component as PhComponent;
class Authentication extends PhComponent
{
// ...
}
Then, I've registered this component in the main App's DI container:
$di->setShared('authentication', 'MyApp\Components\Authentication');
So I can use from my controllers, views, etc. Like:
function homeAction()
{
//...
if($this->authentication->isGuest()) {
//...
}
Finally to store data using the session. Phalcon provide a persistent session bag that you can use to easily store a serialized version of the model in the current session:
class Authentication extends PhComponent
{
// ...
function authenticate($username, $password)
{
// ... Authentication logic
if($validCredentials) {
$this->persistent->currentUser = $userModel;
}
// ...
}
}