public function testSetException()
 {
     $this->config->expects($this->once())->method('setUserValue')->with('JohnDoe', 'contacts', 'keyValue', 'valueValue')->will($this->throwException(new \Exception()));
     $expected = new JSONResponse();
     $expected->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR);
     $this->assertEquals($expected, $this->controller->set('keyValue', 'valueValue'));
 }
 /**
  * @NoAdminRequired
  *
  * @param string $key
  * @param string $value
  * @return JSONResponse
  */
 public function set($key = '', $value = '')
 {
     $response = new JSONResponse();
     if ($key === '' || $value === '') {
         $response->setStatus(Http::STATUS_PRECONDITION_FAILED);
         return $response;
     }
     try {
         $this->config->setUserValue($this->userId, $this->appName, $key, $value);
         $response->setData(['key' => $key, 'value' => $value]);
         return $response;
     } catch (\Exception $e) {
         $response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR);
         return $response;
     }
 }
 public function testShowDoesNotExist()
 {
     $this->accountService->expects($this->once())->method('find')->with($this->equalTo($this->userId), $this->equalTo($this->accountId))->will($this->returnValue($this->account));
     $this->account->expects($this->once())->method('getConfiguration')->will($this->throwException(new OCP\AppFramework\Db\DoesNotExistException('test123')));
     $response = $this->controller->show($this->accountId);
     $expectedResponse = new JSONResponse([]);
     $expectedResponse->setStatus(404);
     $this->assertEquals($expectedResponse, $response);
 }
 public function testWithValidCredentialsBut2faEnabled()
 {
     $user = $this->getMock('\\OCP\\IUser');
     $this->userManager->expects($this->once())->method('checkPassword')->with('john', '123456')->will($this->returnValue($user));
     $this->twoFactorAuthManager->expects($this->once())->method('isTwoFactorAuthenticated')->with($user)->will($this->returnValue(true));
     $this->secureRandom->expects($this->never())->method('generate');
     $expected = new JSONResponse();
     $expected->setStatus(Http::STATUS_UNAUTHORIZED);
     $actual = $this->tokenController->generateToken('john', '123456');
     $this->assertEquals($expected, $actual);
 }
Example #5
0
 /**
  * @NoAdminRequired
  * @param $backends
  * @return JSONResponse
  */
 public function set($backends)
 {
     foreach ($backends as $backend) {
         foreach ($backend['config'] as $key => $value) {
             $this->configMapper->set($backend['id'], $key, $value);
         }
     }
     $res = new JSONResponse();
     $res->setStatus(Http::STATUS_OK);
     return $res;
 }
Example #6
0
 /**
  * @NoAdminRequired
  */
 public function download($path)
 {
     if (!$path) {
         $response = new JSONResponse();
         $response->setStatus(Http::STATUS_BAD_REQUEST);
         return $response;
     }
     $fullPath = '/files' . $path;
     $fileInfo = \OC\Files\Filesystem::getFileInfo($path);
     if ($fileInfo) {
         if ($fileInfo->getMimeType() !== \OCA\Documents\Filter\Office::NATIVE_MIMETYPE) {
             $file = new File($fileInfo->getId());
             $genesis = new Genesis($file);
             $fullPath = $genesis->getPath();
         }
     }
     return new DownloadResponse($this->request, $this->uid, $fullPath);
 }
Example #7
0
 /**
  * If an SecurityException is being caught return a JSON error response
  *
  * @param Controller $controller the controller that is being called
  * @param string $methodName the name of the method that will be called on
  *                           the controller
  * @param \Exception $exception the thrown exception
  * @throws \Exception the passed in exception if it cant handle it
  * @return Response a Response object or null in case that the exception could not be handled
  */
 public function afterException($controller, $methodName, \Exception $exception)
 {
     if ($exception instanceof SecurityException) {
         $response = new JSONResponse(['message' => $exception->getMessage()]);
         if ($exception->getCode() !== 0) {
             $response->setStatus($exception->getCode());
         } else {
             $response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR);
         }
         return $response;
     }
     throw $exception;
 }
Example #8
0
 /**
  * @NoAdminRequired
  * @param $accountId
  * @param $folders
  * @return JSONResponse
  */
 public function detectChanges($accountId, $folders)
 {
     try {
         $query = [];
         foreach ($folders as $folder) {
             $folderId = base64_decode($folder['id']);
             $parts = explode('/', $folderId);
             if (count($parts) > 1 && $parts[1] === 'FLAGGED') {
                 continue;
             }
             if (isset($folder['error'])) {
                 continue;
             }
             $query[$folderId] = $folder;
         }
         $account = $this->accountService->find($this->currentUserId, $accountId);
         $mailBoxes = $account->getChangedMailboxes($query);
         return new JSONResponse($mailBoxes);
     } catch (\Horde_Imap_Client_Exception $e) {
         $response = new JSONResponse();
         $response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR);
         return $response;
     } catch (DoesNotExistException $e) {
         return new JSONResponse();
     }
 }
