ThinkPHP5开发技巧:实现登录校验次数,超过次数冻结用户
整体思路:
1、新建一个数据表,记录登录情况,(网上好多正确登录也记录了,我觉得没必要,只记录错误记录就可以)
2、每次登录校验的时候查询校验错误次数
3、在登录错误的时候插入错误记录
4、以上校验过程是隶属同一个ip,是同一个ip操作下的,也可根据情况去掉
具体代码如下:
DROP TABLE IF EXISTS `rs_user_login_info`; CREATE TABLE `rs_user_login_info` ( `id` int unsigned NOT NULL AUTO_INCREMENT, `uid` int unsigned NOT NULL , `ipaddr` varchar (15) NOT NULL COMMENT '用户登陆IP' , `logintime` int NOT NULL COMMENT '用户登陆时间' , PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; |
/** * 登陆动作 */ public function doLogin(){ $account = request()->post( 'account' , '' ); $password = request()->post( 'password' , '' ); if ( $account == '' ){ $this ->error( '请输入账号' ); } if ( $password == '' ){ $this ->error( '请输入密码' ); } //实例化MODEL $user_mod = new model\Admin() $userLoginInfo_mod = new model\UserLoginInfo(); $where = [ 'account' => $account , 'status' => 1, ]; $userInfo = $user_mod ->where( $where )->find(); if (! $userInfo ){ $this ->error( '账号或密码错误' ); } $wrongRel = $this ->checkPassWrongTime( $userInfo [ 'id' ]); if (! $wrongRel ){ $this ->error( '1小时错误密码输入超过10次,禁用用户1小时' ); } if ( $userInfo [ 'password' ] != $password ){ //登录错误记录 $wrongData [ 'ipaddr' ] = request()->ip(); $wrongData [ 'uid' ] = $userInfo [ 'id' ]; $wrongData [ 'logintime' ] = time(); $userLoginInfo_mod ->save( $wrongData ); $this ->error( '账号或密码错误' ); } //更新最后登陆时间 $userInfo ->isUpdate(true)->save( [ 'last_login_time' => time(), 'last_login_ip' => request()->ip() ], [ 'id' => $userInfo [ 'id' ] ] ) unset( $userInfo [ 'password' ]); unset( $userInfo [ 'status' ]); unset( $userInfo [ 'last_login_time' ]); unset( $userInfo [ 'last_login_ip' ]) session( 'adminInfo' , $userInfo ) $this ->redirect( 'index/index' ); } /** * Notes:检查近一个小时内同ip下输入密码错误次数(大于10次返回错误) * User: Wendy_33 * Time: 2021/9/9 14:33 */ public function checkPassWrongTime( $uid ){ $userLoginInfo_mod = new model\UserLoginInfo(); $whereMap = array ( 'uid' => $uid , 'ipaddr' => request()->ip(), 'logintime' => array ( '>' , time()-3600), //利用比较标签 ); $count = $userLoginInfo_mod ->where( $whereMap )-> count (); // dump($userLoginInfo_mod->getLastSql()); if ( $count >10){ return false; } else { return true; } } |
THE END