From 00bf7aa2b64070883ba68c5ea29707a5c239d836 Mon Sep 17 00:00:00 2001 From: Evert Pot Date: Sun, 7 Oct 2012 22:29:04 +0200 Subject: [PATCH] Added helper class for HTTP basic auth --- lib/Sabre/HTTP/Auth/Basic.php | 81 +++++++++++++++++++++++++++++ tests/Sabre/HTTP/Auth/BasicTest.php | 57 ++++++++++++++++++++ 2 files changed, 138 insertions(+) create mode 100644 lib/Sabre/HTTP/Auth/Basic.php create mode 100644 tests/Sabre/HTTP/Auth/BasicTest.php diff --git a/lib/Sabre/HTTP/Auth/Basic.php b/lib/Sabre/HTTP/Auth/Basic.php new file mode 100644 index 0000000..130bdf5 --- /dev/null +++ b/lib/Sabre/HTTP/Auth/Basic.php @@ -0,0 +1,81 @@ +realm = $realm; + + } + + /** + * This method returns a numeric array with a username and password as the + * only elements. + * + * If no credentials were found, this method returns null. + * + * @param Sabre\HTTP\Request $request + * @return null|array + */ + public function getCredentials(Request $request) { + + $auth = $request->getHeader('Authorization'); + + if (!$auth) { + return null; + } + + if (strtolower(substr($auth,0,6))!=='basic ') { + return null; + } + + return explode(':',base64_decode(substr($auth, 6)), 2); + + } + + /** + * This method sends the needed HTTP header and statuscode (401) to force + * the user to login. + * + * @param Sabre\HTTP\Response + * @return void + */ + public function requireLogin(Response $response) { + + $response->setHeader('WWW-Authenticate','Basic realm="' . $this->realm . '"'); + $response->setStatus(401); + + } + +} diff --git a/tests/Sabre/HTTP/Auth/BasicTest.php b/tests/Sabre/HTTP/Auth/BasicTest.php new file mode 100644 index 0000000..c491812 --- /dev/null +++ b/tests/Sabre/HTTP/Auth/BasicTest.php @@ -0,0 +1,57 @@ + 'Basic ' . base64_encode('user:pass:bla') + )); + + $basic = new Basic('Dagger'); + + $this->assertEquals(array( + 'user', + 'pass:bla', + ), $basic->getCredentials($request)); + + } + + function testGetCredentialsNoheader() { + + $request = new Request('GET','/',array()); + $basic = new Basic('Dagger'); + + $this->assertNull($basic->getCredentials($request)); + + } + + function testGetCredentialsNotBasic() { + + $request = new Request('GET','/',array( + 'Authorization' => 'QBasic ' . base64_encode('user:pass:bla') + )); + $basic = new Basic('Dagger'); + + $this->assertNull($basic->getCredentials($request)); + + } + + function testRequireLogin() { + + $response = new Response(); + $basic = new Basic('Dagger'); + + $basic->requireLogin($response); + + $this->assertEquals('Basic realm="Dagger"', $response->getHeader('WWW-Authenticate')); + $this->assertEquals('401 Unauthorized', $response->getStatus()); + + } + +}