相关知识
准备工作
模拟枚举类
applicationlibenumScopeEnum
class ScopeEnum
{
const User = 16;
// 是给CMS(管理员)准备的权限
const Super = 32;
}
applicationapiserviceUserToken.php
-$cachedValue['scope'] = 16;
+$cachedValue['scope'] = ScopeEnum::User;
异常处理
applicationlibexceptionForbiddenException
<?php
namespace applibexception;
/**
* token验证失败时抛出此异常
*/
class ForbiddenException extends BaseException
{
public $code = 403;
public $msg = '权限不够';
public $errorCode = 10001;
}
Address控制器
applicationapicontrollerv1Address.php
class Address extends BaseController
{
protected $beforeActionList = [
'checkPrimaryScope' => ['only' => 'createOrUpdateAddress']
]
}
BaseController控制器
applicationapicontrollerv1BaseController.php
class BaseController extends Controller
{
protected function checkPrimaryScope()
{
TokenService::needPrimaryScope();
}
protected function checkExclusiveScope()
{
TokenService::needExclusiveScope();
}
Token服务层
applicationapiserviceToken.php
class Token
{
// 用户和CMS管理员都能访问的接口权限
public static function needExclusiveScope()
{
$scope = self::getCurrentTokenVar('scope');
if ($scope) {
if ($scope >= ScopeEnum::User){
return true;
} else {
throw new ForbiddenException();
}
} else {
throw new TokenException();
}
}
// 只有用户才能访问的接口权限
public static function needPrimaryScope()
{
$scope = self::getCurrentTokenVar('scope');
if ($scope){
if ($scope == ScopeEnum::User){
return true;
} else {
throw new ForbiddenException();
}
} else {
throw new TokenException();
}
}
}