Pregunta

Upon login, I return the user object + session token in JSON form, so that the mobile device that connects to my application can be authenticated.

However, I have a difficulty understanding how would I go about authenticating the user only with his session id?

Once logged in, the mobile device sends the session token upon every request, which means I somehow need to check whether it's the same user (using a custom auth filter).

How would I do it?

¿Fue útil?

Solución

You may have a table for saving tokens

Add a filter in routes.php

Route::group(array('before' => 'auth'), function() { ... })

And in the filters.php you can search the token in the database, if isn't exist you return a no access response

Route::filter('auth', function () {

$input_token = Input::get('token');

if (!empty($input_token)) {
    $validator = Validator::make(
        ['token' => $input_token],
        ['token' => 'token']
    );
    if (!$validator->fails()) {

        $token = Token::where('hash', $input_token)->first();

        if ($token) {

            $user = User::find($token->user_id);

            if ($user) {

                Auth::login($user);
                return;

            }
        }
    }
}

$response = Response::make(json_encode([
    'error' => true,
    'messages' => [
        Lang::get('errors.NO_ACCESS')
    ]
]), 200);

$response->header('Content-Type', 'application/json');

return $response;
});

Otros consejos

You could do it like this:

$sessionID = '4842e441673747d0ce8b809fc5d1d06883fde3af'; // get this from \Session::getId(); from your previous authenticated request (after logging in because it changes).

$s = new \Illuminate\Session\Store(NULL, \Session::getHandler(), $sessionID);
$s->start();
$userID = $s->get('login_82e5d2c56bdd0811318f0cf078b78bfc');

\Session::set('login_82e5d2c56bdd0811318f0cf078b78bfc', $userID);
return \Auth::user();

Not the prettiest code but it works. It creates an instance of a session using the previous Session ID, then start loads it up from file. The user ID is in that key, so then it just sets the user id on the current session. Then when you call Auth::user() it loads up the User using that user id.

The reason for all the numbers in the key is because the larval developer thought it would be smart to hash the Auth class name to make the key as unique as possible... :-S

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top