权限管理是一个项目中必不可少的模块之一,常用的有RBAC、Auth等。本文就分享在TP5中通过Auth验证权限的实例,希望对大家有所帮助。
<?php namespace think; use think\Config; use think\Session; use think\Db; /** * 权限认证类 */ //数据库 /* -- ---------------------------- -- mt4_auth_rule,规则表, -- id:主键,name:规则唯一标识, title:规则中文名称 status 状态:为1正常,为0禁用,condition:规则表达式,为空表示存在就验证,不为空表示按照条件验证 -- ---------------------------- DROP TABLE IF EXISTS `mt4_auth_rule`; CREATE TABLE `mt4_auth_rule` ( `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, `name` char(80) NOT NULL DEFAULT '', `title` char(20) NOT NULL DEFAULT '', `type` tinyint(1) NOT NULL DEFAULT '1', `status` tinyint(1) NOT NULL DEFAULT '1', `condition` char(100) NOT NULL DEFAULT '', # 规则附件条件,满足附加条件的规则,才认为是有效的规则 PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- ---------------------------- -- mt4_auth_group 用户组表, -- id:主键, title:用户组中文名称, rules:用户组拥有的规则id, 多个规则","隔开,status 状态:为1正常,为0禁用 -- ---------------------------- DROP TABLE IF EXISTS `mt4_auth_group`; CREATE TABLE `mt4_auth_group` ( `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, `title` char(100) NOT NULL DEFAULT '', `status` tinyint(1) NOT NULL DEFAULT '1', `rules` char(80) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- ---------------------------- -- mt4_auth_group_access 用户组明细表 -- uid:用户id,group_id:用户组id -- ---------------------------- DROP TABLE IF EXISTS `mt4_auth_group_access`; CREATE TABLE `mt4_auth_group_access` ( `uid` mediumint(8) unsigned NOT NULL, `group_id` mediumint(8) unsigned NOT NULL, UNIQUE KEY `uid_group_id` (`uid`,`group_id`), KEY `uid` (`uid`), KEY `group_id` (`group_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; */ class Auth { //默认配置 protected $config = array( 'auth_on' => true, // 认证开关 'auth_type' => 2, // 认证方式,1为实时认证;2为登录认证。 'auth_group' => 'auth_group', // 用户组数据表名 'auth_group_access' => 'auth_group_access', // 用户-用户组关系表 'auth_rule' => 'auth_rule', // 权限规则表 'auth_user' => 'auth_admin' // 用户信息表 ); public function __construct() { if (Config::get('auth_config')) { $this->config = array_merge($this->config, Config::get('auth_config')); //可设置配置项 auth_config, 此配置项为数组。 } } /** * 检查权限 * @param name string|array 需要验证的规则列表,支持逗号分隔的权限规则或索引数组 * @param uid int 认证用户的id * @param string mode 执行check的模式 * @param relation string 如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证 * return boolean 通过验证返回true;失败返回false */ public function check($name, $uid, $type = 1, $mode = 'url', $relation = 'or') { if (!$this->config['auth_on']) { return true; } $authList = $this->getAuthList($uid, $type); //获取用户需要验证的所有有效规则列表 if (is_string($name)) { $name = strtolower($name); // if (strpos($name, ',') !== false) { // $name = explode(',', $name); // } else { // $name = [$name]; // } $name = strpos($name, ',') !== false ? explode(',', $name) : [$name]; } $list = []; //保存验证通过的规则名 if ($mode == 'url') { $REQUEST = unserialize(strtolower(serialize($_REQUEST))); } foreach ($authList as $auth) { $query = preg_replace('/^.+\?/U', '', $auth); if ($mode == 'url' && $query != $auth) { parse_str($query, $param); //解析规则中的param $intersect = array_intersect_assoc($REQUEST, $param); $auth = preg_replace('/\?.*$/U', '', $auth); if (in_array($auth, $name) && $intersect == $param) { //如果节点相符且url参数满足 $list[] = $auth; } } else if (in_array($auth, $name)) { $list[] = $auth; } } if ($relation == 'or' and ! empty($list)) { return false; } $diff = array_diff($name, $list); if ($relation == 'and' and empty($diff)) { return false; } return true; } /** * 根据用户id获取用户组,返回值为数组 * @param uid int 用户id * return array 用户所属的用户组 [ * ['uid'=>'用户id','group_id'=>'用户组id','title'=>'用户组名称','rules'=>'用户组拥有的规则id,多个,号隔开'), * ...) */ public function getGroups($uid) { static $groups = []; if (isset($groups[$uid])) { return $groups[$uid]; } $user_groups = Db::view($this->config['auth_group_access'], 'uid,group_id')->view($this->config['auth_group'], 'title,rules', "{$this->config['auth_group_access']}.group_id={$this->config['auth_group']}.id") ->where(['uid' => $uid, 'status' => 1])->select(); $groups[$uid] = $user_groups ? $user_groups : []; return $groups[$uid]; } /** * 获得权限列表 * @param integer $uid 用户id * @param integer $type */ protected function getAuthList($uid, $type) { static $_authList = []; //保存用户验证通过的权限列表 $t = implode(',', (array) $type); if (isset($_authList[$uid . $t])) { return $_authList[$uid . $t]; } if ($this->config['auth_type'] == 2 && Session::has('_auth_list_' . $uid . $t)) { return Session::get('_auth_list_' . $uid . $t); } //读取用户所属用户组 $groups = $this->getGroups($uid); $ids = []; //保存用户所属用户组设置的所有权限规则id foreach ($groups as $g) { $ids = array_merge($ids, explode(',', trim($g['rules'], ','))); } $ids = array_unique($ids); if (empty($ids)) { $_authList[$uid . $t] = []; return []; } $map = [ 'id' => ['notin', $ids], 'type' => $type, 'status' => 1, ]; //读取用户组所有权限规则 $rules = Db::name($this->config['auth_rule'])->where($map)->field('condition,name')->select(); //循环规则,判断结果。 $authList = []; // foreach ($rules as $rule) { if (!empty($rule['condition'])) { //根据condition进行验证 $this->getUserInfo($uid); //获取用户信息,一维数组 $command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['condition']); @(eval('$condition=(' . $command . ');')); $condition && $authList[] = strtolower($rule['name']); } else { $authList[] = strtolower($rule['name']); //只要存在就记录 } } $_authList[$uid . $t] = $authList; if ($this->config['auth_type'] == 2) { $_SESSION['_auth_list_' . $uid . $t] = $authList; //规则列表结果保存到session } return array_unique($authList); } /** * 获得用户资料,根据自己的情况读取数据库 */ protected function getUserInfo($uid) { static $userinfo = []; if (!isset($userinfo[$uid])) { $userinfo[$uid] = Db::name($this->config['auth_user'])->where(['uid' => $uid])->find(); } return $userinfo[$uid]; } }
相关推荐:
ThinkPHP(RBAC)权限管理视频以及资料(源码、课件)分享
위 내용은 TP5 인증 권한 관리 예시의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

