Laravel $request->session() doesn't keep session alive long time - laravel-9

I've use $request->session()->put for puuting value to session, but when I leave my account open one night for example, the next day I find that the session has been killed.
do you have any suggestions or solutions to keep my session open like "remember me" option for login?
code when i put in the session:
$request->session()->put('key', value);
$request->session()->save();
and i retrieve the session:
if($request->session()->has(value)) {
$var = $request->session()->get(value);
}

Related

How to implement concurrent session filter in grails to handle multiple login session?

For example: Suppose user "testuser#xyz.com" is login from one browser and performing some works. at the same time someone else login with same user "testuser#xyz.com" from another browser/machine in that scenario, i want to implement following ways
if the first logged-in user is not performing any action(inactive condition) from last 3-4 mins then first user will logged-out and second user will logged-in successfully.
If the first logged-in user is performing some task (active condition) then first user should get notification that, someone trying to logged-in from another browser/machine are you agree to allow ? if first user will allow then only second user will able to login(and first user should logout) otherwise not.
Any help is much appreciated.
This is not exact solution to your problem, but definitely it will give you the clue.
In your /grails-app/conf/spring/resources.groovy
//To enforce/restrict one session per user Starts
sessionRegistry(SessionRegistryImpl)
concurrentSessionFilter(ConcurrentSessionFilter, sessionRegistry)
registerSessionAuthenticationStrategy(RegisterSessionAuthenticationStrategy, ref('sessionRegistry')) {}
concurrentSessionControlAuthenticationStrategy(ConcurrentSessionControlAuthenticationStrategy, ref('sessionRegistry')) {
exceptionIfMaximumExceeded = true //False
maximumSessions = 1
}
sessionFixationProtectionStrategy(SessionFixationProtectionStrategy) {
migrateSessionAttributes = false//true
alwaysCreateSession = true//false
}
sessionAuthenticationStrategy(CompositeSessionAuthenticationStrategy, [concurrentSessionControlAuthenticationStrategy, sessionFixationProtectionStrategy, registerSessionAuthenticationStrategy])
//To enforce/restrict one session per user Ends
Source : searchcode.com

Local storage clearing for select users

What could cause specific users to have their local storage cleared, but the rest of the users are unaffected? Is it their firewalls? Is it their anti-virus? Browser? Browser version?
Any help would be greatly appreciated.
The application -
I have a website that requires login. Certain routes require the user receive a token(from the login step) if not they will be redirected to the login page.
The run down-
Two users have come forward and mentioned they couldn't log in. After some trouble shooting and looking at logs I found they were successfully logging in. So I screen shared with one user and I watched the localstorage in the dev console. I saw that they acquired a token successfully. Then they go to navigate to the myorderCards page and suddenly the token is cleared from the storage and they are routed back to the login page. This then puts them in a loop because every time they login successfully I have a return parameter which sends them back to myorderCards which then clears the token etc...
So the problem I am facing is that I can not recreate this issue. I have tested locally and on the published site. I have tested on and off network. I have tested 3 different browsers and even tested on a mac device(the two users in question are using macs) This issue only happens for the two users that have submitted a ticket. Still I can not figure out how the local storage is clearing. the only place that clears the token are the two lines you see below.
Additional Information-
I have tried changing my browser settings to have a high security setting. However, it continues to work for me. I have changed the browser settings to not allow cookies at all but that breaks the entire website.
P.S there are no errors or exceptions to go off of. Either on the server or the browser side.
app.module.ts
RouterModule.forRoot([
{ path: 'myorderCards/:id', component: MyOrderComponent,canActivate:[MyAuthGuard] },]),
In auth guard class
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
const token = this.storage.getLocalStorageValue('mycurrentUser');
if (token != null && Object.keys(token).length != 0) {
const exTime = token.expires;
if (new Date(exTime.toString()) > new Date(Date.now())) {
return true;
}
else {
this.storage.clearLocalStorage('mycurrentUser');
this.router.navigate(["/mylogin"], { queryParams: { returnUrl: state.url } });
return false;
}
}
else {
this.storage.clearLocalStorage('mycurrentUser');
this.router.navigate(["/mylogin"], { queryParams: { returnUrl: state.url } });
return false;
}
}
}
Your token's expiration time comparison isn't timezone agnostic.
The issue is: If, one way or another, your token includes a time that doesn't provide its timezone assumption, like 9/13/21 5:30 PM (or epoch format not based in UTC), then it would already be expired to the end user who's 1 hour ahead of you. Etc.
As a solution, you could provide all datetimes in UTC, and even then convert it to Unix epoch to discourage people trying to manually 'read' it in their local time.
But for OAuth2, it's more common to include 'expires in' rather than 'expires at'. So the body of an OAuth2 access token is typically this:
{
"access_token":"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3",
"token_type":"bearer",
"expires_in":3600,
"refresh_token":"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk",
"scope":"create"
}
expires_in is how long (seconds) the token is valid/alive. When the client receives this token, they assume it expires that long from 'now' (where 'now' is subjective depending on geography). So they calculate the expiration date/time themselves and store it, which sidesteps the issue of timezone conversion altogether.
Then, for two customers authenticating at the same time, one in New York may store 6:00 PM while the one in Chicago may store 5:00 PM as an expiration date, even though they both expire the same moment.

