📜  完整性约束违反 laravel socialite google login - PHP (1)

📅  最后修改于: 2023-12-03 15:25:08.757000             🧑  作者: Mango

完整性约束违反 Laravel Socialite Google Login

问题描述

当使用 Laravel Socialite 以及 Google 用于用户登录时,会出现“完整性约束违反”错误,如下所示:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'google_id-xxxxxxxxxxxxxxxxxxxx' for key 'users_socialite_provider_id_unique'

这个错误通常表示在试图为已经存在于数据库中的用户添加一个新的社交账号时发生了冲突。

解决方案

这个错误的解决方案有两种,可以选择任一一种进行修复。

方案一:忽略错误

你可以通过手动忽略错误,让用户无需遭受任何的干扰。我们可以在控制器中进行修改,如下所示:

try {
    // OAuth 登录
} catch (\Illuminate\Database\QueryException $e) {
    // 如果是 '完整性约束违反' 错误,忽略它
    if ($e->errorInfo[1] == 1062) {
        // 继续登录
    } else {
        // 其他错误,直接抛出异常
        throw $e;
    }
}
方案二:修改代码

如果你想要完全解决这个错误,那么你需要对代码进行一些修改。

我们需要根据 Socialite 提供的回调函数来进行修改。我们可以在 config/services.php 文件中进行配置,如下所示:

return [
    // 其他配置
    'google' => [
        'client_id' => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect' => env('GOOGLE_REDIRECT_URI'),
        'scopes' => [
            Google_Service_PeopleService::USERINFO_EMAIL, 
            Google_Service_PeopleService::USERINFO_PROFILE,
        ],
        'with' => ['user'],
        'user' => [
            'endpoint' => 'https://www.googleapis.com/oauth2/v1/userinfo',
            'fields' => [
                'id',
                'name',
                'email',
                'verified_email',
                'picture',
            ],
        ],
        'callback' => env('GOOGLE_CALLBACK_URL'),
        // 添加这行代码
        'nickname_key' => 'id',
    ],
];

请注意这行代码:

'nickname_key' => 'id',

这是我们新增加的代码,它用来指定 Socialite 使用哪个字段作为用户的唯一标识。

Socialite 默认会使用 getId() 方法返回的值作为唯一标识。但是在 Google OAuth 中,这个值通常是一串随机字符,而不是用户的真实 ID。

我们可以使用 nickname_key 来指定 Socialite 使用哪个字段来代表用户的 ID。

如果你已经使用过 Socialite 登录并且已经有一些用户的数据,那么你需要创建一个迁移文件并修改社交账号关联的列,如下所示:

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        // 删除旧的唯一索引
        $table->dropUnique(['socialite_provider', 'socialite_provider_id']);

        // 添加新的唯一索引
        $table->unique(['socialite_provider', 'google_id']);

        // 修改关联列的类型
        $table->renameColumn('socialite_provider_id', 'google_id');
        $table->string('google_id', 50)->change();
    });
}

public function down()
{
    Schema::table('users', function (Blueprint $table) {
        // 删除新的唯一索引
        $table->dropUnique(['socialite_provider', 'google_id']);

        // 添加旧的唯一索引
        $table->unique(['socialite_provider', 'socialite_provider_id']);

        // 修改关联列的类型
        $table->renameColumn('google_id', 'socialite_provider_id');
        $table->string('socialite_provider_id', 100)->change();
    });
}
结论

总的来说,完整性约束违反错误是一个常见的问题,但是解决起来也非常简单。

你可以选择忽略错误或者修改代码,两种方式都可以解决这个问题。但是建议你尽可能选择方案二,以确保代码的可靠性和稳定性。

以上就是本文的全部内容,如果对你有帮助,请点个赞或者分享给其他的开发者,谢谢!