I have time in seconds when the session should end. If the user has not selected the checkbox "remember_me" - the session will last 2 hours. When the checkbox is selected - should last - 48 hours. I have a loginСontroller, where I react - to the login result and if the validation is successful and checkbox = "on" you need to change the session time. I tried to change by looking at the documentation, and spent a lot of time looking for a solution. Maybe someone can help me. Thank you very much in advance[enter image description here]
here is my file config/app.php
'Session' => [
'defaults' => 'php',
'ini' => [
'session.cookie_lifetime' => 7200,
]
],
and here is my loginController
`public function index()
{
$this->viewBuilder()->setLayout('main');
$this->set("title", "");
$this->set("description", "description");
$this->request->allowMethod(['get', 'post']);
$result = $this->Authentication->getResult();
// regardless of POST or GET, redirect if user is logged in
if ($result->isValid()) {
if ($this->request->getData('remember') == 'on') {
///// the solution should be here
}
$redirect = [
'controller' => 'Main',
'action' => 'index',
];
return $this->redirect($redirect);
}
// display error if user submitted and authentication failed
if ($this->request->is('post') && !$result->isValid()) {
$this->Flash->saved_error(__('Invalid email or password'));
}
}`
You most likely shouldn't do it that way, your controller code shouldn't have to know about such details if it can be avoided.
The authentication plugin ships with a cookie based authenticator that you can use in addition to the session authenticator, that way you can extend authentication beyond the default session lifetime, I'd suggest that you look into that instead.
$service->loadAuthenticator('Authentication.Cookie', [
'fields' => $fields,
'loginUrl' => $loginUrl,
'cookie' => [
// cookie expires in 2 days from now
'expires' => \Cake\Chronos\Chronos::now()->addDays(2)
],
]);
By default the authenticator looks up a field named remember_me, so either rename that in your template, like:
echo $this->Form->control('remember_me', ['type' => 'checkbox']);
or configure the authenticator's rememberMeField option with the custom field name that you're using in your form.
See also
Authentication Cookbook > Authenticators > Cookie Authenticator
Related
I'm using laravel 9 and implementing login authentication manually without the laravel starter kit, I've read a lot of questions like this but most of the answers only apply to those using the starter kit, I've also read some of the other answers without the starter kit but most of them don't work.
This is my login method in the controller:
public function auth()
{
// validation
request()->validate([
'emailOrUsername' => ['required'],
'password' => ['required']
]);
// Check if the user clicks "remember me" in the login form
$remember = (request()->remember) ? true : false;
// If login using email
if (Auth::attempt(['email' => request()->emailOrUsername, 'password' => request()->password], $remember)) {
request()->session()->regenerate();
return redirect()->intended('/dashboard');
}
// If login using username
else if (Auth::attempt(['username' => request()->emailOrUsername, 'password' => request()->password], $remember)) {
request()->session()->regenerate();
return redirect()->intended('/dashboard');
}
// If incorrect credentials
else {
return back()->with('errorAlert', 'Maaf, email/username atau password yang anda masukkan salah');
}
}
I also noticed that it seems the default cookie duration for "remember me" is set in the Illuminate\Auth\SessionGuard namespace (but I didn't find the explanation in the official laravel documentation), I see that class has a setRememberDuration() method to change the duration of the "remember me" cookie, but I don't know how to properly call it, I've used Auth::setRememberDuration(1000) but it doesn't work. Is there any other way to set the "remember me" cookie duration using that method? Or is there another way to change the duration without using that method?
You can set it in config/auth.php :
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
'remember' => now()->addDays(7)->diffInMinutes(),
]
],
it's then used by the AuthManager :
if (isset($config['remember'])) {
$guard->setRememberDuration($config['remember']);
}
edit:
For future readers, this answers only work from Laravel 8.65.0
I have an application based on CakePHP version 3.2.10. I'm totally new in CakePHP so sorry if it is a banal problem. In my application I use CSRF component and Auth component configured in this way:
$this->loadComponent('Auth', [
'authorize'=> 'Controller',
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
],
'scope' => [
'Users.active' => 1,
]
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'logoutAction' => [
'controller' => 'Users',
'action' => 'logout'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'index'
],
'unauthorizedRedirect' => '/', // $this->referer()
]);
and login action like
public function login()
{
$this->set('title', 'Logowanie');
$this->set('bodyclass', 'main-page');
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
if($user['blocked'] == 0) {
$this->Auth->setUser($user);
if ($this->Auth->user('role') == 'admin')
return $this->redirect(['controller' => 'Admin', 'action' => 'index']);
return $this->redirect($this->Auth->redirectUrl());
}
else{
$this->Flash->error('Konto zostało zablokowane przez administratora serwisu. Skontaktuj się z Biurem Obsługi.');
}
} else $this->Flash->error('Błędne dane logowania. Spróbuj ponownie.');
}
}
Now the problem:
Few days ago I changed server where application is running, and after changing it logging in stopped working. After clicking login there is a message CSRF Token cookie is missing. To test if the component is the problem i disabled csrf and try again then white screen appears and nothing happen if i refresh page i'm not logged in. I checked the working version and not working version and realized that Cake not store any cookies on new server, while on old there is everything ok and cookies are set.
After few researches i found out that not only cookies not work but all sessions. I try to dump $_SEESION but it shows something only right after calling $this->Auth->setUser($user), and nowhere else. So i look through some solutions and find that there is a setting in config/app.php to set up the session:
'Session' => [
'defaults' => 'php',
],
And read that when set in that way the session is stored in default php dir. So i changed it to cake(even make a dir sessions in tmp folder and added 777 permissions). But the problem was not solved. I have no idea why it not work. I tried setting cookiePath and other settings i Session config, but it still not work.
I think that this may be the server problem(permissions). So few words about servers: Old server where everything was working was my private server(i have full access), new server(or maybe virtual server/host) is on one of hosting companies(home.pl) where i have almost no privileges to configure.
Make sure you follow these steps:
//For Set
var $var = array('Cookie');
//For Write
$this->Cookie->write('YOUR DESIRED NAME', cookieData, $expires = null);
//For Read
$this->Cookie->read('YOUR DESIRED NAME');
Check in your Conroller code should be in src/Controller/AppController.php for below points
1) have you loaded cookie component properly in initialize() or beforeFilter() method?
2) do you have configured domain and path in your cookie configuration using $this->Cookie->configKey(), if Yes, then change domain to new domain or remove domain configuration.
3) delete cache folders for model and persistence from tmp folder
For more information about Cookie refer Document
Using Yii2 framework:
The code below creates an endless loop.
Can anyone please explain how I make the session data persist on redirect ?
I have checked and there is not data being transferred, but the session data is set inside searchuser correctly.
public function actionSearchUser()
{
$session = \Yii::$app->session;
$session->open();
$session->set('admin.currentuser.id', "This worked out ok");
return $this->redirect(['site/modify-user']);
}
public function actionModifyUser()
{
$session = \Yii::$app->session;
$session->open();
if( !($session->has('admin.currentuser.id')) )
{
return $this->redirect(['site/search-user']);
}
else return $this->render('modifyUser');
}
And here is where I setup my session:
'session'=>array(
'class' => 'yii\web\Session',
'name' => 'SESSIONNAME',
'timeout' => 86400,
'savePath' => '/path/to/sessions',
'useCookies' => true,
'cookieParams' => array(
'lifetime' => 86400,
'path' => '/',
'domain' => 'localhost',
),
),
My problem was the domain (I know, I'm stupid).
I have a custom domain (n099y.local) so I needed to change the cookie domain from localhost to n099y.local and everything was fine.
It was showing all the correct session data on the page until I went to another page when the data was again missing because the cookie domain did not match the domain I was on.
I wanted to integrate the oauth2 server into my laravel 4.1 project. The password flow went pretty well but when writing the authorization code flow I encountered some strange problems with the sessions.
The request to generate leads to this function where filtered for logged in users
Route::get('security/authorize', array('before' => 'check-authorization-params|auth', function()
{
[...]
}));
Guests are redirected to a form to log in
Route::get('security/login', array('before' => 'guest' ,function()
{
return View::make('users.login');
}));
Wich leads to this route where the user should be logged in and redirected to the request he intended to do:
public function login()
{
$creds = array(
'email' => Input::get('email'),
'password'=>Input::get('password')
);
if(Auth::attempt($creds, true))
{
return Redirect::intended('/');
}
return Redirect::to('security/login');
}
The problem is, despite a positive Auth::attempt() I keep being redirected by the auth filter.
I made a few brief tests to check whats wrong by setting and reading session data wich never reached the next request, so i figured out i must have to do with my sessions.
Here's my session config file
<?php
return array(
'driver' => 'database',
'lifetime' => 120,
'expire_on_close' => false,
'files' => storage_path().'/sessions',
'connection' => 'mysql',
'table' => 'sessions',
'lottery' => array(2, 100),
'cookie' => 'laravel_session',
'path' => '/',
'domain' => null,
);
and here are some things I double checked:
database connection is correct and sessions show up in my table
session table fields have the right data types (id - varchar(255), payload - text, last_activity - int(11))
cookies get set
It turned out, that I did not set up the auth identifier in my user model correctly.
Changing it from this
public function getAuthIdentifier()
{
return $this->email;
}
to this
public function getAuthIdentifier()
{
return $this->id;
}
fixed everything.
I have a mongo db structure for users with "username" and "password". I am trying to use the Auth in cakephp login but it seems like its not working for me. I tried removing the $this->data but still it did not work.
My password is hashed using Security::hash($this->data['User']['password'])
if(!empty($this->data))
{
if($this->Auth->login($this->data))
{
echo "yes";
}
else{
echo "no";
}
}
In my app controller I have this:
public $components = array('DebugKit.Toolbar', 'Session', 'Auth' => array(
'loginAction' => array(
'controller' => 'pages',
'action' => 'home'
),
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'username', 'password' => 'password')
)
)
));
Here is the result when I debug the login method:
array(
'User' => array(
'password' => '*****',
'username' => 'test#test.com',
'remember' => '0',
'auto_login' => '0'
)
)
I don't know why I cannot use Auth with mongodb. Thanks for the help in advance.
EDIT:
When i tried and take away the layout, it shows me a query at the bottom of the page saying:
db.users.find( {"username":"test#test.com","password":"2fdf49ffc396453960802df8fc2417655d1e8fca"}, [] ).sort( [] ).limit( 1 ).skip( 0 )
The hashed value of the password that I inputted from the form is different from the hash value that is being queried. The hashed value should be "a2374c309ab7823dcd9b4e21dae7511f7a9c7ec5". Why is it that cakephp is converting the password into another hash value?
There are two ways of using $this->Auth->login(). The CakePHP API documentation explains it:
If a $user is provided that data will be stored as the logged in user. If $user is empty or not specified, the request will be used to identify a user.
The manual also mentions:
In 2.0 $this->Auth->login($this->request->data) will log the user in with whatever data is posted ...
So for the login method of the users controller you shouldn't pass anything:
if($this->Auth->login()) {
// user is now logged in
}
Should you need to manually login a user you can pass the user data as an array:
if($this->Auth->login($this->request->data['User'])) {
// user is now logged in
}
Where $this->request->data['User'] is something like:
array(
'id' => 1,
'username' => 'admin',
'password' => '1234',
);
Note: In both cases you don't need to hash the password as it is done automatically.
I was able to find out the answer. Its because cakephp is automatically hashing the password when searching in the database.
The problem that I had was when I was saving the users' password, I am was using
Security::hash($this->data['User']['password'])
I should have used this one instead:
AuthComponent::password($this->data['User']['password'])
Thank you for all the help especially to #xgalvin