1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?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($ip='192.168.1.222',$port=6379){
if($this->instence === null){
$redis = new \Redis();
$res = $redis->connect($ip,$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),3600);
}
}
}