How to avoid caching in the socket?
I've executed a script listening for sockets, so there I check if the user is logged or not:
Auth::check();
i've tested it, but if I logout or log in ,the status doesn't changes, also this happens with the database eloquent queries, the fluent works fine, any ideas on how to fix this problem?
I need to restart the server to update the session in the sockets, that restart
also I've tried to use raw $_SESSION, it also caches, but I need to check the fresh version of it in the sockets...how to do this?, spent hours but still can't figure it out
I think you have to overwrite the user() Method inside the Guard class. The method originally fetches the user only once per request and you have to disable that for your usecase. See here from Guard.php
// 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 becaue that would tremendously slow the app.
if ( ! is_null($this->user))
{
return $this->user;
}
Related
I want to validate the use of coupons in my app by checking if both the business' owner and the final client are the ones redeeming the coupon. This would be the process:
Client shows his QR code
Owner scans it
Coupon is redeemed if both of them are logged in (this would happen when the Owner's device makes a post request and uses CouponController)
I know I can use auth() to validate the owner's status (he wouldn't be able to access the Redeem view when logged out anyway), but is there any way to check if the Client is also logged in without modifying the User row in the database? Right now, I use the following:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
class LoginController extends Controller
{
...
public function store()
{
if( !auth()->attempt(request(['email','password'])) ){
return back()->withErrors([
'message' => 'Please check your credentials and try again.'
]);
}
$user = User::find(auth()->id());
$user->active = 1;
$user->save();
return redirect()->home();
}
Let's first clarify on how PHP scripts work and how that impacts your path to know if a user is online or not.
Under your Laravel application, for the very reasons on how PHP processes HTTP requests, you can only identify hits (requests), that you can interpret like heartbeats. So, you cannot (at least with bare PHP) see the user online all the time, but you can assume the user is there if the page hit was recently.
That said, it will be up-to-you what will be the acceptable time window to interpret if the user is online or not, once given a page hit/http request.
If you only record that the user is active (as a boolean/int flag like $user->active = 1) upon login, you will think the user is active even long after the user is gone from the application, as the user session may perfectly remain still active (open) but the user is actually inactive.
There are many ways to go around this.
One possible approach is to remember the last time a user hit your page, so you consider him online after the next -say- 5 minutes (this value is up to you). This approach is fair enough for what you are willing to achieve. Keeping this track can be achieved with middlewares, so your controllers are kept clean.
On how exactly implement this, well, that would be an entire and opinionated git project to post here and it's probably outside the scope of this answer. Long story short, think of keeping record of timestamps of the events you will consider relevant as user activity, instead of a flag with no timing information.
If you are willing to implement this as a usable feature with external packages, here are a few options:
https://github.com/highideas/laravel-users-online
https://github.com/thomastkim/laravel-online-users
https://github.com/joshrainwater/active-users
Even if you are not willing to pull in a third party package, feel free to dig in their sources (start on the Traits) to get some ideas on how to go around this.
You will also notice that some of them use Cache to keep track of disposable data without the need of storing this into your business ERD in database.
Hope this helps as a starting point.
I want to use post to update a database and don't want people doing it manually, i.e., it should only be possible through AJAX in a client. Is there some well known cryptographic trick to use in this scenario?
Say I'm issuing a GET request to insert a new user into my database at site.com/adduser/<userid>. Someone could overpopulate my database by issuing fake requests.
There is no way to avoid forged requests in this case, as the client browser already has everything necessary to make the request; it is only a matter of some debugging for a malicious user to figure out how to make arbitrary requests to your backend, and probably even using your own code to make it easier. You don't need "cryptographic tricks", you need only obfuscation, and that will only make forging a bit inconvenient, but still not impossible.
It can be achieved.
Whenever you render a page which is supposed to make such request. Generate a random token and store it in session (for authenticated user) or database (in case this request is publicly allowed).
and instead of calling site.com/adduser/<userid> call site.com/adduser/<userid>/<token>
whenever you receive such request if the token is valid or not (from session or database)
In case token is correct, process the request and remove used token from session / db
In case token is incorrect, reject the request.
I don't really need to restrict access to the server (although that would be great), I'm looking for a cryptographic trick that would allow the server to know when things are coming from the app and not forged by the user using a sniffed token.
You cannot do this. It's almost one of the fundamental problems with client/server applications. Here's why it doesn't work: Say you had a way for your client app to authenticate itself to the server - whether it's a secret password or some other method. The information that the app needs is necessarily accessible to the app (the password is hidden in there somewhere, or whatever). But because it runs on the user's computer, that means they also have access to this information: All they need is to look at the source, or the binary, or the network traffic between your app and the server, and eventually they will figure out the mechanism by which your app authenticates, and replicate it. Maybe they'll even copy it. Maybe they'll write a clever hack to make your app do the heavy lifting (You can always just send fake user input to the app). But no matter how, they've got all the information required, and there is no way to stop them from having it that wouldn't also stop your app from having it.
Prevent Direct Access To File Called By ajax Function seems to address the question.
You can (among other solutions, I'm sure)...
use session management (log in to create a session);
send a unique key to the client which needs to be returned before it expires (can't
be re-used, and can't be stored for use later on);
and/or set headers as in the linked answer.
But anything can be spoofed if people try hard enough. The only completely secure system is one which no-one can access at all.
This is the same problem as CSRF - and the solution is the same: use a token in the AJAX request which you've perviously stored eslewhere (or can regenerate, e.g. by encrypting the parameters using the sessin id as a key). Chriss Shiflett has some sensible notes on this, and there's an OWASP project for detecting CSRF with PHP
This is some authorization issue: only authorized requests should result in the creation of a new user. So when receiving such a request, your sever needs to check whether it’s from a client that is authorized to create new users.
Now the main issue is how to decide what request is authorized. In most cases, this is done via user roles and/or some ticketing system. With user roles, you’ll have additional problems to solve like user identification and user authentication. But if that is already solved, you can easily map the users onto roles like Alice is an admin and Bob is a regular user and only admins are authorized to create new users.
It works like any other web page: login authentication, check the referrer.
The solution is adding the bold line to ajax requests. Also you should look to basic authentication, this will not be the only protector. You can catch the incomes with these code from your ajax page
Ajax Call
function callit()
{
if(window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();}else{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function(){if(xmlhttp.readyState==4&&xmlhttp.status==200){document.getElementById('alp').innerHTML=xmlhttp.responseText;}}
xmlhttp.open("get", "call.asp", true);
**xmlhttp.setRequestHeader("X-Requested-With","XMLHttpRequest");**
xmlhttp.send();
}
PHP/ASP Requested Page Answer
ASP
If Request.ServerVariables("HTTP_X-Requested-With") = "XMLHttpRequest" Then
'Do stuff
Else
'Kill it
End If
PHP
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) )
{
//Do stuff
} else {
//Kill it
}
I have processing db transaction from page using ajax request if user don't press submit button than roll-back all sql transaction which is done by ajax request (i will manage this but currently following logic not working if refresh current page).
I have try following code but not working,
function viewPage(){
$needRollBack=$this->session->userdata('needRollBack');
if($needRollBack){
$this->db->trans_rollback();
}
$this->db->trans_begin();
$this->MyModel1->insert(.....);
$this->MyModel2->insert(.....);
.........................
}
function submitDetails(){
$this->db->trans_complete();
$this->session->set_userdata('needRollBack',false);
}
when again viewPage() function call or refresh page than if submitDetails() not called than rolleback all sql stransaction done via ajax request (starting point from trans_begin()) will be roll-baked?
is this possible? Kindly guide me...
There are a number of things that need addressing here.
First would be that your database and schema type must support transactions (e.g. if you are using MyISAM table type in MySQL you will not be able to use transactions).
Second to test whether or not transactions are succeeding in CI you write error messages to the error log if $this->db->trans_status() === false.
Finally I would use an alternative approach to the one above (if possible) - one possible approach would be to store your data in a session (through the different stages) and make the call or multiple database calls at the final point (when user clicks submit). You can still use transactions this way and it simplifies the problem.
I'm having a lot of problems and I really can't seem to find a solution.
Yesterday, I finished up doing some work on a vagrant box in Laravel. When I shut down the computer, login functionality was working fine.
On opening everything up today I find sessions are no longer working.
I've tried everything I can think of but I cannot log in now and flash data doesn't work.
Every page load a new session is created - e.g using the native driver, if I login, it creates two sessions - one for the login page, and one for the posted login page.
If I use a database driver I get the same result. Every time I click login, I get a further two rows of session data
I can't tell what's happening with the cookie driver but I've tried it and it's not working.
I've tried in Chrome and IE and neither will login. I've tried deleting the contents of the storage folder multiple times, and emptying cookies on the browser side. I did think it may be to do with the time being different on the vm and the local machine but they're synchronised.
Any ideas what could be causing this? Anyone come across this issue before?
edit: I've also now recreated the virtual machine and the problem still exists
second edit: I've now started from scratch using a digitalocean VPS with the same results.
I've stripped out everything in my routes file and all it now has is the following
<?php
Route::get('/sess/set/{value}', function($value) {
Session::set('testv', $value);
Return 'Set ' . $value . ' - ' . Session::get('testv');
});
Route::get('/sess/get', function() {
Return 'Get ' . Session::get('testv');
});
I visit the first page and it shows whatever value I put into the session. Hit the second page and you only get the 'Get ' part without any session value.
session_attributes always has a _token field, I've tried changing the name of the session and the domain and still can't get sessions to work.
edit3: for anyone who comes across this, I never identified the issue. I started a completely new project, copied my controllers and views across, recreated my routes file and everything is now working - although I'm half expecting to be updating this post tomorrow to say it's broken again!
My problem was that I had echo statements in my function. It was keeping the session from being properly created/stored.
I had an echo before my 'return Redirect' so the redirect didn't get the session...
public function login()
{
// auth
if (Auth::attempt(Input::only('email', 'password'), true))
{
return Redirect::route('companies.index');
}
// failed -> back to login
return Redirect::back()->withErrors(['email' => 'Login failed.'])->withInput();
}
Details: http://brainwashinc.com/2014/02/17/laravel-sessions-not-working-in-4-1/
I had this exact problem and with almost identical environments as well. As you experienced as well what ended up working for me was starting a totally fresh Laravel 4.1 project and then copying everything over. However I did also find that by changing one config variable I was able to fix the problem:
In /app/config/session.php change the lifetime config item to something higher than 0. This fixed the issue for me.
I had this same issue and already changed my session values to the 4,1 version. I logged into our server and ran the composer update command, after it finished everything worked fine.
composer update
I spent a whole day with the same issue (session regenerated with almost every request), and could not find anything helpful online. Posting this here in case somebody has the same issue.
Basically the problem was that the session cookie was not set correctly due to template errors. So if you run into this, first check that the session cookie is set with every request via http headers.
In my case I wrongly used something like this in some of my templates:
#section('test')
<p>Some content here</p>
#endsection
This is wrong!
In Laravel 4 it needs to be #stop instead of #endsection:
#section('test')
<p>Some content here</p>
#stop
Using #endsection made the app not finish correctly, so no session cookie was set. There is no trace of anything being wrong in the logfiles however. BTW, this kind of error also leads to after-filters not being applied.
I also has this problem, and it turned out to be with outputting data early - I was already echoing some debug text in the controller action, and then tried setting a session variable for the first time - the session just wouldn't persist, and kept recreating each time - once I removed the output, it worked fine (and fine from then onwards)
I upgraded from Laravel 5.1 to 5.2 and had the issue of numerous sessions being created on every page load. It didn't matter which session driver I used, nor did changing anything in config make it work. (I tried every suggestion on every StackOverflow result produced by Google.)
The solution for me: remove "web" middleware from your routes. Apparently, web middleware is included automatically in 5.2+, so if your routes ALSO specify it, you wind up with multiple sessions being generated.
There are many reasons this can happen, I just ran into this problem myself. The fix for me was to change:
public function getAuthIdentifier()
{
return $this->username;
}
to
public function getAuthIdentifier()
{
return $this->getKey();
}
on the User model.
I've experienced issues related to this. The session file wasn't created every time but sometimes I just can't get the session variable displayed. After hours of experiments I found that the problem was related to Debugbar.
If you're using Debugbar and having session issues, disable it and try again to confirm. There's an issue reported here.
This is my first post on these forums, however I've been using them for years in looking for solutions to my coding challenges...thank you for all for sharing your knowledge.
Ok, to the point...I need a nudge in the right direction for a theory of a solution to the below problem.
Desired Result:
Current existing structure: FLEX RIA that communicates with MySQl DB via PHP.
We basically, have a RIA that is part of a software solution we provide to our customers, we want to restrict login sessions to one/username, which we did successfully by setting a value in our MySQL DB...the point of this was to restrict the use of username(s) to one application access point and create the ability for us to charge for additional usernames, if so desired by our customer.
Problem:
Although, we successfully restricted user logins to one session, we ran into a problem when the RIA connection with the DB was inadequately terminated (eg., browser crash, OS crash, flash player error, etc). When these crashes happenned the value that was set in the DB for the user, showing them logged in, would persist and thusly lock them out of our software application. We would have to go into the database and manually reset their logged in status.
What I am looking for:
I need some suggestions or some areas to look into/research for a solution to this problem
Any help you might provide is greatly appreciated,
Thank You
Dignified Dude
When the Flex app pings your server for the first time; create a server side session. When that session expires, flip the value of the database automatically, regardless of whether or not the user has logged out. You may also want to add some form of timer to the UI to automatically log the user out.
I assume there is some way to run code in PHP when the server side session expires. Here are some approaches that came up in a Google Search:
Run query after session expire
http://forums.digitalpoint.com/showthread.php?t=1320013
PHP session timeout callback?
http://www.google.com/search?q=Run+code+when+PHP+session+expires&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a#sclient=psy-ab&hl=en&safe=off&client=firefox-a&rls=org.mozilla:en-US%3Aofficial&source=hp&q=run+code+on+PHP+session+expire&pbx=1&oq=run+code+on+PHP+session+expire&aq=f&aqi=q-w1&aql=&gs_sm=e&gs_upl=9504l13039l1l13162l32l12l0l0l0l0l1160l5043l2-4.2.1.3.0.1l11l0&bav=on.2,or.r_gc.r_pw.r_cp.,cf.osb&fp=9fb4160009134867&biw=1200&bih=786