<?php
<364666827@qq.com>,开发者QQ群:50304283
namespace app\system\model;
use think\Model;
use app\system\model\SystemUser as UserModel;
class SystemRole extends Model
{
protected $createTime = 'ctime';
protected $updateTime = 'mtime';
protected $autoWriteTimestamp = true;
public function setAuthAttr($value)
{
return json_encode($value);
}
/**
* 获取所有角色(下拉列)
* @param int $id 选中的ID
* @author 橘子俊 <364666827@qq.com>
* @return string
*/
public static function getOption($id = 0)
{
$rows = self::column('id,name');
$str = '';
foreach ($rows as $k => $v) {
if ($k == 1) continue;
}
if ($id == $k) {
$str .= '<option value="'.$k.'" selected>'.$v.'</option>';
} else {
$str .= '<option value="'.$k.'">'.$v.'</option>';
}
}
return $str;
}
/**
* 删除角色
* @param string $id 用户ID
* @author 橘子俊 <364666827@qq.com>
* @return bool
*/
public function del($id = 0)
{
$user_model = new UserModel();
if (is_array($id)) {
$error = '';
foreach ($id as $k => $v) {
if ($v == 1) {
$error .= '不能删除超级管理员角色['.$v.']!<br>';
continue;
}
if ($v <= 0) {
$error .= '参数传递错误['.$v.']!<br>';
continue;
}
if (UserModel::where('role_id', $v)->find()) {
$error .= '删除失败,已有管理员绑定此角色['.$v.']!<br>';
continue;
}
$map = [];
$map['id'] = $v;
self::where($map)->delete();
}
if ($error) {
$this->error = $error;
return false;
}
} else {
$id = (int)$id;
if ($id <= 0) {
$this->error = '参数传递错误!';
return false;
}
if ($id == 1) {
$this->error = '不能删除超级管理员角色!';
return false;
}
if (UserModel::where('role_id', $id)->find()) {
$this->error = '删除失败,已有管理员绑定此角色!<br>';
return false;
}
self::where('id', $id)->delete();
}
return true;
}
/**
* 获取所有角色
* @author 橘子俊 <364666827@qq.com>
* @return array
*/
public static function getAll()
{
return self::column('id,name');
}
/**
* 检查访问权限
* @param int $id 需要检查的节点ID
* @author 橘子俊 <364666827@qq.com>
* @return bool
*/
public static function checkAuth($id = 0)
{
$login = session('admin_user');
if ($login['uid'] == '1' || $login['role_id'] == '1') {
return true;
}
$role_auth = (array)session('role_auth_'.$login['role_id']);
if (!$role_auth) {
$auth = self::where('id', $login['role_id'])->value('auth');
if (!$auth) {
return false;
}
$role_auth = json_decode($auth, true);
if (config('sys.app_debug') == 0) {
session('role_auth_'.$login['role_id'], $role_auth);
}
}
if (!$role_auth) return false;
return in_array($id, $role_auth);
}
}