Laravel 多域名下的字段验证

5次阅读

共计 2377 个字符,预计需要花费 6 分钟才能阅读完成。

前言
正在开发一个统一作者后台,用来让作者给网站提交软件。我们已经对其中一个网站开发了作者后台,现在我们打算将这一个后台提供给其他网站。它具备如下的一些特点:

我们访问的域名是不一致的,解决方案见我的一篇文章,Laravel 路由研究之 domain 解决多域名问题

其次各个站点对后台的要求都是一致的,也就是说,一个后台 N 各站去用。

功能拆分
开始之前我们需要对系统各个功能点进行拆分,估算受影响的点:

登录注册登录注册功能首当其冲,我们需要用户在注册时通过访问的域名不同,记录的身份也不同。所以我们需要进行如下的处理:

增加字段 identity

进行判重
进行登录验证

数据处理这个就不进行讨论了。根据用户所属身份不同,调用的数据也不同就行了。

注册判重
判重依据:我们知道使用 php artisan make:auth 后,默认使用 email 登录,在表单验证中默认对 email 进行判重。代码如下:

默认表单验证:
// Path:app/Http/Controllers/Auth/RegisterController.php
protected function validator(array $data)
{
return Validator::make($data, [
‘name’ => [‘required’, ‘string’, ‘max:255′],
’email’ => [‘required’, ‘string’, ’email’, ‘max:255’, ‘unique:users’],
‘password’ => [‘required’, ‘string’, ‘min:8’, ‘confirmed’],
]);
}

默认登录验证字段
// Path:vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php
public function username()
{
return ’email’;
}
// 当然可以修改验证字段(看过文档的都知道),注意:登录验证字段必须是在表里面唯一的。

现在我们需要分析我们的需求:在单一用户后台中,email 判重已经足够了,但是对于多种用户一起使用就不太够了。假设:我们有 A,B 两个域名,对应 a,b 两种用户,我们需要在一张表中存储 a,b,首先我们判断 a,b 是属于那个域名的(站点),其次,看这个用户是否重复。下面我们用 Laravel 表单验证来实现一下:

增加字段: 为方便演示,我直接在 make auth 生成的迁移文件上直接修改,大家不要在实际项目中直接修改,而是通过新建迁移文件,使用修改表结构的方式增加字段
public function up()
{
Schema::create(‘users’, function (Blueprint $table) {
$table->bigIncrements(‘id’);
$table->string(‘name’);
$table->string(’email’); // 去掉原来的 unique
$table->string(‘identity’); // 增加的字段
$table->timestamp(’email_verified_at’)->nullable();
$table->string(‘password’);
$table->rememberToken();
$table->timestamps();
});
}
注意:在这个需求中,我们对迁移文件中的 email 和 name 字段不需要进行 unique 限定,因为他们的唯一性是有依赖的,不是独立的。

模拟用户注册,插入身份信息
// Path: app/Http/Controllers/Auth/RegisterController.php
protected function create(array $data)
{
return User::create([
‘name’ => $data[‘name’],
’email’ => $data[’email’],
‘password’ => Hash::make($data[‘password’]),
‘identity’ => ‘pcsoft’, // 模拟用户注册时,插入身份字段值
]);
}

进行判重处理
protected function validator(array $data)
{
return Validator::make($data, [
‘name’ => [‘required’, ‘string’, ‘max:255′],
’email’ => [‘required’, ‘string’, ’email’, ‘max:255’, Rule::unique(‘users’)->where(function ($query) {
$query->where(‘identity’, ‘=’, ‘onlinedown’);
})], // 这句话的意思:按照什么条件对 users 表中的 email 去重,我们需要按照身份字段等于我们访问的域名对 email 去重,
‘password’ => [‘required’, ‘string’, ‘min:8’, ‘confirmed’],
]);
}

测试

进行第一次注册,数据库截如下:

进行第二次注册,相同邮件,不同身份:

相同身份,相同邮箱测试

登录验证
覆写 credentials,传入身份验证字段
// Path:app/Http/Controllers/Auth/LoginController.php
protected function credentials(Request $request)
{
$request->merge([‘identity’ => Controller::getWebPrefix()]);
return $request->only($this->username(), ‘password’, ‘identity’);
}

正文完
 0