84 lines
2.0 KiB
PHP
84 lines
2.0 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace app\mzl\modules\permission\model;
|
||
|
|
|
||
|
|
use support\Model;
|
||
|
|
use support\Redis;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* User
|
||
|
|
*/
|
||
|
|
class User extends Model
|
||
|
|
{
|
||
|
|
/**
|
||
|
|
* The connection name for the model.
|
||
|
|
*
|
||
|
|
* @var string|null
|
||
|
|
*/
|
||
|
|
protected $connection = 'mysql';
|
||
|
|
|
||
|
|
/**
|
||
|
|
* The table associated with the model.
|
||
|
|
*
|
||
|
|
* @var string
|
||
|
|
*/
|
||
|
|
protected $table = 'wzh_user';
|
||
|
|
|
||
|
|
/**
|
||
|
|
* The primary key associated with the table.
|
||
|
|
*
|
||
|
|
* @var string
|
||
|
|
*/
|
||
|
|
protected $primaryKey = 'id';
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Indicates if the model should be timestamped.
|
||
|
|
*
|
||
|
|
* @var bool
|
||
|
|
*/
|
||
|
|
public $timestamps = true;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 模型的数据字段的保存格式。
|
||
|
|
*
|
||
|
|
* @var string
|
||
|
|
*/
|
||
|
|
protected $dateFormat = 'U';
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 允许自动填充模型字段
|
||
|
|
*/
|
||
|
|
protected $fillable = ['id', 'password', 'realname', 'idcard', 'gzh_openid', 'identity', 'role_id', 'sex', 'phone', 'created_at', 'updated_at', 'deleted_at'];
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 不允许自动填充模型字段
|
||
|
|
*/
|
||
|
|
protected $guarded = [];
|
||
|
|
|
||
|
|
public function roles()
|
||
|
|
{
|
||
|
|
return $this->belongsToMany(Role::class, 'role_user');
|
||
|
|
}
|
||
|
|
|
||
|
|
public function hasPermission2(string $permission): bool
|
||
|
|
{
|
||
|
|
// 加载角色和每个角色的权限
|
||
|
|
$roles = $this->roles()->with('permissions')->get();
|
||
|
|
// 判断是否有某个权限
|
||
|
|
return $roles->pluck('permissions')->flatten()->pluck('name')->contains($permission);
|
||
|
|
}
|
||
|
|
|
||
|
|
public function hasPermission(string $permission, int $ttl = 24 * 60 * 60): bool
|
||
|
|
{
|
||
|
|
$cacheKey = 'user_permissions_' . $this->id;
|
||
|
|
$permissions = Redis::get($cacheKey);
|
||
|
|
if (!$permissions) {
|
||
|
|
$roles = $this->roles()->with('permissions')->get();
|
||
|
|
$permissions = $roles->pluck('permissions')->flatten()->pluck('name')->toArray();
|
||
|
|
Redis::setEx($cacheKey, $ttl, json_encode($permissions));
|
||
|
|
} else {
|
||
|
|
$permissions = json_decode($permissions, true);
|
||
|
|
}
|
||
|
|
return in_array($permission, $permissions);
|
||
|
|
}
|
||
|
|
}
|