Example #9
0
 /**
  * @NoAdminRequired
  * @PublicPage
  */
 public function poll($command, $args)
 {
     $response = new JSONResponse();
     try {
         $esId = isset($args['es_id']) ? $args['es_id'] : null;
         $session = new Db\Session();
         $session->load($esId);
         $memberId = isset($args['member_id']) ? $args['member_id'] : null;
         $member = new Db\Member();
         $member->load($memberId);
         if (!$member->getIsGuest()) {
             \OCP\JSON::checkLoggedIn();
         }
         try {
             new File($session->getFileId());
         } catch (\Exception $e) {
             $this->logger->warning('Error. Session no longer exists. ' . $e->getMessage(), array('app' => $this->appName));
             $ex = new BadRequestException();
             $ex->setBody(implode(',', $this->request->getParams()));
             throw $ex;
         }
         switch ($command) {
             case 'sync_ops':
                 $seqHead = (string) isset($args['seq_head']) ? $args['seq_head'] : null;
                 if (!is_null($seqHead)) {
                     $ops = isset($args['client_ops']) ? $args['client_ops'] : array();
                     $op = new Db\Op();
                     $currentHead = $op->getHeadSeq($esId);
                     try {
                         $member->updateActivity($memberId);
                     } catch (\Exception $e) {
                         //Db error. Not critical
                     }
                     $response->setData($session->syncOps($memberId, $currentHead, $seqHead, $ops));
                     $inactiveMembers = $member->updateByTimeout($esId);
                     foreach ($inactiveMembers as $inactive) {
                         $op->removeCursor($esId, $inactive);
                         $op->removeMember($esId, $inactive);
                     }
                 } else {
                     // Error - no seq_head passed
                     throw new BadRequestException();
                 }
                 break;
             default:
                 $ex = new BadRequestException();
                 $ex->setBody(implode(',', $this->request->getParams()));
                 throw $ex;
         }
     } catch (BadRequestException $e) {
         $response->setStatus(Http::STATUS_BAD_REQUEST);
         $response->setData(array('err' => 'bad request:[' . $e->getBody() . ']'));
     }
     return $response;
 }
 /**
  * Creates a standard response with exception data
  * 
  * @param \Exception ex The exception to send back
  * @param string callee The calle function/route
  * @param int code HTTP Status code to return, default to Http::STATUS_INTERNAL_SERVER_ERROR
  * 
  * @return JSONResponse
  */
 private function createResponseException(\Exception $ex, $callee, $code = Http::STATUS_INTERNAL_SERVER_ERROR)
 {
     $response = new JSONResponse((object) array('type' => 'error', 'callee' => $callee, 'exception' => get_class($ex), 'message' => $ex->getMessage()));
     $response->setStatus($code);
     return $response;
 }
 /**
  * @NoAdminRequired
  * @NoSubadminRequired
  *
  * @return JSONResponse
  */
 public function create($name)
 {
     try {
         $sessionId = $this->session->getId();
     } catch (SessionNotAvailableException $ex) {
         $resp = new JSONResponse();
         $resp->setStatus(Http::STATUS_SERVICE_UNAVAILABLE);
         return $resp;
     }
     try {
         $sessionToken = $this->tokenProvider->getToken($sessionId);
         $loginName = $sessionToken->getLoginName();
         try {
             $password = $this->tokenProvider->getPassword($sessionToken, $sessionId);
         } catch (PasswordlessTokenException $ex) {
             $password = null;
         }
     } catch (InvalidTokenException $ex) {
         $resp = new JSONResponse();
         $resp->setStatus(Http::STATUS_SERVICE_UNAVAILABLE);
         return $resp;
     }
     $token = $this->generateRandomDeviceToken();
     $deviceToken = $this->tokenProvider->generateToken($token, $this->uid, $loginName, $password, $name, IToken::PERMANENT_TOKEN);
     return ['token' => $token, 'deviceToken' => $deviceToken];
 }
 /**
  * Store the document content to its origin
  * @NoAdminRequired
  */
 public function save()
 {
     $response = new JSONResponse();
     try {
         $esId = $this->request->server['HTTP_WEBODF_SESSION_ID'];
         $session = $this->loadSession($esId);
         $memberId = $this->request->server['HTTP_WEBODF_MEMBER_ID'];
         $currentMember = $this->loadMember($memberId, $esId);
         // Extra info for future usage
         // $sessionRevision = $this->request->server['HTTP_WEBODF_SESSION_REVISION'];
         //NB ouch! New document content is passed as an input stream content
         $stream = fopen('php://input', 'r');
         if (!$stream) {
             throw new \Exception('New content missing');
         }
         $content = stream_get_contents($stream);
         try {
             if ($currentMember->getIsGuest()) {
                 $file = File::getByShareToken($currentMember->getToken());
             } else {
                 $file = new File($session->getFileId());
             }
             $view = $file->getOwnerView(true);
             $path = $file->getPath(true);
         } catch (\Exception $e) {
             //File was deleted or unshared. We need to save content as new file anyway
             //Sorry, but for guests it would be lost :(
             if ($this->uid) {
                 $view = new View('/' . $this->uid . '/files');
                 $dir = \OC::$server->getConfig()->getUserValue($this->uid, 'richdocuments', 'save_path', '');
                 $path = Helper::getNewFileName($view, $dir . 'New Document.odt');
             } else {
                 throw $e;
             }
         }
         $member = new Db\Member();
         $members = $member->getActiveCollection($esId);
         $memberIds = array_map(function ($x) {
             return $x['member_id'];
         }, $members);
         // Active users except current user
         $memberCount = count($memberIds) - 1;
         if ($view->file_exists($path)) {
             $currentHash = $view->hash('sha1', $path, false);
             if (!Helper::isVersionsEnabled() && $currentHash !== $session->getGenesisHash()) {
                 // Original file was modified externally. Save to a new one
                 $path = Helper::getNewFileName($view, $path, '-conflict');
             }
             $mimetype = $view->getMimeType($path);
         } else {
             $mimetype = Storage::MIMETYPE_LIBREOFFICE_WORDPROCESSOR;
         }
         $data = Filter::write($content, $mimetype);
         if ($view->file_put_contents($path, $data['content'])) {
             // Not a last user
             if ($memberCount > 0) {
                 // Update genesis hash to prevent conflicts
                 $this->logger->debug('Update hash', ['app' => $this->appName]);
                 $session->updateGenesisHash($esId, sha1($data['content']));
             } else {
                 // Last user. Kill session data
                 Db\Session::cleanUp($esId);
             }
             $view->touch($path);
         }
         $response->setData(['status' => 'success']);
     } catch (\Exception $e) {
         $response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR);
         $response->setData([]);
         $this->logger->warning('Saving failed. Reason:' . $e->getMessage(), ['app' => $this->appName]);
     }
     return $response;
 }
