简体   繁体   English

Laravel 5.8 在 api 和 app 中为 1 个用户类型使用中间件

[英]Laravel 5.8 use middleware for 1 user type in api and app

I'm trying to implement a middleware in Laravel 5.8 which checks if a value is true for a model Customer .我正在尝试在 Laravel 5.8 中实现一个中间件,它检查模型Customer的值是否为真。 I want the app routes to redirect to a route ( 'login' ), for the api routes I want to give a 401 response.我希望应用程序路由重定向到一个路由( 'login' ),对于我想给出 401 响应的 api 路由。 I think I'm overseeing something.我想我正在监督某事。

This is my Middleware which works for the app routes, but I can't get the middleware to handle the unauthorized requests ( $user['dropshipping'] === false ) correctly..这是我的中间件,适用于应用程序路由,但我无法让中间件正确处理未经授权的请求( $user['dropshipping'] === false )..

public function handle($request, Closure $next)
{
    $user = Auth::user();

    if($user instanceof Customer) {
        if ($user->guard(['web'])['dropshipping']) {
            return $next($request);
        } elseif($user->guard(['customer-api'])['dropshipping']) {
            return $next($request);
        } else {
            return redirect(route('login'))->with('error', 'Account not activated, please contact TWM BV.');
        }
    } else {
        return $next($request);
    }
}

Guards are associated to Auth not to users.警卫与身份验证相关联,而不是与用户相关联。

So you can use Auth::guard('guard-name') or auth()->guard('guard')所以你可以使用Auth::guard('guard-name')auth()->guard('guard')

public function handle($request, Closure $next)
{
    $user = Auth::user();

    if($user instanceof Customer) {
        if (auth()->guard('web')->user()->dropshipping) {
            return $next($request);
        } elseif(auth()->guard('customer-api')->user()->dropshipping) {
            return $next($request);
        } else {
            return redirect(route('login'))->with('error', 'Account not activated, please contact TWM BV.');
        }
    } else {
        return $next($request);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM