laravel 如何使用 auth 中间件管理不同用户类型的登录/重定向?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29845087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:26:11  来源:igfitidea点击:

How to use auth middleware to manage login/redirect of different user types?

phpauthenticationlaravelloginlaravel-5

提问by rolfk

I want to set up two login paths,

我想设置两个登录路径,

  • /admin/
  • /users/
  • /行政/
  • /用户/

Laravel 5 provides auth middleware for authentication. The middleware also provides default views for login, password reset, etc, which I'm planning use as-is, functionally.

Laravel 5 提供了用于身份验证的 auth 中间件。中间件还提供用于登录、密码重置等的默认视图,我计划按原样在功能上使用这些视图。

!: What changes are needed in routes.php and in Controllers to manage these two logins?

!: 需要在routes.php 和Controllers 中进行哪些更改来管理这两个登录?

!!: How do I manage their redirects (one to admin panel, other back to homepage)? (presently auth redirects to 'home' view by default)

!!:我如何管理他们的重定向(一个到管理面板,另一个回到主页)?(目前 auth 默认重定向到“home”视图)

Edit: I know how to prevent unauthorized access, however I'm talking about a setup where I can manage both accesses separately.

编辑:我知道如何防止未经授权的访问,但是我说的是一种可以分别管理两种访问的设置。

回答by Margus Pala

One way is to bind same controller to different paths if the user pool is actually the same.

如果用户池实际上相同,则一种方法是将相同的控制器绑定到不同的路径。

You can decide where to redirect based on logged in user type in the RedirectIfAuthenticated Middleware.

您可以根据 RedirectIfAuthenticated 中间件中的登录用户类型决定重定向的位置。

回答by Fabio Antunes

You could check on your controller if the user is admin or user and present him the correct view, but do you really need a login page different for your users and admins? Do you really need a recover password different for both? If not then you can use the AuthController for both of them, if so then why don't you create two controllers that extend AuthController?

您可以检查您的控制器,如果用户是 admin 或 user 并向他展示正确的视图,但您真的需要一个不同的登录页面供您的用户和管理员使用吗?你真的需要一个不同的恢复密码吗?如果不是,那么您可以对它们都使用 AuthController,如果是,那么为什么不创建两个扩展 AuthController 的控制器呢?

For me the best solution and to keep things clean and separated why don't you extend or even modify RedfirectIfAuthenticated

对我来说最好的解决方案是保持干净和分离,为什么不扩展甚至修改 RedfirectIfAuthenticated

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\RedirectResponse;
use User;

class RedirectIfAuthenticated {

    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->check())
        {
            //we have a logged user check if it's admin
            if($this->auth->user()->admin){
              return new RedirectResponse(url('/admin'));
            }else{
              return new RedirectResponse(url('/user'));
            }
        }

        return $next($request);
    }

}

You could also create a middleware to protect your admin routes:

您还可以创建一个中间件来保护您的管理路由:

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;

class VerifyAdmin {

     /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$this->auth->user()->admin)
        {
            if ($request->ajax())
            {
                return response('Unauthorized.', 401);
            }
            else
            {
                //redirect user or guest to home page or something like that
            }
        }

        return $next($request);

    }

}

register your middleware:

注册你的中间件:

// Within App\Http\Kernel Class...

protected $routeMiddleware = [
    'auth' => 'App\Http\Middleware\Authenticate',
    'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
    'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
    'auth.admin' => 'App\Http\Middleware\VerifyAdmin',
];

On your routes:

在您的路线上:

Route::group(['prefix' => 'admin', 'middleware' => 'auth.admin'], function()
{
    Route::resource('profile','API\ProfileController');
});

回答by Chukky Nze

Admin and Users in the same laravel app is a bad idea simply because the app will share the same session and storage information. There will be a myriad of egde cases that will cause information to bleed through any logic "walls" you set up and you'll end up spending way too much time patching those bleeds. What you really want to do is set up separate laravel applications for each: admin.project.com & project.com. That way you get two separate sessions and storage. All you need to do is ensure that the databases you need are setup in both database.php config files. You can even host BOTH projects on the same server with separate deployments, listening to different ports. TRUST ME this is the best way to go.

Admin 和 Users 在同一个 laravel 应用程序中是一个坏主意,因为该应用程序将共享相同的会话和存储信息。将有无数的 egde 案例会导致信息通过您设置的任何逻辑“墙”流血,最终您将花费太多时间修补这些流血。您真正想做的是为每个应用程序设置单独的 Laravel 应用程序:admin.project.com 和 project.com。这样你就可以得到两个单独的会话和存储。您需要做的就是确保在两个 database.php 配置文件中都设置了您需要的数据库。您甚至可以在具有单独部署的同一台服务器上托管两个项目,侦听不同的端口。相信我,这是最好的方法。