Skip to content

Commit

Permalink
ENHANCEMENT Allowing custom messages and permission codes in BasicAut…
Browse files Browse the repository at this point in the history
…h::protect_entire_site()

ENHANCEMENT Making $permissionCode argument optional for BasicAuth::requireLogin(). If not set the logic only checks for a valid account (but no group memberships)
ENHANCEMENT Using SS_HTTPResponse_Exception instead of header()/die() in BasicAuth::requireLogin() to make it more testable

git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/branches/2.4@107867 467b73ca-7a2a-4603-9d3b-597d59a354a9
  • Loading branch information
chillu authored and Sam Minnee committed Feb 2, 2011
1 parent 7fc3d8b commit 78ac0fe
Show file tree
Hide file tree
Showing 4 changed files with 200 additions and 24 deletions.
6 changes: 5 additions & 1 deletion core/control/Director.php
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,11 @@ protected static function handleRequest(SS_HTTPRequest $request, Session $sessio
$controllerObj = new $controller();
$controllerObj->setSession($session);

$result = $controllerObj->handleRequest($request);
try {
$result = $controllerObj->handleRequest($request);
} catch(SS_HTTPResponse_Exception $responseException) {
$result = $responseException->getResponse();
}
if(!is_object($result) || $result instanceof SS_HTTPResponse) return $result;

user_error("Bad result from url " . $request->getURL() . " handled by " .
Expand Down
73 changes: 50 additions & 23 deletions security/BasicAuth.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,30 +6,45 @@
* {@link BasicAuth::requireLogin()} from your Controller's init() method or action handler method.
*
* It also has a function to protect your entire site. See {@link BasicAuth::protect_entire_site()}
* for more information.
* for more information. You can control this setting on controller-level by using {@link Controller->basicAuthEnabled}.
*
* @package sapphire
* @subpackage security
*/
class BasicAuth {
/**
* Flag set by {@link self::protect_entire_site()}
* @var Boolean Flag set by {@link self::protect_entire_site()}
*/
private static $entire_site_protected = false;

/**
* @var String|array Holds a {@link Permission} code that is required
* when calling {@link protect_site_if_necessary()}. Set this value through
* {@link protect_entire_site()}.
*/
private static $entire_site_protected_code = 'ADMIN';

/**
* @var String Message that shows in the authentication box.
* Set this value through {@link protect_entire_site()}.
*/
private static $entire_site_protected_message = "SilverStripe test website. Use your CMS login.";

/**
* Require basic authentication. Will request a username and password if none is given.
*
* Used by {@link Controller::init()}.
*
* @throws SS_HTTPResponse_Exception
*
* @param string $realm
* @param string|array $permissionCode
* @param string|array $permissionCode Optional
* @param boolean $tryUsingSessionLogin If true, then the method with authenticate against the
* session log-in if those credentials are disabled.
* session log-in if those credentials are disabled.
* @return Member $member
*/
static function requireLogin($realm, $permissionCode, $tryUsingSessionLogin = true) {
if(!Security::database_is_ready() || Director::is_cli()) return true;
static function requireLogin($realm, $permissionCode = null, $tryUsingSessionLogin = true) {
if(!Security::database_is_ready()) return true;

$member = null;
if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
Expand All @@ -43,27 +58,33 @@ static function requireLogin($realm, $permissionCode, $tryUsingSessionLogin = tr

// If we've failed the authentication mechanism, then show the login form
if(!$member) {
header("WWW-Authenticate: Basic realm=\"$realm\"");
header($_SERVER['SERVER_PROTOCOL'] . ' 401 Unauthorized');
$response = new SS_HTTPResponse(null, 401);
$response->addHeader('WWW-Authenticate', "Basic realm=\"$realm\"");

if(isset($_SERVER['PHP_AUTH_USER'])) {
echo _t('BasicAuth.ERRORNOTREC', "That username / password isn't recognised");
$response->setBody(_t('BasicAuth.ERRORNOTREC', "That username / password isn't recognised"));
} else {
echo _t('BasicAuth.ENTERINFO', "Please enter a username and password.");
$response->setBody(_t('BasicAuth.ENTERINFO', "Please enter a username and password."));
}

die();
// Exception is caught by RequestHandler->handleRequest() and will halt further execution
$e = new SS_HTTPResponse_Exception(null, 401);
$e->setResponse($response);
throw $e;
}

if(!Permission::checkMember($member->ID, $permissionCode)) {
header("WWW-Authenticate: Basic realm=\"$realm\"");
header($_SERVER['SERVER_PROTOCOL'] . ' 401 Unauthorized');
if($permissionCode && !Permission::checkMember($member->ID, $permissionCode)) {
$response = new SS_HTTPResponse(null, 401);
$response->addHeader('WWW-Authenticate', "Basic realm=\"$realm\"");

if(isset($_SERVER['PHP_AUTH_USER'])) {
echo _t('BasicAuth.ERRORNOTADMIN', "That user is not an administrator.");
$response->setBody(_t('BasicAuth.ERRORNOTADMIN', "That user is not an administrator."));
}

die();
// Exception is caught by RequestHandler->handleRequest() and will halt further execution
$e = new SS_HTTPResponse_Exception(null, 401);
$e->setResponse($response);
throw $e;
}

return $member;
Expand All @@ -81,10 +102,15 @@ static function requireLogin($realm, $permissionCode, $tryUsingSessionLogin = tr
*
* define('SS_USE_BASIC_AUTH', true);
*
* @param $protect Set this to false to disable protection.
* @param boolean $protect Set this to false to disable protection.
* @param String $code {@link Permission} code that is required from the user.
* Defaults to "ADMIN". Set to NULL to just require a valid login, regardless
* of the permission codes a user has.
*/
static function protect_entire_site($protect = true) {
return self::$entire_site_protected = $protect;
static function protect_entire_site($protect = true, $code = 'ADMIN', $message = null) {
self::$entire_site_protected = $protect;
self::$entire_site_protected_code = $code;
if($message) self::$entire_site_protected_message = $message;
}

/**
Expand All @@ -105,13 +131,14 @@ static function disable() {

/**
* Call {@link BasicAuth::requireLogin()} if {@link BasicAuth::protect_entire_site()} has been called.
* This is a helper function used by Controller.
* This is a helper function used by {@link Controller::init()}.
*
* If you want to enabled protection (rather than enforcing it),
* please use {@link protect_entire_site()}.
*/
static function protect_site_if_necessary() {
if(self::$entire_site_protected) {
// The test-site protection should ignore the session log-in; otherwise it's difficult
// to test the log-in features of your site
self::requireLogin("SilverStripe test website. Use your CMS login.", "ADMIN", false);
self::requireLogin(self::$entire_site_protected_message, self::$entire_site_protected_code, false);
}
}

Expand Down
130 changes: 130 additions & 0 deletions tests/security/BasicAuthTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
<?php
/**
* @package sapphire
* @subpackage tests
*/

class BasicAuthTest extends FunctionalTest {

static $fixture_file = 'sapphire/tests/security/BasicAuthTest.yml';

function tearDown() {
parent::tearDown();

BasicAuth::protect_entire_site(false);
}

function testBasicAuthEnabledWithoutLogin() {
$origUser = @$_SERVER['PHP_AUTH_USER'];
$origPw = @$_SERVER['PHP_AUTH_PW'];

unset($_SERVER['PHP_AUTH_USER']);
unset($_SERVER['PHP_AUTH_PW']);

$response = Director::test('BasicAuthTest_ControllerSecuredWithPermission');
$this->assertEquals(401, $response->getStatusCode());

$_SERVER['PHP_AUTH_USER'] = $origUser;
$_SERVER['PHP_AUTH_PW'] = $origPw;
}

function testBasicAuthDoesntCallActionOrFurtherInitOnAuthFailure() {
$origUser = @$_SERVER['PHP_AUTH_USER'];
$origPw = @$_SERVER['PHP_AUTH_PW'];

unset($_SERVER['PHP_AUTH_USER']);
unset($_SERVER['PHP_AUTH_PW']);
$response = Director::test('BasicAuthTest_ControllerSecuredWithPermission');
$this->assertFalse(BasicAuthTest_ControllerSecuredWithPermission::$index_called);
$this->assertFalse(BasicAuthTest_ControllerSecuredWithPermission::$post_init_called);

$_SERVER['PHP_AUTH_USER'] = 'user-in-mygroup@test.com';
$_SERVER['PHP_AUTH_PW'] = 'test';
$response = Director::test('BasicAuthTest_ControllerSecuredWithPermission');
$this->assertTrue(BasicAuthTest_ControllerSecuredWithPermission::$index_called);
$this->assertTrue(BasicAuthTest_ControllerSecuredWithPermission::$post_init_called);

$_SERVER['PHP_AUTH_USER'] = $origUser;
$_SERVER['PHP_AUTH_PW'] = $origPw;
}

function testBasicAuthEnabledWithPermission() {
$origUser = @$_SERVER['PHP_AUTH_USER'];
$origPw = @$_SERVER['PHP_AUTH_PW'];

$_SERVER['PHP_AUTH_USER'] = 'user-in-mygroup@test.com';
$_SERVER['PHP_AUTH_PW'] = 'wrongpassword';
$response = Director::test('BasicAuthTest_ControllerSecuredWithPermission');
$this->assertEquals(401, $response->getStatusCode(), 'Invalid users dont have access');

$_SERVER['PHP_AUTH_USER'] = 'user-without-groups@test.com';
$_SERVER['PHP_AUTH_PW'] = 'test';
$response = Director::test('BasicAuthTest_ControllerSecuredWithPermission');
$this->assertEquals(401, $response->getStatusCode(), 'Valid user without required permission has no access');

$_SERVER['PHP_AUTH_USER'] = 'user-in-mygroup@test.com';
$_SERVER['PHP_AUTH_PW'] = 'test';
$response = Director::test('BasicAuthTest_ControllerSecuredWithPermission');
$this->assertEquals(200, $response->getStatusCode(), 'Valid user with required permission has access');

$_SERVER['PHP_AUTH_USER'] = $origUser;
$_SERVER['PHP_AUTH_PW'] = $origPw;
}

function testBasicAuthEnabledWithoutPermission() {
$origUser = @$_SERVER['PHP_AUTH_USER'];
$origPw = @$_SERVER['PHP_AUTH_PW'];

$_SERVER['PHP_AUTH_USER'] = 'user-without-groups@test.com';
$_SERVER['PHP_AUTH_PW'] = 'wrongpassword';
$response = Director::test('BasicAuthTest_ControllerSecuredWithoutPermission');
$this->assertEquals(401, $response->getStatusCode(), 'Invalid users dont have access');

$_SERVER['PHP_AUTH_USER'] = 'user-without-groups@test.com';
$_SERVER['PHP_AUTH_PW'] = 'test';
$response = Director::test('BasicAuthTest_ControllerSecuredWithoutPermission');
$this->assertEquals(200, $response->getStatusCode(), 'All valid users have access');

$_SERVER['PHP_AUTH_USER'] = 'user-in-mygroup@test.com';
$_SERVER['PHP_AUTH_PW'] = 'test';
$response = Director::test('BasicAuthTest_ControllerSecuredWithoutPermission');
$this->assertEquals(200, $response->getStatusCode(), 'All valid users have access');

$_SERVER['PHP_AUTH_USER'] = $origUser;
$_SERVER['PHP_AUTH_PW'] = $origPw;
}

}

class BasicAuthTest_ControllerSecuredWithPermission extends ContentController implements TestOnly {

static $post_init_called = false;

static $index_called = false;

function init() {
self::$post_init_called = false;
self::$index_called = false;

BasicAuth::protect_entire_site(true, 'MYCODE');

parent::init();

self::$post_init_called = true;
}

function index() {
self::$index_called = true;
}

}

class BasicAuthTest_ControllerSecuredWithoutPermission extends ContentController implements TestOnly {

function init() {
BasicAuth::protect_entire_site(true, null);

parent::init();
}

}
15 changes: 15 additions & 0 deletions tests/security/BasicAuthTest.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
Group:
mygroup:
Code: mygroup
Member:
user-in-mygroup:
Email: user-in-mygroup@test.com
Password: test
Groups: =>Group.mygroup
user-without-groups:
Email: user-without-groups@test.com
Password: test
Permission:
mycode:
Code: MYCODE
Group: =>Group.mygroup

0 comments on commit 78ac0fe

Please sign in to comment.