Laravel 5.1 多重认证 [英] Laravel 5.1 multiple authentication

查看:33
本文介绍了Laravel 5.1 多重认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Laravel 5.1 中对多种类型的用户进行身份验证,例如求职者、招聘人员、管理员等.

你们中的一些人建议使用单个用户表来仅存储密码和电子邮件,创建配置文件表来存储用户特定信息(jobseeker_profile、recruiter_profile)并使用角色来区分不同类型的用户(即具有角色和 role_user) 表.

这一切都很好,但是如果不同类型的用户有不同的注册和登录表单怎么办.如何自定义默认的 auth 控制器以显示正确的视图?

所以如果我有以下路线:

//求职者身份验证路由...Route::get('auth/login', 'AuthAuthController@getLogin');Route::post('auth/login', 'AuthAuthController@postLogin');Route::get('auth/logout', 'AuthAuthController@getLogout');//求职者注册路径...Route::get('auth/register', 'AuthAuthController@getRegister');Route::post('auth/register', 'AuthAuthController@postRegister');//招聘人员身份验证路由...Route::get('recruiter/auth/login', 'AuthAuthController@getLogin');Route::post('recruiter/auth/login', 'AuthAuthController@postLogin');Route::get('recruiter/auth/logout', 'AuthAuthController@getLogout');//招聘人员注册路径...Route::get('recruiter/auth/register', 'AuthAuthController@getRegister');Route::post('recruiter/auth/register', 'AuthAuthController@postRegister');

这是开箱即用的默认身份验证控制器:

class AuthController 扩展控制器{使用 AuthenticatesAndRegistersUsers;公共函数 __construct(){$this->middleware('guest', ['except' => 'getLogout']);}受保护的函数验证器(数组 $data){返回 Validator::make($data, ['名称' =>'需要|最大:255','电子邮件' =>'required|email|max:255|unique:users','密码' =>'需要|确认|分钟:6',]);}受保护的函数创建(数组 $data){返回用户::创建(['名称' =>$data['name'],'电子邮件' =>$data['email'],'密码' =>bcrypt($data['password']),]);}}

默认开箱即用的身份验证控制器使用的特征:

trait AuthenticatesUsers{使用重定向用户;公共函数 getLogin(){返回视图('auth.login');}公共函数 postLogin(Request $request){$this->validate($request, ['电子邮件' =>'required|email', 'password' =>'必需的',]);$credentials = $this->getCredentials($request);if (Auth::attempt($credentials, $request->has('remember'))) {return redirect()->intended($this->redirectPath());}返回重定向($this->loginPath())->withInput($request->only('email', 'remember'))->withErrors(['电子邮件' =>$this->getFailedLoginMessage(),]);}公共函数 loginPath(){返回 property_exists($this, 'loginPath') ?$this->loginPath : '/auth/login';}}特质注册用户{使用重定向用户;公共函数 getRegister(){返回视图('auth.register');}公共函数 postRegister(Request $request){$validator = $this->validator($request->all());如果 ($validator->fails()) {$this->throwValidationException($request, $validator);}Auth::login($this->create($request->all()));返回重定向($this->redirectPath());}}

我确信这是许多 Web 应用程序的一个非常普遍的要求,但我找不到任何关于 Laravel 特定实现的有用教程.由于某些奇怪的原因,所有教程都只关注开箱即用的实现.

对上述任何帮助将不胜感激.

解决方案

这不是直接解决您的问题,而是解决您的问题的替代方法.

不要为不同的组创建不同的用户名和密码,而是进行具有角色的中央身份验证.它称为用户和角色.

您可以定义具有不同角色的组,每个角色对各自的区域都有特定的访问权限.

关于注册过程,您可以使用相同的控制器创建两个不同的视图,并且您可以为每个视图创建一个隐藏字段,以表明它是求职者组还是招聘者组.

两者都会收到两封不同的确认电子邮件,他们应该填写其余的个人资料信息,例如招聘人员应填写公司名称,求职者应填写其姓名等.他们可能有两个不同的个人资料表,但仍使用相同的表格登录系统.

通过向中间件添加条件和正确的路由,如果求职者试图访问招聘区域,即使求职者登录系统,求职者将无法访问该区域或相反.

由于 Laravel 5.1 具有

我鼓励你阅读一些关于角色的主题,在这里你也会找到一些对 Laravel 3rd 方 acl 系统的启发,可能还有更多文章,但这里有一些:

阅读:
https://laracasts.com/discuss/channels/laravel/which-package-is-best-for-roles-permissions/?page=2
https://laracasts.com/discuss/channels/一般讨论/laravel-5-用户组管理
https://laracasts.com/discuss/频道/一般讨论/角色和权限-laravel-5


编辑

重要提示
Laravel 5.1 引入了 Authorization,我在网上还没有找到太多文档,但值得花点时间学习一下:

http://laravel.com/docs/5.1/authorization#policies

新更新
有一些很棒的视频解决方案可以满足您的要求,请在此处遵循 ACL 部分https://laracasts.com/series/whats-new-in-laravel-5-1

这也可能很有趣:https://laracasts.com/lessons/email-verification-in-laravel

这将为您提供一个完整的自己开发的解决方案.

How can you authenticate multiple types of users in Laravel 5.1 e.g. Jobseeker, Recruiter, Admin etc.

