think php auth实例,ThinkPHP权限认证Auth实例详解

本文以实例代码的形式深入剖析了ThinkPHP权限认证Auth的实现原理与方法,具体步骤如下:

sql;">

-- ----------------------------

-- Table structure for think_auth_group

-- ----------------------------

DROP TABLE IF EXISTS `think_auth_group`;

CREATE TABLE `think_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 AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='用户组表';

-- Records of think_auth_group

INSERT INTO think_auth_group VALUES ('1','管理组','1','1,2');

-- Table structure for think_auth_group_access

DROP TABLE IF EXISTS think_auth_group_access;

CREATE TABLE think_auth_group_access (

uid mediumint(8) unsigned NOT NULL COMMENT '用户id',group_id mediumint(8) unsigned NOT NULL COMMENT '用户组id',UNIQUE KEY uid_group_id (uid,group_id),KEY uid (uid),KEY group_id (group_id)

) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='用户组明细表';

-- Records of think_auth_group_access

INSERT INTO think_auth_group_access VALUES ('1','1');

INSERT INTO think_auth_group_access VALUES ('1','2');

-- Table structure for think_auth_rule

DROP TABLE IF EXISTS think_auth_rule;

CREATE TABLE think_auth_rule (

id mediumint(8) unsigned NOT NULL AUTO_INCREMENT,name char(80) NOT NULL DEFAULT '' COMMENT '规则唯一标识',title char(20) NOT NULL DEFAULT '' COMMENT '规则中文名称',status tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态:为1正常,为0禁用',type char(80) NOT NULL,condition char(100) NOT NULL DEFAULT '' COMMENT '规则表达式,为空表示存在就验证,不为空表示按照条件验证',PRIMARY KEY (id),UNIQUE KEY name (name)

) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='规则表';

-- Records of think_auth_rule

INSERT INTO think_auth_rule VALUES ('1','Home/index','列表','Home','');

INSERT INTO think_auth_rule VALUES ('2','Home/add','添加','');

INSERT INTO think_auth_rule VALUES ('3','Home/edit','编辑','');

INSERT INTO think_auth_rule VALUES ('4','Home/delete','删除','');

DROP TABLE IF EXISTS think_user;

CREATE TABLE think_user (

id int(11) NOT NULL,username varchar(30) DEFAULT NULL,password varchar(32) DEFAULT NULL,age tinyint(2) DEFAULT NULL,PRIMARY KEY (id)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- Records of think_user

INSERT INTO think_user VALUES ('1','admin','21232f297a57a5a743894a0e4a801fc3','25');

配置文件Application\Common\Conf\config.PHP部分:

PHP;">

return array(

//'配置项'=>'配置值'

'DB_DSN' => '',// 数据库连接DSN 用于PDO方式

'DB_TYPE' => 'MysqL',// 数据库类型

'DB_HOST' => 'localhost',// 服务器地址

'DB_NAME' => 'thinkPHP',// 数据库名

'DB_USER' => 'root',// 用户名

'DB_PWD' => 'root',// 密码

'DB_PORT' => 3306,// 端口

'DBPREFIX' => 'think',// 数据库表前缀

'AUTH_CONFIG' => array(

'AUTH_ON' => true,//认证开关

'AUTH_TYPE' => 1,// 认证方式,1为时时认证;2为登录认证。

'AUTH_GROUP' => 'think_auth_group',//用户组数据表名

'AUTH_GROUP_ACCESS' => 'think_auth_group_access',//用户组明细表

'AUTH_RULE' => 'think_auth_rule',//权限规则表

'AUTH_USER' => 'think_user'//用户信息表

)

);

项目Home控制器部分Application\Home\Controller\IndexController.class.PHP代码:

PHP;">

check($name,$uid,$type,$mode,$relation)) {

die('认证:成功');

} else {

die('认证:失败');

}

}

}

以上这些代码就是最基本的验证代码示例。

下面是源码阅读:

1、权限检验类初始化配置信息:

PHP;">

$Auth = new \Think\Auth();

创建一个对象时程序会合并配置信息

程序会合并Application\Common\Conf\config.PHP中的AUTH_CONFIG数组

_config['AUTH_GROUP'] = $prefix . $this->_config['AUTH_GROUP'];

$this->_config['AUTH_RULE'] = $prefix . $this->_config['AUTH_RULE'];

$this->_config['AUTH_USER'] = $prefix . $this->_config['AUTH_USER'];

$this->_config['AUTH_GROUP_ACCESS'] = $prefix . $this->_config['AUTH_GROUP_ACCESS'];

if (C('AUTH_CONFIG')) {

//可设置配置项 AUTH_CONFIG,此配置项为数组。

$this->_config = array_merge($this->_config,C('AUTH_CONFIG'));

}

}

2、检查权限:

PHP;">

check($name,$type = 1,$mode = 'url',$relation = 'or')

大体分析一下这个方法

首先判断是否关闭权限校验 如果配置信息AUTH_ON=>false 则不会进行权限验证 否则继续验证权限

_config['AUTH_ON']) {

return true;

}

获取权限列表之后会详细介绍:

getAuthList($uid,$type);

此次需要验证的规则列表转换成数组:

PHP;">

if (is_string($name)) {

$name = strtolower($name);

if (strpos($name,',') !== false) {

$name = explode(',$name);

} else {

$name = array($name);

}

}

所以$name参数是不区分大小写的,最终都会转换成小写

开启url模式时全部转换为小写:

PHP;">

if ($mode == 'url') {

$REQUEST = unserialize(strtolower(serialize($_REQUEST)));

}

权限校验核心代码段之一,即循环所有该用户权限 判断 当前需要验证的权限 是否 在用户授权列表中:

PHP;">

foreach ($authList as $auth) {

$query = preg_replace('/^.+\?/U','',$auth);//获取url参数

if ($mode == 'url' && $query != $auth) {

parse_str($query,$param); //获取数组形式url参数

$intersect = array_intersect_assoc($REQUEST,$param);

$auth = preg_replace('/\?.*$/U',$auth);//获取访问的url文件

if (in_array($auth,$name) && $intersect == $param) { //如果节点相符且url参数满足

$list[] = $auth;

}

} else if (in_array($auth,$name)) {

$list[] = $auth;

}

}

in_array($auth,$name) 如果 权限列表中 其中一条权限 等于 当前需要校验的权限 则加入到$list中

注:

PHP;">

$list = array(); //保存验证通过的规则名

if ($relation == 'or' and !empty($list)) {

return true;

}

$diff = array_diff($name,$list);

if ($relation == 'and' and empty($diff)) {

return true;

}

$relation == 'or' and !empty($list); //当or时 只要有一条是通过的 则 权限为真

$relation == 'and' and empty($diff); //当and时 $name与$list完全相等时 权限为真

3、获取权限列表:

getAuthList($uid,$type); //获取用户需要验证的所有有效规则列表

这个主要流程:

getGroups($uid);

//SELECT `rules` FROM think_auth_group_access a INNER JOIN think_auth_group g on a.group_id=g.id WHERE ( a.uid='1' and g.status='1' )

简化操作就是:

sql;">

SELECT `rules` FROM think_auth_group WHERE STATUS = '1' AND id='1'//按正常流程 去think_auth_group_access表中内联有点多余....!

取得用户组rules规则字段 这个字段中保存的是think_auth_rule规则表的id用,分割

$ids就是$groups变量最终转换成的 id数组:

array('in',$ids),'type' => $type,'status' => 1,);

取得think_auth_rule表中的规则信息,之后循环:

getUserInfo($uid); //获取用户信息,一维数组

$command = preg_replace('/\{(\w*?)\}/','$user[\'\\1\']',$rule['condition']);

//dump($command);//debug

@(eval('$condition=(' . $command . ');'));

if ($condition) {

$authList[] = strtolower($rule['name']);

}

} else {

//只要存在就记录

$authList[] = strtolower($rule['name']);

}

}

if (!empty($rule['condition'])) { //根据condition进行验证

这里就可以明白getUserInfo 会去获取配置文件AUTH_USER对应表名 去查找用户信息

重点是:

PHP;">

$command = preg_replace('/\{(\w*?)\}/',$rule['condition']);

@(eval('$condition=(' . $command . ');'));

'/\{(\w*?)\}/ 可以看成要匹配的文字为 {字符串} 那么 {字符串} 会替换成$user['字符串']

$command =$user['字符串']

如果

5';

$command =$user['age'] > 10

@(eval('$condition=(' . $command . ');'));

即:

10);

这时再看下面代码 如果为真则加为授权列表

PHP;">

if ($condition) {

$authList[] = strtolower($rule['name']);

}

更多关于thinkPHP相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》及《PHP模板技术总结》。

希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。

总结

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Django auth 是 Django 自带的认证系统,它提供了用户认证权限管理和用户会话管理等功能,可以方便地为 Django 应用添加用户认证权限控制功能。 首先,在 Django 项目中需要在 settings.py 文件中配置 auth 应用: ``` INSTALLED_APPS = [ ... 'django.contrib.auth', 'django.contrib.contenttypes', ... ] ``` 接着,在 Django 项目的 urls.py 文件中添加 auth 的 URL 配置: ``` from django.contrib.auth import views as auth_views urlpatterns = [ ... path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), ... ] ``` 这里使用了 Django 自带的 LoginView 和 LogoutView 来处理用户登录和注销,可以通过重写这两个视图来自定义登录和注销的行为。 在 Django auth 中,用户模型是通过 auth.User 类来实现的,可以通过以下代码获取当前登录的用户: ``` from django.contrib.auth.decorators import login_required @login_required def my_view(request): user = request.user ... ``` 这里使用了 Django 自带的 login_required 装饰器来限制只有登录用户才能访问 my_view 视图。 除了用户认证外,Django auth 还提供了权限管理功能,可以通过以下代码来控制用户的权限: ``` from django.contrib.auth.decorators import permission_required @permission_required('myapp.can_view') def my_view(request): ... ``` 这里使用了 Django 自带的 permission_required 装饰器来限制只有拥有 myapp.can_view 权限的用户才能访问 my_view 视图。 举个实例,假设我们要实现一个博客应用,只有登录用户才能发表文章和评论,并且只有文章的作者和管理员才能编辑和删除文章。可以通过以下代码来实现: ``` from django.contrib.auth.decorators import login_required, permission_required from django.shortcuts import get_object_or_404, render, redirect from django.contrib import messages from django.contrib.auth.models import User from .models import Post, Comment @login_required def new_post(request): if request.method == 'POST': title = request.POST['title'] content = request.POST['content'] author = request.user post = Post.objects.create(title=title, content=content, author=author) messages.success(request, 'Post created successfully!') return redirect('post_detail', post.id) return render(request, 'new_post.html') @login_required def new_comment(request, post_id): post = get_object_or_404(Post, id=post_id) if request.method == 'POST': content = request.POST['content'] author = request.user comment = Comment.objects.create(post=post, content=content, author=author) messages.success(request, 'Comment created successfully!') return redirect('post_detail', post.id) return render(request, 'new_comment.html', {'post': post}) @login_required @permission_required('blog.change_post', raise_exception=True) def edit_post(request, post_id): post = get_object_or_404(Post, id=post_id) if request.method == 'POST': title = request.POST['title'] content = request.POST['content'] post.title = title post.content = content post.save() messages.success(request, 'Post updated successfully!') return redirect('post_detail', post.id) return render(request, 'edit_post.html', {'post': post}) @login_required @permission_required('blog.delete_post', raise_exception=True) def delete_post(request, post_id): post = get_object_or_404(Post, id=post_id) post.delete() messages.success(request, 'Post deleted successfully!') return redirect('post_list') ``` 这里使用了 Django auth 的登录限制和权限管理功能来保护博客应用中的敏感操作,只有登录用户才能发表文章和评论,并且只有文章的作者和管理员才能编辑和删除文章。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值