全棧微信小程式商城 學習筆記10.1 對更新收貨地址介面做許可權控制
阿新 • • 發佈:2021-09-01
相關知識
準備工作
模擬列舉類
application\lib\enum\ScopeEnum
class ScopeEnum
{
const User = 16;
// 是給CMS(管理員)準備的許可權
const Super = 32;
}
application\api\service\UserToken.php
-$cachedValue['scope'] = 16;
+$cachedValue['scope'] = ScopeEnum::User;
異常處理
application\lib\exception\ForbiddenException
<?php
namespace app\lib\exception;
/**
* token驗證失敗時丟擲此異常
*/
class ForbiddenException extends BaseException
{
public $code = 403;
public $msg = '許可權不夠';
public $errorCode = 10001;
}
Address控制器
application\api\controller\v1\Address.php
class Address extends BaseController { protected $beforeActionList = [ 'checkPrimaryScope' => ['only' => 'createOrUpdateAddress'] ] }
BaseController控制器
application\api\controller\v1\BaseController.php
class BaseController extends Controller { protected function checkPrimaryScope() { TokenService::needPrimaryScope(); } protected function checkExclusiveScope() { TokenService::needExclusiveScope(); } }
Token服務層
application\api\service\Token.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();
}
}
}