Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions src/Auth/LaravelAuthProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php namespace Dingo\Api\Auth;

use Illuminate\Http\Request;
use Illuminate\Routing\Route;
use Illuminate\Auth\AuthManager;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

class LaravelAuthProvider extends AuthorizationProvider {

/**
* Illuminate authentication manager.
*
* @var \Illuminate\Auth\AuthManager
*/
protected $auth;

/**
* Create a new instance.
*
* @param \Illuminate\Auth\AuthManager $auth
* @return void
*/
public function __construct(AuthManager $auth)
{
$this->auth = $auth;
}

/**
* Check if user is authenticated.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Routing\Route $route
* @return int
*/
public function authenticate(Request $request, Route $route)
{
if($this->auth->check())
{
return $this->auth->user()->id;
}

throw new UnauthorizedHttpException('Laravel', 'Not authorized.');
}

/**
* Get the providers authorization method.
*
* @return string
*/
public function getAuthorizationMethod()
{
return 'laravel';
}

}
51 changes: 51 additions & 0 deletions tests/AuthLaravelProviderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

use Mockery as m;
use Illuminate\Http\Request;
use Dingo\Api\Auth\LaravelAuthProvider;

class AuthLaravelProviderTest extends PHPUnit_Framework_TestCase {

public function setUp()
{
$this->auth = m::mock('Illuminate\Auth\AuthManager');
}

public function tearDown()
{
m::close();
}

public function testIsAuthenticatedAndReturnsUserId()
{
$this->auth->shouldReceive('check')
->once()
->andReturn(true);

$this->auth->shouldReceive('user')
->once()
->andReturn((object) ['id' => 1]);


$request = Request::create('foo', 'GET');
$provider = new LaravelAuthProvider($this->auth);

$this->assertEquals(1, $provider->authenticate($request, m::mock('Illuminate\Routing\Route')));
}

/**
* @expectedException \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
*/
public function testIsNotAuthenticatedThrowsException()
{
$request = Request::create('foo', 'GET');
$provider = new LaravelAuthProvider($this->auth);

$this->auth->shouldReceive('check')
->once()
->andReturn(false);

$provider->authenticate($request, m::mock('Illuminate\Routing\Route'));
}

}