AuthAccessGateTest.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398
  1. <?php
  2. namespace Illuminate\Tests\Auth;
  3. use Illuminate\Auth\Access\AuthorizationException;
  4. use Illuminate\Auth\Access\Gate;
  5. use Illuminate\Auth\Access\HandlesAuthorization;
  6. use Illuminate\Auth\Access\Response;
  7. use Illuminate\Container\Container;
  8. use InvalidArgumentException;
  9. use PHPUnit\Framework\TestCase;
  10. use stdClass;
  11. class AuthAccessGateTest extends TestCase
  12. {
  13. public function testBasicClosuresCanBeDefined()
  14. {
  15. $gate = $this->getBasicGate();
  16. $gate->define('foo', function ($user) {
  17. return true;
  18. });
  19. $gate->define('bar', function ($user) {
  20. return false;
  21. });
  22. $this->assertTrue($gate->check('foo'));
  23. $this->assertFalse($gate->check('bar'));
  24. }
  25. public function testBeforeCanTakeAnArrayCallbackAsObject()
  26. {
  27. $gate = new Gate(new Container, function () {
  28. //
  29. });
  30. $gate->before([new AccessGateTestBeforeCallback, 'allowEverything']);
  31. $this->assertTrue($gate->check('anything'));
  32. }
  33. public function testBeforeCanTakeAnArrayCallbackAsObjectStatic()
  34. {
  35. $gate = new Gate(new Container, function () {
  36. //
  37. });
  38. $gate->before([new AccessGateTestBeforeCallback, 'allowEverythingStatically']);
  39. $this->assertTrue($gate->check('anything'));
  40. }
  41. public function testBeforeCanTakeAnArrayCallbackWithStaticMethod()
  42. {
  43. $gate = new Gate(new Container, function () {
  44. //
  45. });
  46. $gate->before([AccessGateTestBeforeCallback::class, 'allowEverythingStatically']);
  47. $this->assertTrue($gate->check('anything'));
  48. }
  49. public function testBeforeCanAllowGuests()
  50. {
  51. $gate = new Gate(new Container, function () {
  52. //
  53. });
  54. $gate->before(function (?stdClass $user) {
  55. return true;
  56. });
  57. $this->assertTrue($gate->check('anything'));
  58. }
  59. public function testAfterCanAllowGuests()
  60. {
  61. $gate = new Gate(new Container, function () {
  62. //
  63. });
  64. $gate->after(function (?stdClass $user) {
  65. return true;
  66. });
  67. $this->assertTrue($gate->check('anything'));
  68. }
  69. public function testClosuresCanAllowGuestUsers()
  70. {
  71. $gate = new Gate(new Container, function () {
  72. //
  73. });
  74. $gate->define('foo', function (?stdClass $user) {
  75. return true;
  76. });
  77. $gate->define('bar', function (stdClass $user) {
  78. return false;
  79. });
  80. $this->assertTrue($gate->check('foo'));
  81. $this->assertFalse($gate->check('bar'));
  82. }
  83. public function testPoliciesCanAllowGuests()
  84. {
  85. unset($_SERVER['__laravel.testBefore']);
  86. $gate = new Gate(new Container, function () {
  87. //
  88. });
  89. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyThatAllowsGuests::class);
  90. $this->assertTrue($gate->check('edit', new AccessGateTestDummy));
  91. $this->assertFalse($gate->check('update', new AccessGateTestDummy));
  92. $this->assertTrue($_SERVER['__laravel.testBefore']);
  93. $gate = $this->getBasicGate();
  94. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyThatAllowsGuests::class);
  95. $this->assertTrue($gate->check('edit', new AccessGateTestDummy));
  96. $this->assertTrue($gate->check('update', new AccessGateTestDummy));
  97. unset($_SERVER['__laravel.testBefore']);
  98. }
  99. public function testPolicyBeforeNotCalledWithGuestsIfItDoesntAllowThem()
  100. {
  101. $_SERVER['__laravel.testBefore'] = false;
  102. $gate = new Gate(new Container, function () {
  103. //
  104. });
  105. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyWithNonGuestBefore::class);
  106. $this->assertTrue($gate->check('edit', new AccessGateTestDummy));
  107. $this->assertFalse($gate->check('update', new AccessGateTestDummy));
  108. $this->assertFalse($_SERVER['__laravel.testBefore']);
  109. unset($_SERVER['__laravel.testBefore']);
  110. }
  111. public function testBeforeAndAfterCallbacksCanAllowGuests()
  112. {
  113. $_SERVER['__laravel.gateBefore'] = false;
  114. $_SERVER['__laravel.gateBefore2'] = false;
  115. $_SERVER['__laravel.gateAfter'] = false;
  116. $_SERVER['__laravel.gateAfter2'] = false;
  117. $gate = new Gate(new Container, function () {
  118. //
  119. });
  120. $gate->before(function (?stdClass $user) {
  121. $_SERVER['__laravel.gateBefore'] = true;
  122. });
  123. $gate->after(function (?stdClass $user) {
  124. $_SERVER['__laravel.gateAfter'] = true;
  125. });
  126. $gate->before(function (stdClass $user) {
  127. $_SERVER['__laravel.gateBefore2'] = true;
  128. });
  129. $gate->after(function (stdClass $user) {
  130. $_SERVER['__laravel.gateAfter2'] = true;
  131. });
  132. $gate->define('foo', function ($user = null) {
  133. return true;
  134. });
  135. $this->assertTrue($gate->check('foo'));
  136. $this->assertTrue($_SERVER['__laravel.gateBefore']);
  137. $this->assertFalse($_SERVER['__laravel.gateBefore2']);
  138. $this->assertTrue($_SERVER['__laravel.gateAfter']);
  139. $this->assertFalse($_SERVER['__laravel.gateAfter2']);
  140. unset(
  141. $_SERVER['__laravel.gateBefore'],
  142. $_SERVER['__laravel.gateBefore2'],
  143. $_SERVER['__laravel.gateAfter'],
  144. $_SERVER['__laravel.gateAfter2']
  145. );
  146. }
  147. public function testResourceGatesCanBeDefined()
  148. {
  149. $gate = $this->getBasicGate();
  150. $gate->resource('test', AccessGateTestResource::class);
  151. $dummy = new AccessGateTestDummy;
  152. $this->assertTrue($gate->check('test.view'));
  153. $this->assertTrue($gate->check('test.create'));
  154. $this->assertTrue($gate->check('test.update', $dummy));
  155. $this->assertTrue($gate->check('test.delete', $dummy));
  156. }
  157. public function testCustomResourceGatesCanBeDefined()
  158. {
  159. $gate = $this->getBasicGate();
  160. $abilities = [
  161. 'ability1' => 'foo',
  162. 'ability2' => 'bar',
  163. ];
  164. $gate->resource('test', AccessGateTestCustomResource::class, $abilities);
  165. $this->assertTrue($gate->check('test.ability1'));
  166. $this->assertTrue($gate->check('test.ability2'));
  167. }
  168. public function testBeforeCallbacksCanOverrideResultIfNecessary()
  169. {
  170. $gate = $this->getBasicGate();
  171. $gate->define('foo', function ($user) {
  172. return true;
  173. });
  174. $gate->before(function ($user, $ability) {
  175. $this->assertSame('foo', $ability);
  176. return false;
  177. });
  178. $this->assertFalse($gate->check('foo'));
  179. }
  180. public function testBeforeCallbacksDontInterruptGateCheckIfNoValueIsReturned()
  181. {
  182. $gate = $this->getBasicGate();
  183. $gate->define('foo', function ($user) {
  184. return true;
  185. });
  186. $gate->before(function () {
  187. //
  188. });
  189. $this->assertTrue($gate->check('foo'));
  190. }
  191. public function testAfterCallbacksAreCalledWithResult()
  192. {
  193. $gate = $this->getBasicGate();
  194. $gate->define('foo', function ($user) {
  195. return true;
  196. });
  197. $gate->define('bar', function ($user) {
  198. return false;
  199. });
  200. $gate->after(function ($user, $ability, $result) {
  201. if ($ability === 'foo') {
  202. $this->assertTrue($result, 'After callback on `foo` should receive true as result');
  203. } elseif ($ability === 'bar') {
  204. $this->assertFalse($result, 'After callback on `bar` should receive false as result');
  205. } else {
  206. $this->assertNull($result, 'After callback on `missing` should receive null as result');
  207. }
  208. });
  209. $this->assertTrue($gate->check('foo'));
  210. $this->assertFalse($gate->check('bar'));
  211. $this->assertFalse($gate->check('missing'));
  212. }
  213. public function testAfterCallbacksCanAllowIfNull()
  214. {
  215. $gate = $this->getBasicGate();
  216. $gate->after(function ($user, $ability, $result) {
  217. return true;
  218. });
  219. $this->assertTrue($gate->allows('null'));
  220. }
  221. public function testAfterCallbacksDoNotOverridePreviousResult()
  222. {
  223. $gate = $this->getBasicGate();
  224. $gate->define('deny', function ($user) {
  225. return false;
  226. });
  227. $gate->define('allow', function ($user) {
  228. return true;
  229. });
  230. $gate->after(function ($user, $ability, $result) {
  231. return ! $result;
  232. });
  233. $this->assertTrue($gate->allows('allow'));
  234. $this->assertTrue($gate->denies('deny'));
  235. }
  236. public function testAfterCallbacksDoNotOverrideEachOther()
  237. {
  238. $gate = $this->getBasicGate();
  239. $gate->after(function ($user, $ability, $result) {
  240. return $ability === 'allow';
  241. });
  242. $gate->after(function ($user, $ability, $result) {
  243. return ! $result;
  244. });
  245. $this->assertTrue($gate->allows('allow'));
  246. $this->assertTrue($gate->denies('deny'));
  247. }
  248. public function testCurrentUserThatIsOnGateAlwaysInjectedIntoClosureCallbacks()
  249. {
  250. $gate = $this->getBasicGate();
  251. $gate->define('foo', function ($user) {
  252. $this->assertSame(1, $user->id);
  253. return true;
  254. });
  255. $this->assertTrue($gate->check('foo'));
  256. }
  257. public function testASingleArgumentCanBePassedWhenCheckingAbilities()
  258. {
  259. $gate = $this->getBasicGate();
  260. $dummy = new AccessGateTestDummy;
  261. $gate->before(function ($user, $ability, array $arguments) use ($dummy) {
  262. $this->assertCount(1, $arguments);
  263. $this->assertSame($dummy, $arguments[0]);
  264. });
  265. $gate->define('foo', function ($user, $x) use ($dummy) {
  266. $this->assertSame($dummy, $x);
  267. return true;
  268. });
  269. $gate->after(function ($user, $ability, $result, array $arguments) use ($dummy) {
  270. $this->assertCount(1, $arguments);
  271. $this->assertSame($dummy, $arguments[0]);
  272. });
  273. $this->assertTrue($gate->check('foo', $dummy));
  274. }
  275. public function testMultipleArgumentsCanBePassedWhenCheckingAbilities()
  276. {
  277. $gate = $this->getBasicGate();
  278. $dummy1 = new AccessGateTestDummy;
  279. $dummy2 = new AccessGateTestDummy;
  280. $gate->before(function ($user, $ability, array $arguments) use ($dummy1, $dummy2) {
  281. $this->assertCount(2, $arguments);
  282. $this->assertSame([$dummy1, $dummy2], $arguments);
  283. });
  284. $gate->define('foo', function ($user, $x, $y) use ($dummy1, $dummy2) {
  285. $this->assertSame($dummy1, $x);
  286. $this->assertSame($dummy2, $y);
  287. return true;
  288. });
  289. $gate->after(function ($user, $ability, $result, array $arguments) use ($dummy1, $dummy2) {
  290. $this->assertCount(2, $arguments);
  291. $this->assertSame([$dummy1, $dummy2], $arguments);
  292. });
  293. $this->assertTrue($gate->check('foo', [$dummy1, $dummy2]));
  294. }
  295. public function testClassesCanBeDefinedAsCallbacksUsingAtNotation()
  296. {
  297. $gate = $this->getBasicGate();
  298. $gate->define('foo', AccessGateTestClass::class.'@foo');
  299. $this->assertTrue($gate->check('foo'));
  300. }
  301. public function testInvokableClassesCanBeDefined()
  302. {
  303. $gate = $this->getBasicGate();
  304. $gate->define('foo', AccessGateTestInvokableClass::class);
  305. $this->assertTrue($gate->check('foo'));
  306. }
  307. public function testGatesCanBeDefinedUsingAnArrayCallback()
  308. {
  309. $gate = $this->getBasicGate();
  310. $gate->define('foo', [new AccessGateTestStaticClass, 'foo']);
  311. $this->assertTrue($gate->check('foo'));
  312. }
  313. public function testGatesCanBeDefinedUsingAnArrayCallbackWithStaticMethod()
  314. {
  315. $gate = $this->getBasicGate();
  316. $gate->define('foo', [AccessGateTestStaticClass::class, 'foo']);
  317. $this->assertTrue($gate->check('foo'));
  318. }
  319. public function testPolicyClassesCanBeDefinedToHandleChecksForGivenType()
  320. {
  321. $gate = $this->getBasicGate();
  322. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicy::class);
  323. $this->assertTrue($gate->check('update', new AccessGateTestDummy));
  324. }
  325. public function testPolicyClassesHandleChecksForAllSubtypes()
  326. {
  327. $gate = $this->getBasicGate();
  328. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicy::class);
  329. $this->assertTrue($gate->check('update', new AccessGateTestSubDummy));
  330. }
  331. public function testPolicyClassesHandleChecksForInterfaces()
  332. {
  333. $gate = $this->getBasicGate();
  334. $gate->policy(AccessGateTestDummyInterface::class, AccessGateTestPolicy::class);
  335. $this->assertTrue($gate->check('update', new AccessGateTestSubDummy));
  336. }
  337. public function testPolicyConvertsDashToCamel()
  338. {
  339. $gate = $this->getBasicGate();
  340. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicy::class);
  341. $this->assertTrue($gate->check('update-dash', new AccessGateTestDummy));
  342. }
  343. public function testPolicyDefaultToFalseIfMethodDoesNotExistAndGateDoesNotExist()
  344. {
  345. $gate = $this->getBasicGate();
  346. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicy::class);
  347. $this->assertFalse($gate->check('nonexistent_method', new AccessGateTestDummy));
  348. }
  349. public function testPolicyClassesCanBeDefinedToHandleChecksForGivenClassName()
  350. {
  351. $gate = $this->getBasicGate(true);
  352. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicy::class);
  353. $this->assertTrue($gate->check('create', [AccessGateTestDummy::class, true]));
  354. }
  355. public function testPoliciesMayHaveBeforeMethodsToOverrideChecks()
  356. {
  357. $gate = $this->getBasicGate();
  358. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyWithBefore::class);
  359. $this->assertTrue($gate->check('update', new AccessGateTestDummy));
  360. }
  361. public function testPoliciesAlwaysOverrideClosuresWithSameName()
  362. {
  363. $gate = $this->getBasicGate();
  364. $gate->define('update', function () {
  365. $this->fail();
  366. });
  367. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicy::class);
  368. $this->assertTrue($gate->check('update', new AccessGateTestDummy));
  369. }
  370. public function testPoliciesDeferToGatesIfMethodDoesNotExist()
  371. {
  372. $gate = $this->getBasicGate();
  373. $gate->define('nonexistent_method', function ($user) {
  374. return true;
  375. });
  376. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicy::class);
  377. $this->assertTrue($gate->check('nonexistent_method', new AccessGateTestDummy));
  378. }
  379. public function testForUserMethodAttachesANewUserToANewGateInstance()
  380. {
  381. $gate = $this->getBasicGate();
  382. // Assert that the callback receives the new user with ID of 2 instead of ID of 1...
  383. $gate->define('foo', function ($user) {
  384. $this->assertSame(2, $user->id);
  385. return true;
  386. });
  387. $this->assertTrue($gate->forUser((object) ['id' => 2])->check('foo'));
  388. }
  389. public function testForUserMethodAttachesANewUserToANewGateInstanceWithGuessCallback()
  390. {
  391. $gate = $this->getBasicGate();
  392. $gate->define('foo', function () {
  393. return true;
  394. });
  395. $counter = 0;
  396. $guesserCallback = function () use (&$counter) {
  397. $counter++;
  398. };
  399. $gate->guessPolicyNamesUsing($guesserCallback);
  400. $gate->getPolicyFor('fooClass');
  401. $this->assertSame(1, $counter);
  402. // now the guesser callback should be present on the new gate as well
  403. $newGate = $gate->forUser((object) ['id' => 1]);
  404. $newGate->getPolicyFor('fooClass');
  405. $this->assertSame(2, $counter);
  406. $newGate->getPolicyFor('fooClass');
  407. $this->assertSame(3, $counter);
  408. }
  409. /**
  410. * @dataProvider notCallableDataProvider
  411. */
  412. public function testDefineSecondParameterShouldBeStringOrCallable($callback)
  413. {
  414. $this->expectException(InvalidArgumentException::class);
  415. $gate = $this->getBasicGate();
  416. $gate->define('foo', $callback);
  417. }
  418. /**
  419. * @return array
  420. */
  421. public function notCallableDataProvider()
  422. {
  423. return [
  424. [1],
  425. [new stdClass],
  426. [[]],
  427. [1.1],
  428. ];
  429. }
  430. public function testAuthorizeThrowsUnauthorizedException()
  431. {
  432. $this->expectException(AuthorizationException::class);
  433. $this->expectExceptionMessage('You are not an admin.');
  434. $this->expectExceptionCode(null);
  435. $gate = $this->getBasicGate();
  436. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicy::class);
  437. $gate->authorize('create', new AccessGateTestDummy);
  438. }
  439. public function testAuthorizeThrowsUnauthorizedExceptionWithCustomStatusCode()
  440. {
  441. $this->expectException(AuthorizationException::class);
  442. $this->expectExceptionMessage('Not allowed to view as it is not published.');
  443. $this->expectExceptionCode('unpublished');
  444. $gate = $this->getBasicGate();
  445. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyWithCode::class);
  446. $gate->authorize('view', new AccessGateTestDummy);
  447. }
  448. public function testAuthorizeWithPolicyThatReturnsDeniedResponseObjectThrowsException()
  449. {
  450. $this->expectException(AuthorizationException::class);
  451. $this->expectExceptionMessage('Not allowed.');
  452. $this->expectExceptionCode('some_code');
  453. $gate = $this->getBasicGate();
  454. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyWithDeniedResponseObject::class);
  455. $gate->authorize('create', new AccessGateTestDummy);
  456. }
  457. public function testPolicyThatThrowsAuthorizationExceptionIsCaughtInInspect()
  458. {
  459. $gate = $this->getBasicGate();
  460. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyThrowingAuthorizationException::class);
  461. $response = $gate->inspect('create', new AccessGateTestDummy);
  462. $this->assertTrue($response->denied());
  463. $this->assertFalse($response->allowed());
  464. $this->assertSame('Not allowed.', $response->message());
  465. $this->assertSame('some_code', $response->code());
  466. }
  467. public function testAuthorizeReturnsAllowedResponse()
  468. {
  469. $gate = $this->getBasicGate(true);
  470. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicy::class);
  471. $check = $gate->check('create', new AccessGateTestDummy);
  472. $response = $gate->authorize('create', new AccessGateTestDummy);
  473. $this->assertInstanceOf(Response::class, $response);
  474. $this->assertNull($response->message());
  475. $this->assertTrue($check);
  476. }
  477. public function testResponseReturnsResponseWhenAbilityGranted()
  478. {
  479. $gate = $this->getBasicGate(true);
  480. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyWithCode::class);
  481. $response = $gate->inspect('view', new AccessGateTestDummy);
  482. $this->assertInstanceOf(Response::class, $response);
  483. $this->assertNull($response->message());
  484. $this->assertTrue($response->allowed());
  485. $this->assertFalse($response->denied());
  486. $this->assertNull($response->code());
  487. }
  488. public function testResponseReturnsResponseWhenAbilityDenied()
  489. {
  490. $gate = $this->getBasicGate();
  491. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyWithCode::class);
  492. $response = $gate->inspect('view', new AccessGateTestDummy);
  493. $this->assertInstanceOf(Response::class, $response);
  494. $this->assertSame('Not allowed to view as it is not published.', $response->message());
  495. $this->assertFalse($response->allowed());
  496. $this->assertTrue($response->denied());
  497. $this->assertSame('unpublished', $response->code());
  498. }
  499. public function testAuthorizeReturnsAnAllowedResponseForATruthyReturn()
  500. {
  501. $gate = $this->getBasicGate();
  502. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicy::class);
  503. $response = $gate->authorize('update', new AccessGateTestDummy);
  504. $this->assertInstanceOf(Response::class, $response);
  505. $this->assertNull($response->message());
  506. }
  507. public function testAllowIfAuthorizesTrue()
  508. {
  509. $response = $this->getBasicGate()->allowIf(true);
  510. $this->assertTrue($response->allowed());
  511. }
  512. public function testAllowIfAuthorizesTruthy()
  513. {
  514. $response = $this->getBasicGate()->allowIf('truthy');
  515. $this->assertTrue($response->allowed());
  516. }
  517. public function testAllowIfAuthorizesIfGuest()
  518. {
  519. $response = $this->getBasicGate()->forUser(null)->allowIf(true);
  520. $this->assertTrue($response->allowed());
  521. }
  522. public function testAllowIfAuthorizesCallbackTrue()
  523. {
  524. $response = $this->getBasicGate()->allowIf(function ($user) {
  525. $this->assertSame(1, $user->id);
  526. return true;
  527. }, 'foo', 'bar');
  528. $this->assertTrue($response->allowed());
  529. $this->assertSame('foo', $response->message());
  530. $this->assertSame('bar', $response->code());
  531. }
  532. public function testAllowIfAuthorizesResponseAllowed()
  533. {
  534. $response = $this->getBasicGate()->allowIf(Response::allow('foo', 'bar'));
  535. $this->assertTrue($response->allowed());
  536. $this->assertSame('foo', $response->message());
  537. $this->assertSame('bar', $response->code());
  538. }
  539. public function testAllowIfAuthorizesCallbackResponseAllowed()
  540. {
  541. $response = $this->getBasicGate()->allowIf(function () {
  542. return Response::allow('quz', 'qux');
  543. }, 'foo', 'bar');
  544. $this->assertTrue($response->allowed());
  545. $this->assertSame('quz', $response->message());
  546. $this->assertSame('qux', $response->code());
  547. }
  548. public function testAllowsIfCallbackAcceptsGuestsWhenAuthenticated()
  549. {
  550. $response = $this->getBasicGate()->allowIf(function (stdClass $user = null) {
  551. return $user !== null;
  552. });
  553. $this->assertTrue($response->allowed());
  554. }
  555. public function testAllowIfCallbackAcceptsGuestsWhenUnauthenticated()
  556. {
  557. $gate = $this->getBasicGate()->forUser(null);
  558. $response = $gate->allowIf(function (stdClass $user = null) {
  559. return $user === null;
  560. });
  561. $this->assertTrue($response->allowed());
  562. }
  563. public function testAllowIfThrowsExceptionWhenFalse()
  564. {
  565. $this->expectException(AuthorizationException::class);
  566. $this->getBasicGate()->allowIf(false);
  567. }
  568. public function testAllowIfThrowsExceptionWhenCallbackFalse()
  569. {
  570. $this->expectException(AuthorizationException::class);
  571. $this->expectExceptionMessage('foo');
  572. $this->expectExceptionCode('bar');
  573. $this->getBasicGate()->allowIf(function () {
  574. return false;
  575. }, 'foo', 'bar');
  576. }
  577. public function testAllowIfThrowsExceptionWhenResponseDenied()
  578. {
  579. $this->expectException(AuthorizationException::class);
  580. $this->expectExceptionMessage('foo');
  581. $this->expectExceptionCode('bar');
  582. $this->getBasicGate()->allowIf(Response::deny('foo', 'bar'));
  583. }
  584. public function testAllowIfThrowsExceptionWhenCallbackResponseDenied()
  585. {
  586. $this->expectException(AuthorizationException::class);
  587. $this->expectExceptionMessage('quz');
  588. $this->expectExceptionCode('qux');
  589. $this->getBasicGate()->allowIf(function () {
  590. return Response::deny('quz', 'qux');
  591. }, 'foo', 'bar');
  592. }
  593. public function testAllowIfThrowsExceptionIfUnauthenticated()
  594. {
  595. $this->expectException(AuthorizationException::class);
  596. $this->expectExceptionMessage('foo');
  597. $this->expectExceptionCode('bar');
  598. $gate = $this->getBasicGate()->forUser(null);
  599. $gate->allowIf(function () {
  600. return true;
  601. }, 'foo', 'bar');
  602. }
  603. public function testAllowIfThrowsExceptionIfAuthUserExpectedWhenGuest()
  604. {
  605. $this->expectException(AuthorizationException::class);
  606. $this->expectExceptionMessage('foo');
  607. $this->expectExceptionCode('bar');
  608. $gate = $this->getBasicGate()->forUser(null);
  609. $gate->allowIf(function (stdClass $user) {
  610. return true;
  611. }, 'foo', 'bar');
  612. }
  613. public function testDenyIfAuthorizesFalse()
  614. {
  615. $response = $this->getBasicGate()->denyIf(false);
  616. $this->assertTrue($response->allowed());
  617. }
  618. public function testDenyIfAuthorizesFalsy()
  619. {
  620. $response = $this->getBasicGate()->denyIf(0);
  621. $this->assertTrue($response->allowed());
  622. }
  623. public function testDenyIfAuthorizesIfGuest()
  624. {
  625. $response = $this->getBasicGate()->forUser(null)->denyIf(false);
  626. $this->assertTrue($response->allowed());
  627. }
  628. public function testDenyIfAuthorizesCallbackFalse()
  629. {
  630. $response = $this->getBasicGate()->denyIf(function ($user) {
  631. $this->assertSame(1, $user->id);
  632. return false;
  633. }, 'foo', 'bar');
  634. $this->assertTrue($response->allowed());
  635. $this->assertSame('foo', $response->message());
  636. $this->assertSame('bar', $response->code());
  637. }
  638. public function testDenyIfAuthorizesResponseAllowed()
  639. {
  640. $response = $this->getBasicGate()->denyIf(Response::allow('foo', 'bar'));
  641. $this->assertTrue($response->allowed());
  642. $this->assertSame('foo', $response->message());
  643. $this->assertSame('bar', $response->code());
  644. }
  645. public function testDenyIfAuthorizesCallbackResponseAllowed()
  646. {
  647. $response = $this->getBasicGate()->denyIf(function () {
  648. return Response::allow('quz', 'qux');
  649. }, 'foo', 'bar');
  650. $this->assertTrue($response->allowed());
  651. $this->assertSame('quz', $response->message());
  652. $this->assertSame('qux', $response->code());
  653. }
  654. public function testDenyIfCallbackAcceptsGuestsWhenAuthenticated()
  655. {
  656. $response = $this->getBasicGate()->denyIf(function (stdClass $user = null) {
  657. return $user === null;
  658. });
  659. $this->assertTrue($response->allowed());
  660. }
  661. public function testDenyIfCallbackAcceptsGuestsWhenUnauthenticated()
  662. {
  663. $gate = $this->getBasicGate()->forUser(null);
  664. $response = $gate->denyIf(function (stdClass $user = null) {
  665. return $user !== null;
  666. });
  667. $this->assertTrue($response->allowed());
  668. }
  669. public function testDenyIfThrowsExceptionWhenTrue()
  670. {
  671. $this->expectException(AuthorizationException::class);
  672. $this->getBasicGate()->denyIf(true);
  673. }
  674. public function testDenyIfThrowsExceptionWhenCallbackTrue()
  675. {
  676. $this->expectException(AuthorizationException::class);
  677. $this->expectExceptionMessage('foo');
  678. $this->expectExceptionCode('bar');
  679. $this->getBasicGate()->denyIf(function () {
  680. return true;
  681. }, 'foo', 'bar');
  682. }
  683. public function testDenyIfThrowsExceptionWhenResponseDenied()
  684. {
  685. $this->expectException(AuthorizationException::class);
  686. $this->expectExceptionMessage('foo');
  687. $this->expectExceptionCode('bar');
  688. $this->getBasicGate()->denyIf(Response::deny('foo', 'bar'));
  689. }
  690. public function testDenyIfThrowsExceptionWhenCallbackResponseDenied()
  691. {
  692. $this->expectException(AuthorizationException::class);
  693. $this->expectExceptionMessage('quz');
  694. $this->expectExceptionCode('qux');
  695. $this->getBasicGate()->denyIf(function () {
  696. return Response::deny('quz', 'qux');
  697. }, 'foo', 'bar');
  698. }
  699. public function testDenyIfThrowsExceptionIfUnauthenticated()
  700. {
  701. $this->expectException(AuthorizationException::class);
  702. $this->expectExceptionMessage('foo');
  703. $this->expectExceptionCode('bar');
  704. $gate = $this->getBasicGate()->forUser(null);
  705. $gate->denyIf(function () {
  706. return false;
  707. }, 'foo', 'bar');
  708. }
  709. public function testDenyIfThrowsExceptionIfAuthUserExpectedWhenGuest()
  710. {
  711. $this->expectException(AuthorizationException::class);
  712. $this->expectExceptionMessage('foo');
  713. $this->expectExceptionCode('bar');
  714. $gate = $this->getBasicGate()->forUser(null);
  715. $gate->denyIf(function (stdClass $user) {
  716. return false;
  717. }, 'foo', 'bar');
  718. }
  719. protected function getBasicGate($isAdmin = false)
  720. {
  721. return new Gate(new Container, function () use ($isAdmin) {
  722. return (object) ['id' => 1, 'isAdmin' => $isAdmin];
  723. });
  724. }
  725. public function testAnyAbilityCheckPassesIfAllPass()
  726. {
  727. $gate = $this->getBasicGate();
  728. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyWithAllPermissions::class);
  729. $this->assertTrue($gate->any(['edit', 'update'], new AccessGateTestDummy));
  730. }
  731. public function testAnyAbilityCheckPassesIfAtLeastOnePasses()
  732. {
  733. $gate = $this->getBasicGate();
  734. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyWithMixedPermissions::class);
  735. $this->assertTrue($gate->any(['edit', 'update'], new AccessGateTestDummy));
  736. }
  737. public function testAnyAbilityCheckFailsIfNonePass()
  738. {
  739. $gate = $this->getBasicGate();
  740. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyWithNoPermissions::class);
  741. $this->assertFalse($gate->any(['edit', 'update'], new AccessGateTestDummy));
  742. }
  743. public function testNoneAbilityCheckPassesIfAllFail()
  744. {
  745. $gate = $this->getBasicGate();
  746. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyWithNoPermissions::class);
  747. $this->assertTrue($gate->none(['edit', 'update'], new AccessGateTestDummy));
  748. }
  749. public function testEveryAbilityCheckPassesIfAllPass()
  750. {
  751. $gate = $this->getBasicGate();
  752. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyWithAllPermissions::class);
  753. $this->assertTrue($gate->check(['edit', 'update'], new AccessGateTestDummy));
  754. }
  755. public function testEveryAbilityCheckFailsIfAtLeastOneFails()
  756. {
  757. $gate = $this->getBasicGate();
  758. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyWithMixedPermissions::class);
  759. $this->assertFalse($gate->check(['edit', 'update'], new AccessGateTestDummy));
  760. }
  761. public function testEveryAbilityCheckFailsIfNonePass()
  762. {
  763. $gate = $this->getBasicGate();
  764. $gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyWithNoPermissions::class);
  765. $this->assertFalse($gate->check(['edit', 'update'], new AccessGateTestDummy));
  766. }
  767. /**
  768. * @dataProvider hasAbilitiesTestDataProvider
  769. *
  770. * @param array $abilitiesToSet
  771. * @param array|string $abilitiesToCheck
  772. * @param bool $expectedHasValue
  773. */
  774. public function testHasAbilities($abilitiesToSet, $abilitiesToCheck, $expectedHasValue)
  775. {
  776. $gate = $this->getBasicGate();
  777. $gate->resource('test', AccessGateTestResource::class, $abilitiesToSet);
  778. $this->assertEquals($expectedHasValue, $gate->has($abilitiesToCheck));
  779. }
  780. public function hasAbilitiesTestDataProvider()
  781. {
  782. $abilities = ['foo' => 'foo', 'bar' => 'bar'];
  783. $noAbilities = [];
  784. return [
  785. [$abilities, ['test.foo', 'test.bar'], true],
  786. [$abilities, ['test.bar', 'test.foo'], true],
  787. [$abilities, ['test.bar', 'test.foo', 'test.baz'], false],
  788. [$abilities, ['test.bar'], true],
  789. [$abilities, ['baz'], false],
  790. [$abilities, [''], false],
  791. [$abilities, [], true],
  792. [$abilities, 'test.bar', true],
  793. [$abilities, 'test.foo', true],
  794. [$abilities, '', false],
  795. [$noAbilities, '', false],
  796. [$noAbilities, [], true],
  797. ];
  798. }
  799. public function testClassesCanBeDefinedAsCallbacksUsingAtNotationForGuests()
  800. {
  801. $gate = new Gate(new Container, function () {
  802. //
  803. });
  804. $gate->define('foo', AccessGateTestClassForGuest::class.'@foo');
  805. $gate->define('obj_foo', [new AccessGateTestClassForGuest, 'foo']);
  806. $gate->define('static_foo', [AccessGateTestClassForGuest::class, 'staticFoo']);
  807. $gate->define('static_@foo', AccessGateTestClassForGuest::class.'@staticFoo');
  808. $gate->define('bar', AccessGateTestClassForGuest::class.'@bar');
  809. $gate->define('invokable', AccessGateTestGuestInvokableClass::class);
  810. $gate->define('nullable_invokable', AccessGateTestGuestNullableInvokable::class);
  811. $gate->define('absent_invokable', 'someAbsentClass');
  812. AccessGateTestClassForGuest::$calledMethod = '';
  813. $this->assertTrue($gate->check('foo'));
  814. $this->assertSame('foo was called', AccessGateTestClassForGuest::$calledMethod);
  815. $this->assertTrue($gate->check('static_foo'));
  816. $this->assertSame('static foo was invoked', AccessGateTestClassForGuest::$calledMethod);
  817. $this->assertTrue($gate->check('bar'));
  818. $this->assertSame('bar got invoked', AccessGateTestClassForGuest::$calledMethod);
  819. $this->assertTrue($gate->check('static_@foo'));
  820. $this->assertSame('static foo was invoked', AccessGateTestClassForGuest::$calledMethod);
  821. $this->assertTrue($gate->check('invokable'));
  822. $this->assertSame('__invoke was called', AccessGateTestGuestInvokableClass::$calledMethod);
  823. $this->assertTrue($gate->check('nullable_invokable'));
  824. $this->assertSame('Nullable __invoke was called', AccessGateTestGuestNullableInvokable::$calledMethod);
  825. $this->assertFalse($gate->check('absent_invokable'));
  826. }
  827. }
  828. class AccessGateTestClassForGuest
  829. {
  830. public static $calledMethod = null;
  831. public function foo($user = null)
  832. {
  833. static::$calledMethod = 'foo was called';
  834. return true;
  835. }
  836. public static function staticFoo($user = null)
  837. {
  838. static::$calledMethod = 'static foo was invoked';
  839. return true;
  840. }
  841. public function bar(?stdClass $user)
  842. {
  843. static::$calledMethod = 'bar got invoked';
  844. return true;
  845. }
  846. }
  847. class AccessGateTestStaticClass
  848. {
  849. public static function foo($user)
  850. {
  851. return $user->id === 1;
  852. }
  853. }
  854. class AccessGateTestClass
  855. {
  856. public function foo($user)
  857. {
  858. return $user->id === 1;
  859. }
  860. }
  861. class AccessGateTestInvokableClass
  862. {
  863. public function __invoke($user)
  864. {
  865. return $user->id === 1;
  866. }
  867. }
  868. class AccessGateTestGuestInvokableClass
  869. {
  870. public static $calledMethod = null;
  871. public function __invoke($user = null)
  872. {
  873. static::$calledMethod = '__invoke was called';
  874. return true;
  875. }
  876. }
  877. class AccessGateTestGuestNullableInvokable
  878. {
  879. public static $calledMethod = null;
  880. public function __invoke(?stdClass $user)
  881. {
  882. static::$calledMethod = 'Nullable __invoke was called';
  883. return true;
  884. }
  885. }
  886. interface AccessGateTestDummyInterface
  887. {
  888. //
  889. }
  890. class AccessGateTestDummy implements AccessGateTestDummyInterface
  891. {
  892. //
  893. }
  894. class AccessGateTestSubDummy extends AccessGateTestDummy
  895. {
  896. //
  897. }
  898. class AccessGateTestPolicy
  899. {
  900. use HandlesAuthorization;
  901. public function createAny($user, $additional)
  902. {
  903. return $additional;
  904. }
  905. public function create($user)
  906. {
  907. return $user->isAdmin ? $this->allow() : $this->deny('You are not an admin.');
  908. }
  909. public function updateAny($user, AccessGateTestDummy $dummy)
  910. {
  911. return ! $user->isAdmin;
  912. }
  913. public function update($user, AccessGateTestDummy $dummy)
  914. {
  915. return ! $user->isAdmin;
  916. }
  917. public function updateDash($user, AccessGateTestDummy $dummy)
  918. {
  919. return $user instanceof stdClass;
  920. }
  921. }
  922. class AccessGateTestPolicyWithBefore
  923. {
  924. public function before($user, $ability)
  925. {
  926. return true;
  927. }
  928. public function update($user, AccessGateTestDummy $dummy)
  929. {
  930. return false;
  931. }
  932. }
  933. class AccessGateTestResource
  934. {
  935. public function view($user)
  936. {
  937. return true;
  938. }
  939. public function create($user)
  940. {
  941. return true;
  942. }
  943. public function update($user, AccessGateTestDummy $dummy)
  944. {
  945. return true;
  946. }
  947. public function delete($user, AccessGateTestDummy $dummy)
  948. {
  949. return true;
  950. }
  951. }
  952. class AccessGateTestCustomResource
  953. {
  954. public function foo($user)
  955. {
  956. return true;
  957. }
  958. public function bar($user)
  959. {
  960. return true;
  961. }
  962. }
  963. class AccessGateTestPolicyWithMixedPermissions
  964. {
  965. public function edit($user, AccessGateTestDummy $dummy)
  966. {
  967. return false;
  968. }
  969. public function update($user, AccessGateTestDummy $dummy)
  970. {
  971. return true;
  972. }
  973. }
  974. class AccessGateTestPolicyWithNoPermissions
  975. {
  976. public function edit($user, AccessGateTestDummy $dummy)
  977. {
  978. return false;
  979. }
  980. public function update($user, AccessGateTestDummy $dummy)
  981. {
  982. return false;
  983. }
  984. }
  985. class AccessGateTestPolicyWithAllPermissions
  986. {
  987. public function edit($user, AccessGateTestDummy $dummy)
  988. {
  989. return true;
  990. }
  991. public function update($user, AccessGateTestDummy $dummy)
  992. {
  993. return true;
  994. }
  995. }
  996. class AccessGateTestPolicyThatAllowsGuests
  997. {
  998. public function before(?stdClass $user)
  999. {
  1000. $_SERVER['__laravel.testBefore'] = true;
  1001. }
  1002. public function edit(?stdClass $user, AccessGateTestDummy $dummy)
  1003. {
  1004. return true;
  1005. }
  1006. public function update($user, AccessGateTestDummy $dummy)
  1007. {
  1008. return true;
  1009. }
  1010. }
  1011. class AccessGateTestPolicyWithNonGuestBefore
  1012. {
  1013. public function before(stdClass $user)
  1014. {
  1015. $_SERVER['__laravel.testBefore'] = true;
  1016. }
  1017. public function edit(?stdClass $user, AccessGateTestDummy $dummy)
  1018. {
  1019. return true;
  1020. }
  1021. public function update($user, AccessGateTestDummy $dummy)
  1022. {
  1023. return true;
  1024. }
  1025. }
  1026. class AccessGateTestBeforeCallback
  1027. {
  1028. public function allowEverything($user = null)
  1029. {
  1030. return true;
  1031. }
  1032. public static function allowEverythingStatically($user = null)
  1033. {
  1034. return true;
  1035. }
  1036. }
  1037. class AccessGateTestPolicyWithCode
  1038. {
  1039. use HandlesAuthorization;
  1040. public function view($user)
  1041. {
  1042. if (! $user->isAdmin) {
  1043. return $this->deny('Not allowed to view as it is not published.', 'unpublished');
  1044. }
  1045. return true;
  1046. }
  1047. }
  1048. class AccessGateTestPolicyWithDeniedResponseObject
  1049. {
  1050. public function create()
  1051. {
  1052. return Response::deny('Not allowed.', 'some_code');
  1053. }
  1054. }
  1055. class AccessGateTestPolicyThrowingAuthorizationException
  1056. {
  1057. public function create()
  1058. {
  1059. throw new AuthorizationException('Not allowed.', 'some_code');
  1060. }
  1061. }