Example #13
0
 public function setStatus($status)
 {
     parent::setStatus($status);
     return $this;
 }
 /**
  * Generate a new access token clients can authenticate with
  *
  * @PublicPage
  * @NoCSRFRequired
  *
  * @param string $user
  * @param string $password
  * @param string $name the name of the client
  * @return JSONResponse
  */
 public function generateToken($user, $password, $name = 'unknown client')
 {
     if (is_null($user) || is_null($password)) {
         $response = new JSONResponse();
         $response->setStatus(Http::STATUS_UNPROCESSABLE_ENTITY);
         return $response;
     }
     $loginName = $user;
     $user = $this->userManager->checkPassword($loginName, $password);
     if ($user === false) {
         $response = new JSONResponse();
         $response->setStatus(Http::STATUS_UNAUTHORIZED);
         return $response;
     }
     if ($this->twoFactorAuthManager->isTwoFactorAuthenticated($user)) {
         $resp = new JSONResponse();
         $resp->setStatus(Http::STATUS_UNAUTHORIZED);
         return $resp;
     }
     $token = $this->secureRandom->generate(128);
     $this->tokenProvider->generateToken($token, $user->getUID(), $loginName, $password, $name, IToken::PERMANENT_TOKEN);
     return ['token' => $token];
 }
 public function testCreateInvalidToken()
 {
     $name = 'Company IPhone';
     $this->session->expects($this->once())->method('getId')->will($this->returnValue('sessionid'));
     $this->tokenProvider->expects($this->once())->method('getToken')->with('sessionid')->will($this->throwException(new InvalidTokenException()));
     $expected = new JSONResponse();
     $expected->setStatus(Http::STATUS_SERVICE_UNAVAILABLE);
     $this->assertEquals($expected, $this->controller->create($name));
 }
 private function getServiceNotAvailableResponse()
 {
     $resp = new JSONResponse();
     $resp->setStatus(Http::STATUS_SERVICE_UNAVAILABLE);
     return $resp;
 }