How to keep admin login when use ajaxProcess? - prestashop

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

Related

How do I make user authentication api for laravel

I tried this using jwt-auth, but the thing is token gets expired. I want to remember the user with token that never gets expired. Is their any possible way to do it in Laravel 5.2.
Should I send email and password for each request to api instead of saving session and token.
I will implement this way:
If the user selects Remember me, set the ttl to a longer time ,say 1 year OR month. To do this we need to publish
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
Then we can override the default ttl value which is 60 mins to our desired value.
$jwt = \Illuminate\Support\Facades\Config::get('jwt');
$jwt['ttl'] = 60*24*30; // 30 days
\Illuminate\Support\Facades\Config::set('jwt',$jwt);
Hope this helps!

Does Laravel query database each time I call Auth::user()?

In my Laravel application I used Auth::user() in multiple places. I am just worried that Laravel might be doing some queries on each call of Auth::user()
Kindly advice
No the user model is cached. Let's take a look at Illuminate\Auth\Guard#user:
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;
}
As the comment says, after retrieving the user for the first time, it will be stored in $this->user and just returned back on the second call.
For same Request, If you run Auth::user() multiple time, it will only run 1 query and not multiple time.
But , if you go and call for another request with Auth::user() , it will go and run 1 query again.
This cannot be cached for all request after first request has been made due to security point of view.
So, It runs 1 query per request irrespective of number of time you are calling.
I see use of some session here to avoid run multiple query, so you can try these code : http://laravel.usercv.com/post/16/using-session-against-authuser-in-laravel-4-and-5-cache-authuser
Thanks

MVC4 Force session update before request ends

We are developing using VS2010 and MVC4, deploying our web app on an IIS 7.5 on Windows7.
Our project has a long running process for which we want to display status and progress.
In order to accomplish this we have a small serializable class with properties that describe the current status. The long operation pseudo code goes like this:
int curentPercentComplete = 0;
EngineStatus status = new EngineStatus();
while (!done) {
status.PercentComplete = curentPercentComplete;
Session['status'] = status;
// do lengthy operation
curentPercentComplete = compute();
done = isJobFinished();
}
We also have an other controller action that tries to retrieve the current status from the session
which then encodes to json and returns it to the browser via an Ajax request.
Our problem is that we always seem to get the last saved data from the previous request, in other words the session object does not seem to update the Session['status'] field during the execution of the while block.
We have tried the session state mode both InProc and StateServer with exactly the same behavior.
Thanks in advance.
It turns out that the MVC framework performs a single update of the session data at the end of the request which means that only the last value is saved.
Since the "lengthy" operation is performed in a single request-response cycle, the idea of storing intermediate status information in the session is plain wrong.

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>

Update Rails session with Backbone.js history navigate?

I have a Market stored in a user session in Rails, set via session[:current_market] in my application_controller.rb.
I have my front-end interface served with Backbone.js, and I have a little market selector widget that calls
BackboneApp.data.currentMarket = market.toJSON()
Backbone.history.navigate market.homeUrl(), trigger: true
... when a user selects a market. This works except that if a user hard-navigates to another page, the market reverts to whatever it was set on the initial page load (whatever was originally loaded in session[:current_market] in Rails.
How can I update the user's market in session when a Backbone.js navigation event occurs?
I tried manually doing this by triggering a silent GET:
$.get '/api/v1/reset_current_market', { market_id: market.toJSON().id }
... but that doesn't seem to work.
I assume that when the user switches market then some ajax request will be fired to hit your rails api and fetch the data for that market. What you could do is make the controller action for that route update the current users session to whatever market got requested.
how about wrap this market info to new Model and handling change with that? This is just a pseudo code examlpe.
var marketModel = Backbone.Model.extend({
urlRoot:"/you/url/market",
defaults:{
marker: ""
},
initialize:function () {
}
});
BackboneApp.data.currentMarket = new marketModel(market.toJSON())
Set selected market to this new model, and call save().
At rails change session info at your /your/url/marget POST method. If this object have id property then impelent also PUT method.