ActiveController.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace oauth2\controllers;
  3. use Yii;
  4. use yii\filters\Cors;
  5. use yii\web\BadRequestHttpException;
  6. use oauth2\behaviors\JWTAuth;
  7. use common\traits\BaseAction;
  8. use common\behaviors\HttpSignAuth;
  9. /**
  10. * Class ActiveController
  11. * @package oauth2\controllers
  12. * @author jianyan74 <751393839@qq.com>
  13. */
  14. class ActiveController extends \yii\rest\ActiveController
  15. {
  16. use BaseAction;
  17. /**
  18. * 不用进行登录验证的方法
  19. * 例如: ['index', 'update', 'create', 'view', 'delete']
  20. * 默认全部需要验证
  21. *
  22. * @var array
  23. */
  24. protected $authOptional = [];
  25. /**
  26. * 不用进行签名验证的方法
  27. * 例如: ['index', 'update', 'create', 'view', 'delete']
  28. * 默认全部需要验证
  29. *
  30. * @var array
  31. */
  32. protected $signOptional = [];
  33. /**
  34. * 行为验证
  35. *
  36. * @return array
  37. */
  38. public function behaviors()
  39. {
  40. $behaviors = parent::behaviors();
  41. // 进行签名验证
  42. if (Yii::$app->params['user.httpSignValidity'] == true) {
  43. $behaviors['signTokenValidate'] = [
  44. 'class' => HttpSignAuth::class,
  45. 'optional' => $this->signOptional, // 不进行认证判断方法
  46. ];
  47. }
  48. // 授权验证
  49. $behaviors['jwtAuth'] = [
  50. 'class' => JWTAuth::class,
  51. // 不进行认证判断方法
  52. 'optional' => $this->authOptional,
  53. ];
  54. return $behaviors;
  55. }
  56. /**
  57. * @param $action
  58. * @return bool
  59. * @throws BadRequestHttpException
  60. * @throws \yii\web\ForbiddenHttpException
  61. */
  62. public function beforeAction($action)
  63. {
  64. if (!parent::beforeAction($action)) {
  65. return false;
  66. }
  67. // 权限方法检查,如果用了rbac,请注释掉
  68. $this->checkAccess($action->id, $this->modelClass, Yii::$app->request->get());
  69. // 每页数量
  70. $this->pageSize = Yii::$app->request->get('per-page', 10);
  71. $this->pageSize > 50 && $this->pageSize = 50;
  72. return true;
  73. }
  74. /**
  75. * 权限验证
  76. *
  77. * @param string $action 当前的方法
  78. * @param null $model 当前的模型类
  79. * @param array $params $_GET变量
  80. * @throws \yii\web\BadRequestHttpException
  81. */
  82. public function checkAccess($action, $model = null, $params = [])
  83. {
  84. // 方法名称
  85. if (in_array($action, ['update', 'create', 'delete'])) {
  86. throw new \yii\web\BadRequestHttpException('您的权限不足,如需要请联系管理员');
  87. }
  88. }
  89. }
粤ICP备19079148号