1 <?php
2 3 4 5 6 7
8 namespace Cross\Auth;
9
10 use Cross\Core\Helper;
11 use Cross\I\HttpAuthInterface;
12
13 14 15 16 17
18 class CookieAuth implements HttpAuthInterface
19 {
20 21 22 23 24
25 private $key = '!wl<@>c(r#%o*s&s';
26
27 function __construct($key = '')
28 {
29 if ($key) {
30 $this->key = $key;
31 }
32 }
33
34 35 36 37 38 39 40 41
42 function set($name, $params, $expire = 0)
43 {
44 if ($params === '' || $params === null) {
45 $expire = time() - 3600;
46 $value = null;
47 } else {
48 $encryptKey = $this->getEncryptKey($name);
49 if (is_array($params)) {
50 $params = json_encode($params);
51 }
52 $value = Helper::authCode($params, 'ENCODE', $encryptKey);
53 if ($expire > 0) {
54 $expire = time() + $expire;
55 }
56 }
57
58 $cookie_domain = null;
59 if (defined('COOKIE_DOMAIN')) {
60 $cookie_domain = COOKIE_DOMAIN;
61 }
62
63 if (setcookie($name, $value, $expire, '/', $cookie_domain, null, true)) {
64 return true;
65 }
66
67 return false;
68 }
69
70 71 72 73 74 75 76
77 function get($params, $deCode = false)
78 {
79 if (false !== strpos($params, ':') && $deCode) {
80 list($name, $arrKey) = explode(':', $params);
81 } else {
82 $name = $params;
83 }
84
85 if (!isset($_COOKIE[$name])) {
86 return false;
87 }
88
89 $value = $_COOKIE[$name];
90 $encryptKey = $this->getEncryptKey($name);
91 $result = Helper::authCode($value, 'DECODE', $encryptKey);
92 if (!$result) {
93 return false;
94 }
95
96 if ($deCode) {
97 $result = json_decode($result, true);
98 if (isset($arrKey) && isset($result[$arrKey])) {
99 return $result[$arrKey];
100 }
101 }
102
103 return $result;
104 }
105
106 107 108 109 110 111
112 protected function getEncryptKey($cookieName)
113 {
114 if (isset($_SERVER['HTTP_USER_AGENT'])) {
115 $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
116 } else {
117 $agent = 'agent';
118 }
119
120 return md5($agent . $this->key . $cookieName);
121 }
122 }
123