简体   繁体   English

Laravel 不同角色用户的名媛

[英]Laravel Socialite For Different Role User

I'm creating a project with two user roles.我正在创建一个具有两个用户角色的项目。 I use the role_id field to distinguish roles from users.我使用 role_id 字段来区分角色和用户。

When a user registers an account via manual input I make use of the hidden input to store the role_id.当用户通过手动输入注册帐户时,我使用隐藏的输入来存储 role_id。 But how can I save the role_id of users when they register for an account using a google account?但是,当用户使用google帐户注册帐户时,如何保存用户的role_id?

This is my controller这是我的 controller

public function redirect($provider)
{
    return Socialite::driver($provider)->redirect();
}

public function callback($provider)
{
    $getInfo = Socialite::driver($provider)->user();
    $user = $this->createUser($getInfo, $provider);
    auth()->login($user);

    return redirect()->to('/');
}

function createUser($getInfo, $provider){
    $user = User::where('provider_id', $getInfo->id)->first();

    if(!$user) {
        $user = User::create([
            'name' => $getInfo->name,
            'email' => $getInfo->email,
            'provider' => $provider,
            'provider_id' => $getInfo->id,
            'email_verified_at' => Carbon\Carbon::now()
        ]);

    }

    return $user;
}

This is my route这是我的路线

 Route::get('/auth/redirect/{provider}/', 'LoginUserController@redirect');
 Route::get('/callback/{provider}/', 'LoginUserController@callback' );

My View我的看法

a href="{{ url('/auth/redirect/google') }}" class="link-custom">{{ __('Google Account') }}</a>

Two things you need to consider:您需要考虑两件事:

  • Don't use hidden field to store a role_id .不要使用隐藏字段来存储role_id What's up with an user edit the code inline and change the role_id ?用户编辑内联代码并更改role_id是怎么回事?
  • You should to set up a default value for the role_id field, then all the users will have that default role.您应该为role_id字段设置一个默认值,然后所有用户都将拥有该默认角色。

It is not entirely clear how you save the user role.尚不完全清楚如何保存用户角色。 Is it in a different table?它在不同的表中吗? On which basis do you assign roles to users?您根据什么为用户分配角色? Nevertheless, you could always adjust the createUser method and save the other related info after creating the user.尽管如此,您始终可以在创建用户后调整createUser方法并保存其他相关信息。 For example:例如:

private function createUser($getInfo, $provider){
    $user = User::where('provider_id', $getInfo->id)->first();

    if(!$user) {
        $user = User::create([
            'name' => $getInfo->name,
            'email' => $getInfo->email,
            'provider' => $provider,
            'provider_id' => $getInfo->id,
            'email_verified_at' => Carbon\Carbon::now()
        ]);

        // Here you can save other stuff, 
        // E.g. the user role supposing it is saved in a different table
        UserRole::create([
            'user_id' => $user->id,
            'role_id' => 1 // Assigned role id
        ]);
    }

    return $user;
}

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

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