public function authorize(Request $request, Response $response)
{
if (!$request->getHeader("authorization")) {
$response->setStatus(401);
$response->setHeader("www-authenticate", "Basic realm=\"Use your ID as username and token as password!\"");
$response->send("");
return;
}
$authorization = $request->getHeader("authorization");
$authorization = explode(" ", $authorization, 2);
if (count($authorization) < 2) {
$result = new Error("bad_request", "invalid authorization header", 400);
$this->writeResponse($request, $response, $result);
return;
}
switch (strtolower($authorization[0])) {
case "token":
break;
case "basic":
$authorization[1] = (string) @base64_decode($authorization[1]);
break;
default:
$result = new Error("bad_request", "invalid authorization header", 400);
$this->writeResponse($request, $response, $result);
return;
}
try {
$user = (yield resolve($this->authentication->authenticateWithToken($authorization[1])));
$request->setLocalVar("chat.api.user", $user);
} catch (AuthenticationException $e) {
$result = new Error("bad_authentication", "invalid token in authorization header", 403);
$this->writeResponse($request, $response, $result);
}
// a callable further down the chain will send the body
}