<?php /** * Created by PhpStorm. * User: chouchou * Date: 2020-3-22 * Time: 19:03 */ namespace app\admin\controller; use app\admin\model\StaffModel; use think\Exception; use think\facade\Cookie; class SingleSign { public $instence = null; public function __construct(){ if($this->instence === null){ $redis = new \Redis(); $res = $redis->connect(config('admin.redis_host'),config('admin.redis_port')); if($res) $this->instence = $redis; else throw new Exception("redis connect faild"); } } //获取session public function getSid($prex = 'PHPREDIS_SESSION:'){ $sid = Cookie::get('PHPSESSID'); $sid = $prex.$sid; $str = $this->instence->get($sid); if(!$str) throw new Exception("session info not found"); return $str; } //从session中读取信息 public function getUserInfo(){ $str = $this->getSid(); $pos = stripos($str,'is_admin|b:') + 11; $isAdmin = substr($str,$pos,1); $user['is_admin'] = $isAdmin; if($user['is_admin'] == true) { $user['username'] = 'gonnadmin'; } else { preg_match('/adminuser\|s\:(\d+)\:/',$str,$match); if($match){ $pos = stripos($str,'adminuser|s:') + strlen('adminuser|s:'); $pos += strlen($match[1]) + 2; $user['username'] = substr($str,$pos,$match[1]+0); } } $pos = stripos($str,'ukey|s:10:') + 11; $ukey = substr($str,$pos,10); $user['ukey'] = $ukey; preg_match('/[\x80-\xff]+/',$str,$matchb); if($matchb) $user['name'] = $matchb[0]; return $user; } //获取userid public function getUserId($user=[]){ if(!$user['is_admin']){ $email = $user['username'].'@gonn.com.cn'; $staff = StaffModel::where(['email'=>$email])->find(); if($staff) return $staff->id; else throw new Exception('user id not found'); } else { return 8; } } //将加密串保存到redis public function saveKey($key,$user=[]){ $encryptKey = substr(md5(config('admin.encrypt_key').$key),0,10); //存储到redis if(!$this->instence->get($encryptKey)){ $this->instence->set($encryptKey,json_encode($user),1800); } } public function clear($prex = 'PHPREDIS_SESSION:'){ $sid = Cookie::get('PHPSESSID'); $sid = $prex.$sid; if($this->instence->set($sid,'')) return true; return false; } }