symfony裏實現resfull api並實現權限控制

----------------------------------------------------------

1、restfull api部分

注:筆記,自己摸索出來的,路子野,僅供參考。

----------------------- 歡迎指教交流。。。

<?php
// BaseController.php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class BaseController extends Controller
{
    protected static $method_type = array('get', 'post', 'put', 'patch', 'delete');

	/**
	 * description: 負責restfull api調派
	 * @param {request obj,class||obj,[array],string} 
	 * @return: array
	 */
	public static function restfullDispatch(Request $request,$obj,$params=null,$resouce=null){
		$resouce = $resouce ? $resouce:explode('Action',explode('Controller::',$request->get('_controller'))[1])[0];
		$method = strtolower($request->server->get('REQUEST_METHOD'));
		if (in_array($method, self::$method_type)) {
			//調用請求方式對應的方法
			$method_name = $method . ucfirst($resouce);
			if(!method_exists($obj,$method_name)){
				throw new Exception('The method: '.$method_name.' not exists!');
			}
			return $obj->$method_name($params);
		}
		return false;
	}

}

然後所有controller繼承BaseController,Action調$this::restfullDispatch() 就行了,最後路由可以設置成類似:

get /admin/user

post /admin/user

put /admin/user

patch /admin/user

……

2、權限控制部分

其實也很簡單,由於開始時沒有認真看框架的 事件監聽 部分的文檔,摸索了很久。。。這裏做個記錄。

簡單總結爲以下幾個步驟:

1、securty.yml裏配置好角色繼承關係

security:

    #···

    #分層角色
    role_hierarchy:
        ROLE_ADMIN:          ROLE_USER
        ROLE_SUPER_ADMIN:    ROLE_ADMIN
        ^ROLE_CUSTOM_:       ROLE_USER      #自定義角色需繼承ROLE_USER才能登錄,沒錯可以用正則,棒棒的

2、數據庫裏建立RBAC關係表(這部分基本和別的框架一樣)

數據庫大概是這個樣子:

角色表

權限表表

用戶表裏面有一個role字段,值爲角色表裏的一條記錄的name,就不截圖了

3、監聽kener.controller事件,根據role的驗證權限,根據驗證結果setController

<?php

namespace AppBundle\EventListener;

use Symfony\Component\HttpFoundation\Response;
// use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
// use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

use AppBundle\System\Status;
use AppBundle\Entity\Users;
use AppBundle\Entity\Roles;

/**
 * 偵聽系統的kernel.controller事件,通過actionName實現權限控制
 */
class RunActionListenter
{
    protected $controllerConfig = array('Admin'); //需要進行權限控制的controller
    protected $em;
    protected $tokenStorage;
    protected $result = array(
        'code'   =>    Status::ALL['PERMISSION_DENIED'][0],
        'msg'    =>    Status::ALL['PERMISSION_DENIED'][1],
        'data'   =>    null,
    );

    public function __construct(TokenStorageInterface $tokenStorage,ContainerInterface $container){
        $this->tokenStorage = $tokenStorage;
        $this->em = $container->get('doctrine')->getManager();
    }

    public function onKernelController(FilterControllerEvent $event){
        if(! $event->isMasterRequest()){
            return;
        }
        $request = $event->getRequest();
        $isAjax = $request->isXmlHttpRequest();
        $method = strtolower($request->server->get('REQUEST_METHOD'));

        $controller = explode('Controller::',$request->get('_controller'));
        $controllerName = substr($controller[0],21);

        if(in_array($controllerName,$this->controllerConfig)){
            $user =  $this->tokenStorage->getToken()->getUser();
            //超級管理員只做登錄驗證,此角色可以爲所欲爲,並且不能通過系統的權限管理分配到此角色
            if(! $user->hasRole('ROLE_SUPER_ADMIN')){  
                $actionName = $method.ucfirst(explode('Action',$controller[1])[0]);
                $userRole = $user->getRoles()[0];
                $privileges = $this->em->getRepository(Roles::class)
                ->findOneBy(array('name'=>$userRole))->getPrivileges();
                // $privilegeId = $this->em->getRepository('AppBundle\Entity\privileges')
                // ->findOneBy(array('actionName'=>$actionName))->getId();

                if(!in_array($actionName,$privileges)){
                    $this->result['msg'] = $this->result['msg'].',你當前的職位還需要權限:'.$actionName.'才能繼續訪問,請【聯繫管理員授權】!'; 
                    $controller = $event->getController()[0];
                    $event->setController(function() use ($isAjax){
                        if($isAjax){
                            return new Response(
                                json_encode($this->result,true),
                                200,
                                array('Content-Type' => 'application/json')
                            );  
                        }else{
                            return new Response('<h4>'.$this->result['msg'].'</h4>');
                        }
 
                    });                  
                }
            }
            
        }


    }

}

然後別忘了按照文檔說的在service.yml裏把它寫進去

-----------over。。。

------------------------------------------------------------------------

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章