phpsessionscanstorestrings, 숫자, 배열 및 객체 1.Strings : TextDatalikeUsernames.2.numbers : integorfloatsforcounters.3.arrays : listslikeshoppingcarts.4.objects : complexStructuresThatareserialized.

세션 재생은 세션 고정 공격의 경우 사용자가 민감한 작업을 수행 할 때 새 세션 ID를 생성하고 이전 ID를 무효화하는 것을 말합니다. 구현 단계에는 다음이 포함됩니다. 1. 민감한 작업 감지, 2. 새 세션 ID 생성, 3. 오래된 세션 ID 파괴, 4. 사용자 측 세션 정보 업데이트.

PHP 세션은 응용 프로그램 성능에 큰 영향을 미칩니다. 최적화 방법은 다음과 같습니다. 1. 데이터베이스를 사용하여 세션 데이터를 저장하여 응답 속도를 향상시킵니다. 2. 세션 데이터 사용을 줄이고 필요한 정보 만 저장하십시오. 3. 비 차단 세션 프로세서를 사용하여 동시성 기능을 향상시킵니다. 4. 사용자 경험과 서버 부담의 균형을 맞추기 위해 세션 만료 시간을 조정하십시오. 5. 영구 세션을 사용하여 데이터 읽기 및 쓰기 시간의 수를 줄입니다.

phpsessionsareser-side, whilecookiesareclient-side.1) sessions stessoredataontheserver, andhandlargerdata.2) cookiesstoredataonthecure, andlimitedinsize.usesessionsforsensitivestataondcookiesfornon-sensistive, client-sensation.

phpidifiesauser의 sssessionusessessioncookiesandssessionids.1) whensession_start () iscalled, phpgeneratesauniquessessionStoredInacookienamedPhpsSessIdonSeuser 'sbrowser.2) thisidallowsphptoretrievessessionDataTromServer.

PHP 세션의 보안은 다음 측정을 통해 달성 할 수 있습니다. 1. Session_REGENEREAT_ID ()를 사용하여 사용자가 로그인하거나 중요한 작업 일 때 세션 ID를 재생합니다. 2. HTTPS 프로토콜을 통해 전송 세션 ID를 암호화합니다. 3. 세션 _save_path ()를 사용하여 세션 데이터를 저장하고 권한을 올바르게 설정할 보안 디렉토리를 지정하십시오.

phpsessionfilesarestoredInTheRectorySpecifiedBysession.save_path, 일반적으로/tmponunix-likesystemsorc : \ windows \ temponwindows.tocustomizethis : 1) austession_save_path () toSetacustomDirectory, verlyTeCustory-swritation;


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

드림위버 CS6
시각적 웹 개발 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.
