Yii2: Frontend user logout but backend remains logged in - php

I’m having a problem, when I logout from either frontend or backend, the other one remains log in. I have been searching online for the solutions but did not find anything like this. What should I change so that when I logout from frontend or backend, the other one must logout.
Log in is working fine for both:
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}

Please update your frontend and backend main.php as below
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-auth', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the frontend
'name' => 'AuthSession',
],
once the identityCookie and sessions are identical, then you can manage your session from both frontend and backend.

Related

Laravel Session with database driver keeps updating after logging out

I switched to database driver for Session and migrated the table. I've noticed that even after the logout action, the value last_activity in the table keeps getting updated after every refresh, even if the user isn't logged-in anymore.
I've tried removing it from the records of the database, but once the user refreshs at the login page, it gets inserted again.
I believe I'm doing something wrong to logout the user well. I want Laravel to stop refreshing the record of the session, as it might cause issues if every logged-out user kept accessing the database with their refreshes.
I'm logging in like this:
if (Auth::attempt($request->only('email', 'password'), ($request->remember_me === "on" ? true : false))) {
// return settings too
if(Auth::user()->active === false){
return response()->json(array('status' => 'failure', 'message' => "Your account isn't active!"),500);
}
return response()->json(
array(
'status' => 'success',
'message' => "Login is successful!"
),
200
);
}
I'm logging out like this:
public function logoutUser(Request $request){
Auth::user()->tokens()->delete();
Session::flush();
}
It's a SPA project via Sanctum.
config/session.php
'driver' => env('SESSION_DRIVER', 'database'),
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
'encrypt' => false,
'files' => storage_path('framework/sessions'),
'connection' => env('SESSION_CONNECTION', null),
'table' => 'sessions',
'store' => env('SESSION_STORE', null),
'lottery' => [2, 100],
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
'path' => '/',
'domain' => env('SESSION_DOMAIN', null),
'secure' => env('SESSION_SECURE_COOKIE'),
'http_only' => true,
'same_site' => 'lax',
The user access /login page, then they get redirected to /dashboard. Basically, /dashboard needs auth, otherwise, you don't need to be logged in.
I've tried using /dashboard by the path field and cleared the config, it didn't work.
** I've noticed that the session gets registered regardless if the user is logged or not, as long as the user visits the website, it gets registered. My understanding was that it happens after the user is logged, as it would be a hassle to insert a record whenever a guest visits.
My question shifts into the following: How can I prevent this behavior from happening? I want to limit the session saving on a specific path only, which is /dashboard, and I want to ignore the session tracking for unlogged users. The moment they logout, the session gets destroyed.

How to make if Login in frontend also login in backen in Yii2?

Hi I want to ask how can I make login function that if I login in frontend the user also login in the backend in Yii2
I have tried to make session from frontend but at the backend, the session can't get.
In backend/config/main add :
'components' => [
'session' => [
// this is the name of the session cookie used for login on the backend
'name' => 'test',
],
]
name must be same with session name in the frontend

Yii2 CSRF token time period increase

Currently I am working on Yii2 and when I go to form submit after some time then Yii2 redirect to bad request, I think there is CSRF token expire so my question is, how increase CSRF token life in Yii2?
How can we do with form submit with long time and CSRF token also validate?
CSRF token validation disable is working fine in my code but I didn't want to disable it.
No need to code show here, I think.
You can use frontend and backend as different cookie and session
Cookie Backend
'identityCookie' => [
'name' => '_backendIdentity',
'path'=>'/admin',
'httpOnly' => true,
],
Cookie Frontend
'identityCookie' => [
'name' => '_frontendIdentity',
'path'=>'/',
'httpOnly' => true,
],
Session Backend
'session' => [
'name' => 'session_backend'
],
Session Frontend
'session' => [
'name' => 'session_frontend'
],
You can increase csrf token expiry time by adding following code in config/web.php file. From below code csrf token valid for one hour only. Can increase time as per your need.
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'Key Here',
'csrfCookie' => [
'expire' => time() + 3600,
'secure' => true,
],
],

Deny access to the application for the role. Yii2

I have 2 applications: frontend and backend.
Users on frontend have role "client".
How do I disable access to the application backend users with "client" role. All other roles are allowed access. site/login on backend allow for all users.
I wrote the following code in my main.phpfile:
'as beforeRequest' => [
'class' => 'yii\filters\AccessControl',
'rules' => [
[
'allow' => true,
'controllers' => ['site'],
'actions' => ['login'],
'roles' => ['?'],
],
[
'allow' => false,
'roles' => ['client'],
],
],
'denyCallback' => function () {
return Yii::$app->response->redirect(['site/login']);
},
],
I have error: ERR_TOO_MANY_REDIRECTS in chrome.
From the guide 'roles' => ['?']:
matches a guest user (not authenticated yet)
Since the user is logged in they are stuck in a redirect loop caused by the second rule and the denyCallback i.e.
User is logged in but is of role client and is therefore not allowed.
Since user has been denied access, redirect to site/login.
See 1.
This can be fixed by omitting the roles element in your first rule:
If [role] is not set or empty, it means this rule applies to all roles.
HOWEVER THIS IS THE WRONG APPROACH
Users who are logged in but are of role client should be denied access to the backend. Sending them to login will not help since they are already logged in. The proper course of action is to send them to the frontend's error page.

Simultaneous authorization in advanced app

In advanced app, I tried to implement divided authorization for backend and frontend.
In first case, I used User class from basic app, in order to use users without database. But for frontend part, I used User class from advanced app.
It would seemthat everything is working perfectly. But when you try to log in at the same time on both sides, the latter takes precedence over the previous one. Ie after entering the frontend parts - automatically eject the user from the backend and vice versa.
You have to set different cookies for frontend and backend in config/main.php file. For Eg.:
In backend:
'components' => [
'session' => [
'name' => 'BACKENDID', //Set name
'savePath' => __DIR__ . '/../tmp', //create tmp folder and set path
],
],
In Frontend:
'components' => [
'session' => [
'name' => 'FRONTENDID',
'savePath' => __DIR__ . '/../tmp',
],
],

Categories