public function testOnBeforeWrite()
 {
     /** @var ApiKeyPair $keyPair */
     $keyPair = ApiKeyPair::create();
     $keyPair->write();
     $keyLen = strlen(hash('md5', ''));
     $secretLen = strlen(hash('sha1', ''));
     $this->assertEquals($keyLen, strlen($keyPair->Key), "The autogenerated 'Key' value should be " . $keyLen . " characters long");
     $this->assertEquals($secretLen, strlen($keyPair->Secret), "The autogenerated 'Secret' value should be " . $secretLen . " characters long");
 }
 public static function authenticate()
 {
     $controller = Controller::curr();
     $request = $controller->getRequest();
     // Check that the date is within 15 minutes of server time
     $timeToCheck = $request->getHeader(self::getHeaderPrefix() . 'Date') ?: $request->getHeader('Date');
     if (!self::validateRequestTime($timeToCheck)) {
         return false;
     }
     preg_match('`\\s*' . self::getApiName() . '\\s+([^:]+):(\\S+)`', $request->getHeader('Authorization'), $authMatches);
     if (count($authMatches) !== 3) {
         return false;
     }
     // Check with the raw key, or try to base64_decode and convert to hex
     $keys = ApiKeyPair::get()->filter('Key', strtolower($authMatches[1]));
     if (!$keys->count()) {
         $keys = ApiKeyPair::get()->filter('Key', bin2hex(base64_decode($authMatches[1])));
     }
     /** @var ApiKeyPair $apiKey */
     $apiKey = $keys->first();
     if (!($apiKey and $apiKey->exists() and $apiKey->Enabled)) {
         return false;
     }
     $contentMD5 = $request->getHeader('Content-Md5');
     if ($contentMD5 and !self::validateContentIntegrity($contentMD5)) {
         return false;
     }
     if (!self::validateSignedRequest($request, $apiKey->Secret, $authMatches[2])) {
         return false;
     }
     $member = $apiKey->Member();
     if (!($member and $member->exists())) {
         return false;
     }
     // All tests pass; log the member in and return it
     $member->logIn();
     return $member;
 }