Fastadmin后台单点登录

FastAdmin框架有单点登录的配置,然好像不起什么作用,所以自己实现了一个。

原理:记录用户ID、用户名与session_id的对应关系,发生改变时,即视为重新登录,此时重新绑定关系,老的关系失效,强制清空session.

数据结构

CREATE TABLE `fa_session_log` (
  `id` int NOT NULL AUTO_INCREMENT,
  `user_id` int DEFAULT '0' COMMENT '用户ID',
  `user_name` varbinary(30) DEFAULT '' COMMENT '用户名',
  `session_id` varchar(100) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT 'SESSION ID',
  `create_time` int DEFAULT '0' COMMENT '添加时间',
  `update_time` int DEFAULT '0' COMMENT '更新时间',
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`) USING BTREE,
  KEY `session_id` (`session_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='SESSION LOG';

登录时session处理

application/admin/library/Auth.phplogin方法,大约第64行添加:

//session log处理
$session_id = session_id();
$user_id = $admin->id;
$user_name = $admin->username;
$session_log = db('session_log')->where(['user_id' => $user_id])->find();
if($session_log){
    $data = [
        'session_id' => $session_id,
        'update_time' => time()
    ];
    db('session_log')->where(['user_id' => $user_id])->update($data);
}else{
    $data = [
        'user_id' => $user_id,
        'user_name' => $user_name,
        'session_id' => $session_id,
        'create_time' => time(),
        'update_time' => 0
    ];
    db('session_log')->insertGetId($data);
}

后台操作判断

application/common/controller/Backend.php_initialize方法,约第166行添加:

//单点登录判断
$auth = Auth::instance();
if($auth->isLogin()){
    $user_id = $auth->isLogin() ? $auth->id : 0;
    $user_name = $auth->isLogin() ? $auth->username : __('Unknown');

    $session_id = session_id();
    $session_log = db('session_log')->where(['session_id' => $session_id])->find();
    if(!$session_log){
        session(null);
        $this->error("登录失效1,请重新登录", url('index/login'));
    }

    $session_log = db('session_log')->where(['user_id' => $user_id])->find();
    if(! $session_log || $session_log['session_id'] != $session_id || $session_log['user_name'] != $user_name){
        session(null);
        $this->error("登录失效2,请重新登录", url('index/login'));
    }
}

Leave a Comment

豫ICP备19001387号-1