Laravel,一个请求的登录用户

Dan*_*y D 2 laravel

我正在用 Laravel 构建一个 REST API,我有一个检查令牌的过滤器:

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

    $token = Request::header('X-CSRF-Token') ? Request::header('X-CSRF-Token') : '';

    if (empty($token)) {
        return Response::json(
            ['message' => 'A valid API key is required!'],
            401
        );
    };

    $user = User::where('token', '=', $token);

    if ($user->count()) {
        $user = $user->first();
        Auth::login($user);
    } else {
        return Response::json(
            ['message' => 'Your token has expired!'],
            401
        );
    };
});
Run Code Online (Sandbox Code Playgroud)

如果一切正常,过滤器将登录用户 uth::login($user);

我怎样才能只为 1 个请求登录他?

由于每次请求都会检查此过滤器,因此我认为每次都将用户注销会更好。

我在 Laravel 的文档中看到过这个,不知道如何应用它:

if (Auth::once($credentials))
{
    //
}
Run Code Online (Sandbox Code Playgroud)

我的回复中可以有回调吗?我可以在哪里注销用户?

/*
获取所有产品。*/ 公共函数 getProducts() {

$products = Auth::user()->products;

return Response::json($products, 200);
Run Code Online (Sandbox Code Playgroud)

}

有任何想法吗?

3eh*_*ang 11

如果您没有用户的密码,请使用:

if(Auth::onceUsingId($userId)) {
    // do something here
}
Run Code Online (Sandbox Code Playgroud)