How to keep admin login when use ajaxProcess?

Module send only Ajax process to module controller every 5 seconds. After few minutes prestashop automatically logged out employee. How I can keep stay loggin?
In your ajaxProcess function, do this:
$cookie = Context::getContext()->cookie;
$cookie->write();
This will refresh the duration of your admin cookie when your ajaxProcess returns, that is when the headers are sent which is how cookies get set.
Optionally you can include this code above the write() call so that the last activity time is also recorded
if (!Tools::getValue('stay_logged_in')) {
$cookie->last_activity = time();
}
You can see this code in action in /controllers/admin/AdminLoginController.php

MVC 4 Forms Authentication (Infinite Login)

I was surprised I couldn't find a good answer to this out on the interwebz, so here we are.
I'm setting a FormsAuthenticationTicket to expire after a week. This is used in tandem with a "Remember Me" setting we feature on our login form. This is being accomplished by :
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName);
// set the auth token expiration to a week
var authTicket = new FormsAuthenticationTicket(1, user.Email, DateTime.Now, DateTime.Now.AddHours(168), true, userData);
var encryptedTicket = FormsAuthentication.Encrypt(authTicket);
cookie.Value = encryptedTicket;
cookie.Expires = authTicket.Expiration;
With this, I've also extended our session timeout, as many of our users keep the application open for equally long periods of time :
<forms loginUrl="~/account/sign-in" timeout="10080" name="t5S4U4Y152" domain=".xxxxxxx.xxx.xxxxx"/>
My question :
I've been asked to make this a non-expiring cookie, such that as long as the user retains it, they'll always be logged in - more or less an infinite login. Is there a default value I can set the ticket and timeout to in order to achieve this?
Yes, I could set both expiration's to something like 50 years from the present, but I'm wondering if there is a cleaner or more suitable approach?
No there isn't any value you can set the expiration so it is infinite. You'll just need to set it to something really long.
As you know, if you do not set an expiration the cookie then only lives for the length of the session (when the browser is closed), which is definitely not what you want.
You can also use slidingexpiration=true so that whenever a user comes back to the site, the expiration date on the cookie is refreshed to be Today + Timeout instead of DateInitiallyIssued + Timeout

Laravel, get currently logged-in users

I want to display a list of currently logged-in users in an app. I want to use Laravel Auth method. I'm looking at the API and I cannot find anything like it.
I would probably need to loop through the sessions store and then match it to a user ID. Am I right?
UPDATE: Forgot to mention, I'm storing sessions in the DB.
"Currently logged in" is something you can't do with plain old sessions. Let me explain why:
A session is a bunch of data stored at server side which is assigned to an user through a cookie. That cookie remains on user browser and so it keeps the session active. Sessions can stay "alive" months without the user even logging in.
But, it's possible to store sessions on database.
As you can see, Laravel keeps a field called last_activity and, through that field, you should be able to retrieve all sessions that had activity within the last 15 minutes (or something else, you call it).
When your retrieve those records, the data field is a serialized representation of session data. You can unserialize($session_record->data) and retrieve the user id.
Depending on your Auth driver, session's user id may have different names:
For eloquent driver, it should be eloquent_login.
For fluent driver fluent_login.
For your Custom\AuthClass, it should be called custom_authclass_login.
Assume that all http requests from logged in users are passing auth middleware, we can override terminate function like following:
public function terminate($request, $response)
{
Auth::user()->save();
}
Then a query like User::where('updated_at', '>', Carbon::now()->subMinutes(12))->get(); will bring all logged in user, where 12 is the lifetime of session.
Of course, for real time, we should use ajax calls every 5 seconds or websockets via pusher or other.
First create a table where the logged in user's id will be inserted
Schema::create('active_users', function(Blueprint $table)
{
$table->increments('id')->unsigned();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')
->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
Then in yourcontroller insert data while logging in
if (Auth::attempt($credentials)) {
DB::table('active_users')->insert(array('user_id' => Auth::id()));
}
and delete the data while logging out
DB::table('active_users')->where('user_id', '=', Auth::id())->delete();
Print the online users list in your view
<ul><strong>Online Users</strong>
<?php $online_users = DB::table('active_users')->where('user_id','!=',Auth::id())->get(); ?>
#foreach($online_users as $online_user)
<li>{{User::find($online_user->user_id)->first_name}}</li>
#endforeach
</ul>