准备:
前提:上回我们通过获取到 用户openid 将用户信息写入缓存 ,然后将 $key(Token) 返回给客户端小程序;
缓存内容如下:scope即表示用户的权限值(值越大代表权限越大)
{"session_key":"XoG******3Oxg==","expires_in":7200,"openid":"oPPr8*******yGGh5k","uid":1,"scope":16}";
思路:
用户进行敏感操作时,通过客户端传递的token,找到该用户的scope值,判断用户scope是否大于或等于 该操作的权限;
protected function checkPrimaryScope()
{
$scope = $this->getCurrentTokenVar('scope');
if ($scope){
if ($scope>=ScopeEnum::User){
return true; //若大于等于则可以操作
}else{
throw new ForbiddenException();
}
}else{
throw new TokenException();
}
}
//从cache中读取并返回用户所需要的键值
public static function getCurrentTokenVar($key)
{
$token = Request::instance()->header('token');
$vars = Cache::get($token);//token即为键值
if (!$vars){
throw new TokenException();
}else{
if (!is_array($vars)){ //如果用redis,则直接就是数组了。不需要进行json_decode
$vars = json_decode($vars,true);
}
//$vars 内容为 ['session_key','openid'=>'**','uid'=>1111,'expires_in'=>7200,'scope'=>16]
if (array_key_exists($key,$vars)){
return $vars[$key];
}else{
throw new Exception('尝试获取的Token变量不存在');
}
}
}
注:
ScopeEnum::User
ScopeEnum::Super
自己定义的权限级别
class ScopeEnum
{
const User = 16;
const Super = 32;
}
在写入缓存时:
[session_key] => /+Xq*****Xz/zzjA==
[expires_in] => 7200
[openid] => oPPr80M******umQ5g86*****k
[scope] => ScopeEnum::User
[uid] => $uid