Some of you have suggested using a single users table to store only the password and email, creating profile tables to store user specific information (jobseeker_profile, recruiter_profile) and using roles to differentiate between the different types of users (i.e having a roles and role_user) table.

This is all very well but then what if the different types of users have different registration and login forms. How do you customize the default auth controller out of the box to display the correct view?

So if I have the following routes:

// Jobseeker Authentication routes...
Route::get('auth/login', 'AuthAuthController@getLogin');
Route::post('auth/login', 'AuthAuthController@postLogin');
Route::get('auth/logout', 'AuthAuthController@getLogout');

// Jobseeker Registration routes...
Route::get('auth/register', 'AuthAuthController@getRegister');
Route::post('auth/register', 'AuthAuthController@postRegister');


// Recruiter Authentication routes...
Route::get('recruiter/auth/login', 'AuthAuthController@getLogin');
Route::post('recruiter/auth/login', 'AuthAuthController@postLogin');
Route::get('recruiter/auth/logout', 'AuthAuthController@getLogout');

// Recruiter Registration routes...
Route::get('recruiter/auth/register', 'AuthAuthController@getRegister');
Route::post('recruiter/auth/register', 'AuthAuthController@postRegister');

This is the default auth controller out of the box:

class AuthController extends Controller
{
    use AuthenticatesAndRegistersUsers;

    public function __construct()
    {
        $this->middleware('guest', ['except' => 'getLogout']);
    }

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
        ]);
    }

    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}    

traits used by the default out of the box auth controller:

trait AuthenticatesUsers
{
   use RedirectsUsers;

   public function getLogin()
   {
        return view('auth.login');
    }

   public function postLogin(Request $request)
   {
        $this->validate($request, [
            'email' => 'required|email', 'password' => 'required',
        ]);

        $credentials = $this->getCredentials($request);

        if (Auth::attempt($credentials, $request->has('remember'))) {
            return redirect()->intended($this->redirectPath());
        }

        return redirect($this->loginPath())
            ->withInput($request->only('email', 'remember'))
            ->withErrors([
               'email' => $this->getFailedLoginMessage(),
            ]);
   }

    public function loginPath()
   {
        return property_exists($this, 'loginPath') ? $this->loginPath : '/auth/login';
    }

}

trait RegistersUsers
{
    use RedirectsUsers;

    public function getRegister()
    {
        return view('auth.register');
    }

    public function postRegister(Request $request)
    {
        $validator = $this->validator($request->all());

        if ($validator->fails()) {
            $this->throwValidationException(
                $request, $validator
            );
         }

         Auth::login($this->create($request->all()));

        return redirect($this->redirectPath());
    }
}

I'm sure this is a very common requirement for many web applications but I can't find any helpful tutorials for Laravel specific implementations. All the tutorial simply focus on the out of the box implementation for some odd reason.

Any help on the above would be much appreciated.

解决方案

This is not a solution to your question directly, but alternative way to solve your question problem with.

In stead of creating different username and password for different groups, make a central authentication that has roles. It called user and roles.

You can define groups with different roles, and each roles has specific access to respective area.

Regarding registration process you can make two differnet views but using the same controller, and for each view you can create a hidden field to indicate if it is jobseekers group or recruiter group.

Both will receive two different confirmation emails where they should fill the rest of the profile information, like recruiter should put company name and jobseeker should put his name etc. they might have two different tables for profile information, but still using the same login system.

By adding condition to middleware and correct route, if jobseeker tries to access recruiter area even if jobseeker is logged in the system, the jobseeker won't be able to access that area or the opposite way.

Since Laravel 5.1 has build in user login system, so you have few choices, build your own roles or use 3rd party.

I suggest you to build your own so you have control over your code and can further develop it as you wish with time. It might take you half day to get it run and understand how it works, but it is worth spending that time with the right approach in stead of the way you go in your Question OR using 3rd party is fine too, there is a lot of packages around you can search for. I have personally used Entrust (https://github.com/Zizaco/entrust) it is easy and nice way to provide roles and permissions to your project.

Here is also a link to video developed by Jeffrey Way at Laracast, it builds user and roles system from scratch for Laravel 4. but since you have user part, just follow roles part and with small modifications you will have a roles system to your Laravel 5.1, I have tried it and it works.

Regarding your question in the comments, when you follow the video you will understand the concept.

Link to the video: https://laracasts.com/lessons/users-and-roles

You might need to create account to see the video, most of videos are free.

Good practice It is always also a good practice to illustrate what you want to achieve that makes things easier, I have just made an example for your project, but that is only example for learning:

I encourage you to read some of the topics regarding roles, here you will also find some inspiration to 3rd party acl systems to Laravel, there might be more articles but here is some:

Reading:
https://laracasts.com/discuss/channels/laravel/which-package-is-best-for-roles-permissions/?page=2
https://laracasts.com/discuss/channels/general-discussion/laravel-5-user-groups-management
https://laracasts.com/discuss/channels/general-discussion/roles-and-permissions-in-laravel-5


EDIT

Important Note
Laravel 5.1 has introduced Authorization, I have not found much documentation online yet but it is worth to spend some time learning it:

http://laravel.com/docs/5.1/authorization#policies

NEW UPDATE
There are some great videos solution for what you asking, follow ACL parts here https://laracasts.com/series/whats-new-in-laravel-5-1

This might be very interesting too: https://laracasts.com/lessons/email-verification-in-laravel

This will give you a complete own developed solution.

这篇关于Laravel 5.1 多重认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