Files
laravel-google2fa-module/Models/Google2FA.php
2022-12-02 11:52:48 +08:00

143 lines
3.0 KiB
PHP

<?php
namespace Modules\Google2FA\Models;
use App\Models\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Support\Facades\Crypt;
class Google2FA extends Model
{
protected $table = 'google2fas';
protected $casts = [
'status' => 'boolean',
];
protected static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->google2fa_secret = app('g2fa')->generateSecretKey(config('google2fa.key_length'));
});
}
/**
* Notes : 所属模型
*
* @Date : 2022/12/1 13:28
* @Author : <Jason.C>
* @return MorphTo
*/
public function subscriber(): MorphTo
{
return $this->morphTo(__FUNCTION__, 'subscriber_type', 'subscriber_id');
}
/**
* Notes : 更新密钥
*
* @Date : 2022/12/1 13:26
* @Author : <Jason.C>
* @return bool
*/
public function upgrade(): bool
{
$this->google2fa_secret = app('g2fa')->generateSecretKey(config('google2fa.key_length'));
return $this->save();
}
/**
* Notes : 开启两步验证
*
* @Date : 2022/12/1 15:45
* @Author : <Jason.C>
* @return bool
*/
public function open(): bool
{
$this->status = 1;
return $this->save();
}
/**
* Notes : 关闭两步验证
*
* @Date : 2022/12/1 15:44
* @Author : <Jason.C>
* @return bool
*/
public function close(): bool
{
$this->status = 0;
return $this->save();
}
/**
* Notes :
*
* @Date : 2022/12/1 13:31
* @Author : <Jason.C>
* @return string
*/
public function getQRCodeUrl(): string
{
return app('g2fa')->getQRCodeUrl(
$this->subscriber->getUsername(),
$this->subscriber->getNickname().'@'.config('app.name'),
$this->google2fa_secret
);
}
/**
* Notes : 验证
*
* @Date : 2022/11/30 20:49
* @Author : <Jason.C>
* @param string $value
* @return bool
*/
public function verify(string $value): bool
{
return app('g2fa')->verifyGoogle2FA($this->google2fa_secret, $value);
}
/**
* Notes : 获取当前验证码
*
* @Date : 2022/12/2 11:49
* @Author : <Jason.C>
* @return mixed
*/
public function getCurrentOtp()
{
return app('g2fa')->getCurrentOtp($this->google2fa_secret);
}
/**
* Notes : 存储到数据库的数据加密
*
* @Date : 2022/12/2 11:49
* @Author : <Jason.C>
* @param $value
*/
public function setGoogle2faSecretAttribute($value): void
{
$this->attributes['google2fa_secret'] = Crypt::encrypt($value);
}
/**
* Notes : 解密
*
* @Date : 2022/12/2 11:49
* @Author : <Jason.C>
* @param $value
* @return string
*/
public function getGoogle2faSecretAttribute($value): string
{
return Crypt::decrypt($value);
}
}