Thinkphp Auth类重构用于连接另一个数据库User表

1,新建auth类
2,新建user 和member模型类
3,调用auth类(auth类调用user)
一,\woo\helper\AuthHxf.php
<?php
namespace woo\helper;
class AuthHxf {
// 用户模型名称比如User
public $userModel = ‘UserHxf’;
protected $connection = ‘db_**’;
private $userModelObject = NULL;
// 登录地址
public $loginAction = ‘’;
// 登出以后跳转地址在这里插入代码片
public $logoutRedirect = ‘’;
// 登录以后跳转地址
public $loginRedirect = ‘’;
// 登录帐号字段
public $userField = ‘username’;
// 登录密码字段
public $pwdField = ‘password’;
// 关联查询模型
public $contain = [];
private $allowMethod = [];
// 登录用户session名
private $authKey;
private $authDefaultKey;
private $request = [];
public function __construct()
{
$addon = parse_name(request()->param(‘addon’));
$controller = parse_name(request()->param(‘control’));
a c t i o n = s t r t o l o w e r ( r e q u e s t ( ) > p a r a m ( a c t i o n ) ) ; i f ( ! e m p t y ( action = strtolower(request()->param('action')); if (!empty( addon) && !empty(KaTeX parse error: Expected 'EOF', got '&' at position 13: controller) &̲& !empty(action)) {
$this->request[‘addon’] = $addon;
$this->request[‘controller’] = $controller;
$this->request[‘action’] = $action;
$this->request[‘is_addon’] = true;
$this->request[‘module’] = ‘addon’;
} else {
$this->request[‘module’] = request()->module();
$this->request[‘controller’] = request()->controller();
$this->request[‘action’] = request()->action();
$this->request[‘is_addon’] = false;
}
$this->authDefaultKey = config(‘auth.default_name’);
$module = $this->request[‘module’];
if (config(‘auth.’ . $module . ‘_name’)) {
$this->authKey = config(‘auth.’ . $module . ‘_name’);
} else {
$this->authKey = config(‘auth.default_name’);
}
t h i s > a u t h D e f a u l t K e y = m d 5 ( this->authDefaultKey = md5( this->authDefaultKey ? $this->authDefaultKey : ‘default’);
t h i s > a u t h K e y = m d 5 ( this->authKey = md5( this->authKey ? $this->authKey : KaTeX parse error: Expected 'EOF', got '}' at position 28: …faultKey); }̲ // Auth获取…this->userModelObject) {
return;
}
if (!$this->userModel) {
exit(‘请设置Auth::userModel’);
}
t h i s > u s e r M o d e l O b j e c t = m o d e l ( this->userModelObject = model( this->userModel);
}
// Auth登录
public function login(KaTeX parse error: Expected '}', got 'EOF' at end of input: …if(session('?'.this->authKey)) redirect($this->loginRedirect);
t h i s > g e t U s e r O b j ( ) ; i f ( e m p t y ( this->getUserObj(); if (empty( data)) {
KaTeX parse error: Expected 'EOF', got '}' at position 32: …st.'); }̲ if (is…data[‘data’])) {
$data = $data[‘data’];
}
d a t a = i s s e t ( data = isset( data[$this->userModel]) ? d a t a [ data[ this->userModel] : d a t a ; i f ( ! i s a r r a y ( data; if (!is_array( data)) {
return false;
}
if (!trim( d a t a [ data[ this->userField]) || !trim( d a t a [ data[ this->pwdField])) {
return false;
}
u s e r n a m e = a d d s l a s h e s ( t r i m ( username = addslashes(trim( data[$this->userField]));
p a s s w o r d = s e l f : : p a s s w o r d ( t r i m ( password = self::password(trim( data[$this->pwdField]));
$login = t h i s > u s e r M o d e l O b j e c t > w i t h ( this->userModelObject->with( this->contain)->where([[$this->userField, ‘=’, u s e r n a m e ] , [ username], [ this->pwdField, ‘=’, p a s s w o r d ] ] ) > f i n d ( ) ; i f ( ! password]])->find(); if (! login) {
return false;
}
$login = l o g i n > t o A r r a y ( ) ; i f ( i s s e t ( login->toArray(); if (isset( login[‘logined_session_id’])) {
KaTeX parse error: Expected 'EOF', got '}' at position 53: …_id(); }̲ if (is…login[‘logined_ip’])) {
KaTeX parse error: Expected 'EOF', got '}' at position 48: …>ip(); }̲ if (is…login[‘logined’])) {
KaTeX parse error: Expected 'EOF', got '}' at position 49: …i:s'); }̲ sessio…this->authKey, $login);
if (!session(’?’ . KaTeX parse error: Expected '}', got 'EOF' at end of input: … session(this->authDefaultKey, KaTeX parse error: Expected 'EOF', got '}' at position 17: …ogin); }̲ sessio…data = array())
{
$this->getUserObj();
u s e r n a m e = a d d s l a s h e s ( t r i m ( username = addslashes(trim( data[$this->userField]));
$login = t h i s > u s e r M o d e l O b j e c t > w i t h ( this->userModelObject->with( this->contain)->where([[$this->userField, ‘=’, u s e r n a m e ] ] ) > f i n d ( ) ; i f ( ! username] ])->find(); if (! login) {
return false;
}
$login = l o g i n > t o A r r a y ( ) ; i f ( i s s e t ( login->toArray(); if (isset( login[‘logined_session_id’])) {
KaTeX parse error: Expected 'EOF', got '}' at position 53: …_id(); }̲ if (is…login[‘logined_ip’])) {
KaTeX parse error: Expected 'EOF', got '}' at position 48: …>ip(); }̲ if (is…login[‘logined’])) {
KaTeX parse error: Expected 'EOF', got '}' at position 49: …i:s'); }̲ sessio…this->authKey, $login);
if (!session(’?’ . KaTeX parse error: Expected '}', got 'EOF' at end of input: … session(this->authDefaultKey, $login);
}
session(‘REFERER’, null);
return true;
}
// Auth登录后更新用户信息并重写session
public function relogin()
{
if (!session(’?’ . $this->authKey)) {
return false;
}
$this->getUserObj();
$login = t h i s > u s e r M o d e l O b j e c t > w i t h ( this->userModelObject->with( this->contain)->where(‘id’, t h i s > u s e r ( i d ) ) > f i n d ( ) ; i f ( ! this->user('id'))->find(); if (! login) {
$this->logout();
return false;
}
$login = l o g i n > t o A r r a y ( ) ; / / u n s e t ( login->toArray(); //unset( login[ t h i s > p w d F i e l d ] ) ; s e s s i o n ( this->pwdField]); session( this->authKey, $login);
d e f a u l t = s e s s i o n ( default = session( this->authDefaultKey);
if ($default[‘id’] == KaTeX parse error: Expected '}', got 'EOF' at end of input: … session(this->authDefaultKey, $login);
}
return true;
}
// Auth登出
public function logout()
{
l o g i n = s e s s i o n ( login = session( this->authKey);
d e f a u l t = s e s s i o n ( default = session( this->authDefaultKey);
if ($login[‘id’] == KaTeX parse error: Expected '}', got 'EOF' at end of input: … session(this->authDefaultKey, NULL);
}
session(KaTeX parse error: Expected 'EOF', got '}' at position 27: …ey, NULL); }̲ // Auth获取…key = NULL)
{
if (!session(’?’ . $this->authKey)) {
return false;
}
l o g i n = s e s s i o n ( login = session( this->authKey);
if (!$key) {
return KaTeX parse error: Expected 'EOF', got '}' at position 16: login; }̲ if (in…key, array_keys($login))) {
return l o g i n [ login[ key];
}
return KaTeX parse error: Expected 'EOF', got '}' at position 12: login; }̲ // Auth可访…method = NULL)
{
a r g s = f u n c g e t a r g s ( ) ; i f ( e m p t y ( args = func_get_args(); if (empty( args)) {
t h i s > a l l o w M e t h o d = g e t c l a s s m e t h o d s ( this->allowMethod = get_class_methods( GLOBALS[‘controller’]);
return;
}
if (!is_array($method)) {
m e t h o d = a r r a y ( method = array( method);
}
$this->allowMethod += KaTeX parse error: Expected 'EOF', got '}' at position 13: method; }̲ // Auth不可…method = NULL)
{
a r g s = f u n c g e t a r g s ( ) ; i f ( e m p t y ( args = func_get_args(); if (empty( args)) {
KaTeX parse error: Expected 'EOF', got '}' at position 58: …eturn; }̲ if (!i…method)) {
m e t h o d = a r r a y ( method = array( method);
}
t h i s > a l l o w M e t h o d = a r r a y d i f f ( this->allowMethod = array_diff( this->allowMethod, $method);
}
// 检查是否登录
public function check()
{
if (!session(’?’ . KaTeX parse error: Expected 'EOF', got '&' at position 16: this->authKey) &̲& !in_array(this->request[‘action’], $this->allowMethod)) {
session(‘REFERER’, request()->url(true));
return false;
}
return true;
}
// 检查是否登录
public function checkloged()
{
if (!session(’?’ . $this->authKey)) {
return false;
}
return true;
}
public function getPowerList()
{
$powerModel = model(‘Power’);
$powerTeeModel = model(‘PowerTree’);
$user_id = $this->user(‘id’);
$user_group_id = $this->user(‘user_group_id’);
$powers = p o w e r M o d e l > w h e r e ( [ [ f o r e i g n i d , = , i n t v a l ( powerModel->where([['foreign_id', '=', intval( user_id)], [‘type’, ‘=’, ‘user’]])->find();
if ($powers) {
p o w e r s = u n s e r i a l i z e ( @ g z u n c o m p r e s s ( powers = unserialize(@gzuncompress( powers[‘content’]));
} else {
$powers = p o w e r M o d e l > w h e r e ( [ [ f o r e i g n i d , = , i n t v a l ( powerModel->where([['foreign_id', '=', intval( user_group_id)], [‘type’, ‘=’, ‘usergroup’]])->find();
if ($powers) {
p o w e r s = u n s e r i a l i z e ( @ g z u n c o m p r e s s ( powers = unserialize(@gzuncompress( powers[‘content’]));
} else {
$powers = [];
}
}
return $powers;
}
public function checkPower()
{
t o g e t h e r = s t r t o l o w e r ( together = strtolower( GLOBALS[‘controller’]->params[‘controller’]) . ‘::’ . strtolower($GLOBALS[‘controller’]->params[‘action’]);
p o w e r T e e M o d e l = m o d e l ( P o w e r T r e e ) ; i f ( powerTeeModel = model('PowerTree'); if ( powerTeeModel->where(‘together’, $together)->count()) {
$powers = t h i s > g e t P o w e r L i s t ( ) ; i f ( i n a r r a y ( a l l : : a l l , ( a r r a y ) this->getPowerList(); if (in_array('all::all', (array) powers)) {
return true;
}
return in_array( t o g e t h e r , ( a r r a y ) together, (array) powers);
}
return true;
}
// 密码加密,返回密码
public static function password(KaTeX parse error: Expected '}', got 'EOF' at end of input: …turn md5(crypt(password, config(‘auth.salt’) . substr($password, 0, 2)));
}
public function __destruct()
{
if (request()->isGet() && !request()->isAjax()) {
session(‘last_url’, request()->url(true));
}
} }

二,引用Auth 类
\app\home\controller\Index.php

<?php
namespace app\home\controller;
use app\common\controller\Home;
use think\facade\Cookie;
use think\Db;
use think\facade\Config;
use think\validate\ValidateRule;
use woo\helper\AuthHxf;
class Index extends Home
{
protected $db_config = 'db
’;
public function initialize()
{
call_user_func(array(‘parent’, FUNCTION));
}
}*

*数据库配置
\data\config\database.php

<?php
return array (
‘type’ => ‘mysql’,
‘hostname’ => ‘127.0.0.1’,
‘username’ => ‘root’,
‘password’ => ‘root’,
‘hostport’ => ‘3306’,
‘charset’ => ‘utf8’,
‘database’ => '
’,
‘prefix’ => ‘fa_’,
//数据库配置知识全库
'db_
’ => [
‘type’ => ‘mysql’,
‘hostname’ => ‘127.0.0.1’,
‘username’ => ‘root’,
‘password’ => ‘root’,
‘charset’ => ‘utf8’,
‘database’ => '
*’,
‘prefix’ => ‘zf_’,
],
//数据库配置知识全库
‘db_fqa_base’ => [
‘type’ => ‘mysql’,
‘hostname’ => ‘127.0.0.1’,
‘database’ => '’,
‘username’ => ‘root’,
// ‘password’ => ‘mysql’,.
‘password’ => ‘root’,
‘password’ => ‘root’,
‘charset’ => ‘utf8’,
‘prefix’ => ‘zf_’,
],
)

?>*

三,新建模型类user 和member类
\app\common\model\UserHxf.php

<?php
namespace app\common\model;
use woo\helper\AuthHxf;
class UserHxf extends App
{
public $display = ‘username’;
protected $table = ‘zf_user’;
protected $connection = 'db_
’;
public $assoc = array(
‘UserGroup’ => array(
‘type’ => ‘belongsTo’
),
‘UserGrade’ => array(
‘type’ => ‘belongsTo’
),
‘Member’ => array(
‘type’ => ‘hasOne’,
‘deleteWith’ => true,
),
‘UserLogin’ => ‘hasMany’
);
public function initialize()
{
$this->form = array(
‘id’ => array(
‘type’ => ‘integer’,
‘name’ => ‘ID’,
‘elem’ => ‘hidden’,
),
‘username’ => array(
‘type’ => ‘string’,
‘name’ => ‘用户名’,
‘elem’ => ‘text’
),
‘password’ => array(
‘type’ => ‘string’,
‘name’ => ‘密码’,
‘elem’ => ‘password’,
‘list’ => ‘password’
),
‘user_group_id’ => array(
‘type’ => ‘integer’,
‘name’ => ‘用户组’,
‘elem’ => ‘assoc_select’,
‘list’ => ‘assoc’,
‘foreign’ => ‘UserGroup.title’,
‘prepare’ => ‘select’
),
‘user_grade_id’ => array(
‘type’ => ‘integer’,
‘name’ => ‘用户等级’,
‘elem’ => ‘format’,
‘list’ => ‘assoc’,
‘foreign’ => ‘UserGrade.title’
),
‘status’ => array(
‘type’ => ‘string’,
‘name’ => ‘状态’,
‘elem’ => ‘radio’,
‘options’ => array(
‘verified’ => ‘正常’,
‘unverified’ => ‘未激活’,
‘banned’ => ‘已禁用’
),
‘list’ => ‘options’,
),
‘email’ => array(
‘type’ => ‘string’,
‘name’ => ‘认证邮箱’,
‘elem’ => ‘text’,
‘list’ => ‘show’
),
‘user_score_sum’ => array(
‘type’ => ‘float’,
‘name’ => ‘积分’,
‘elem’ => 0,
‘list’ => ‘show’
),
‘logined’ => array(
‘type’ => ‘datetime’,
‘name’ => ‘最后登录时间’,
‘elem’ => 0,
‘list’ => ‘datetime’
),
‘logined_ip’ => array(
‘type’ => ‘string’,
‘name’ => ‘最后登录IP’,
‘elem’ => 0
),
‘logined_session_id’ => array(
‘type’ => ‘string’,
‘name’ => ‘最后登录SESSION_ID’,
‘elem’ => 0
),
‘created’ => array(
‘type’ => ‘datetime’,
‘name’ => ‘注册时间’,
‘elem’ => 0,
‘list’ => ‘datetime’
)
);
call_user_func(array(‘parent’, FUNCTION));
}
##当前类验证规则
protected $validate = array(
‘username’ => array(
‘rule’ => array(‘unique’, ‘user’)
),
‘password’ => array(
array(
‘rule’ => ‘require’,
‘on’ => ‘add’
),
array(
‘rule’ => array(‘length’, 4, 16)
)
),
‘email’=>array(
‘allowEmpty’ => true,
‘rule’ => ‘email’
),
‘user_group_id’ => array(
‘rule’ => array(‘egt’, 1),
‘message’ => ‘请选择用户组’
),
‘status’ => array(
‘rule’ => ‘require’
),
);
public function beforeInsertCall()
{
KaTeX parse error: Expected group after '_' at position 39: …rray('parent', _̲_FUNCTION__)); …this[‘password’]) && t h i s [ p a s s w o r d ] = = = ) u n s e t ( this['password'] === '') unset( this[‘password’]);
if (isset($this[‘password’])) t h i s [ p a s s w o r d ] = A u t h H x f : : p a s s w o r d ( this['password'] = AuthHxf::password( this[‘password’]);
return $rslt;
}
public function beforeUpdateCall()
{
KaTeX parse error: Expected group after '_' at position 39: …rray('parent', _̲_FUNCTION__)); …this[‘password’]) && t h i s [ p a s s w o r d ] = = = ) u n s e t ( this['password'] === '') unset( this[‘password’]);
if (isset($this[‘password’])) t h i s [ p a s s w o r d ] = A u t h H x f : : p a s s w o r d ( this['password'] = AuthHxf::password( this[‘password’]);
return $rslt;
}
public function afterInsertCall()
{
$rslt = call_user_func(array(‘parent’, FUNCTION));
$data[‘user_id’] = $this[‘id’];
$data[‘nickname’] = ‘’;
$memberModel = model(‘MemberHxf’);
$memberModel->data([]);
m e m b e r M o d e l > i s V a l i d a t e ( f a l s e ) > i s U p d a t e ( f a l s e ) > s a v e ( memberModel->isValidate(false)->isUpdate(false)->save( data);
return $rslt;
}
public function afterUpdateCall()
{
$rslt = call_user_func(array(‘parent’, FUNCTION));
$this->checkUserGrade();
return KaTeX parse error: Expected 'EOF', got '}' at position 11: rslt; }̲ protected …this->oldData[‘user_score_sum’]) || !isset( t h i s [ u s e r s c o r e s u m ] ) ! i s s e t ( this['user_score_sum']) || !isset( this[‘id’])) {
return;
}
// 积分有改变
if ($this->oldData[‘user_score_sum’] != $this[‘user_score_sum’]) {
$gradeModel = model(‘UserGrade’);
$grade = $gradeModel
->where([
[‘min’, ‘<=’, $this[‘user_score_sum’]],
[‘max’, ‘>’, t h i s [ u s e r s c o r e s u m ] ] ] ) > f i n d ( ) ; i f ( this['user_score_sum']] ]) ->find(); if ( grade) {
$gradeId = $grade[‘id’];
o l d G r a d e I d = i s s e t ( oldGradeId = isset( this[‘user_grade_id’]) ? $this[‘user_grade_id’] : $this->where(‘id’, ‘=’, t h i s [ i d ] ) > v a l u e ( u s e r g r a d e i d ) ; i f ( this['id'])->value('user_grade_id'); if ( oldGradeId != $gradeId) {
$this->isValidate(false)->where(‘id’, ‘=’, $this[‘id’])->setField(‘user_grade_id’, g r a d e I d ) ; / / gradeId); // this->isValidate(false)->allowField([‘id’, ‘user_grade_id’])->save([‘user_grade_id’ => $gradeId], [‘id’ => $this[‘id’]]);
}
}
}
}
}*

\app\common\model\MemberHxf.php

<?php
namespace app\common\model;
class MemberHxf extends App
{
//关联模型
public $parentModel = ‘UserHxf’;
protected $table = ‘zf_member’;
protected $connection = 'db_
’;
public $assoc = [
‘User’ => ‘belongsTo’
];
public function initialize()
{
$this->form = [
‘id’ => [
‘type’ => ‘integer’,
‘name’ => ‘ID’,
‘elem’ => ‘hidden’,
],
‘user_id’ => array(
‘type’ => ‘integer’,
‘name’ => ‘所属用户’,
‘foreign’ => ‘User.username’,
‘elem’ => ‘format’,
‘list’ => ‘assoc’
),
‘nickname’ => array(
‘type’ => ‘string’,
‘name’ => ‘昵称’,
‘elem’ => ‘text’,
‘list’ => ‘show’,
),
‘truename’ => array(
‘type’ => ‘string’,
‘name’ => ‘真实姓名’,
‘elem’ => ‘text’,
‘list’ => ‘show’,
),
‘headimg’ => array(
‘type’ => ‘string’,
‘name’ => ‘头像’,
‘elem’ => ‘image.upload’,
‘list’ => ‘image’,
‘upload’ => array(
‘maxSize’ => 512,
‘validExt’ => array(‘jpg’, ‘png’, ‘gif’)
)
),
‘sex’ => array(
‘type’ => ‘string’,
‘name’ => ‘性别’,
‘elem’ => ‘radio’,
‘options’ => [‘m’ => ‘男’, ‘f’ => ‘女’, ‘x’ => ‘保密’]
),
‘mobile’ => array(
‘type’ => ‘string’,
‘name’ => ‘手机号码’,
‘elem’ => ‘text’,
‘list’ => ‘show’,
),
‘region’ => array(
‘type’ => ‘none’,
‘name’ => ‘所在地区’,
‘elem’ => ‘multi_select.ajax’,
‘multi_field’ => [
‘province’ => ‘省’,
‘city’ => ‘市’,
‘area’ => ‘区’,
],
‘multi_options’ => [
‘order’ => [‘list_order’ => ‘DESC’,‘id’ => ‘ASC’],
‘where’ => []
],
‘foreign’ => ‘Region.title’,
‘list’ => ‘assoc’
),
‘province’ => array(
‘type’ => ‘integer’,
‘name’ => ‘省’,
‘elem’ => 0
),
‘city’ => array(
‘type’ => ‘integer’,
‘name’ => ‘市’,
‘elem’ => 0
),
‘area’ => array(
‘type’ => ‘integer’,
‘name’ => ‘区’,
‘elem’ => 0
),
‘address1111’ => array(
‘type’ => ‘string’,
‘name’ => ‘联系地址’,
‘elem’ => ‘text’,
‘list’ => ‘show’,
),
];
call_user_func_array([‘parent’, FUNCTION], func_get_args());
}
//数据验证
protected v a l i d a t e = [ ] ; p u b l i c f u n c t i o n g e t B y U s e r ( validate = []; public function getByUser( user_id)
{
$member = t h i s > w h e r e ( u s e r i d , = , i n t v a l ( this->where('user_id', '=', intval( user_id))->fetchSql(true)->find();
echo m e m b e r ; i f ( e m p t y ( member; if (empty( member)) {
$userModel = model(‘UserHxf’);
$user = u s e r M o d e l > g e t ( i n t v a l ( userModel->get(intval( user_id));
if (empty($user)) {
return false;
}
d a t a [ u s e r i d ] = i n t v a l ( data['user_id'] = intval( user_id);
$data[‘nickname’] = ‘’;
t h i s > i s V a l i d a t e ( f a l s e ) > c r e a t e D a t a ( this->isValidate(false)->createData( data);
$member = $this;
}
return $member;
}
}*

发布了58 篇原创文章 · 获赞 0 · 访问量 2761

猜你喜欢

转载自blog.csdn.net/qq_30439399/article/details/103321383