/**
  * Process add media request
  *
  * @param ServerRequestInterface $request
  * @param ResponseInterface $response
  * @return ResponseInterface
  */
 public function mainAction(ServerRequestInterface $request, ResponseInterface $response)
 {
     $files = $request->getParsedBody()['file'];
     $newMedia = [];
     if (isset($files['newMedia'])) {
         $newMedia = (array) $files['newMedia'];
     }
     foreach ($newMedia as $media) {
         if (!empty($media['url']) && !empty($media['target'])) {
             $allowed = !empty($media['allowed']) ? GeneralUtility::trimExplode(',', $media['allowed']) : [];
             $file = $this->addMediaFromUrl($media['url'], $media['target'], $allowed);
             if ($file !== null) {
                 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $file->getName(), $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:online_media.new_media.added'), FlashMessage::OK, true);
             } else {
                 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:online_media.error.invalid_url'), $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:online_media.error.new_media.failed'), FlashMessage::ERROR, true);
             }
             $this->addFlashMessage($flashMessage);
         }
     }
     $redirect = isset($request->getParsedBody()['redirect']) ? $request->getParsedBody()['redirect'] : $request->getQueryParams()['redirect'];
     $redirect = GeneralUtility::sanitizeLocalUrl($redirect);
     if ($redirect) {
         $response = $response->withHeader('Location', GeneralUtility::locationHeaderUrl($redirect))->withStatus(303);
     }
     return $response;
 }
 /**
  * @param Request $request
  * @param Response $response
  * @param callable $next
  * @return \Psr\Http\Message\MessageInterface|HtmlResponse
  * @throws Exception
  */
 public function __invoke(Request $request, Response $response, callable $next)
 {
     //$form = new LoginForm('Login', []);
     //$form->get('submit')->setValue('Login');
     if ($request->getMethod() == 'POST') {
         $auth = new AuthenticationService();
         $query = $request->getParsedBody();
         $authAdapter = new AuthAdapter($query['login'], $query['password'], $this->authConfig);
         $result = $auth->authenticate($authAdapter);
         if (!$result->isValid()) {
             //$response->getBody()->write("Not valid authentication\n");
             //return $response->withStatus(403)->withHeader("Content-type", 'text/html');
             throw new Exception("Not valid authentication\n", 403);
         } else {
             if ($request->getUri()->getPath() === '/auth') {
                 $render = $this->template->render('app::homepage');
                 $query = $request->getParsedBody();
                 $query['view']['render'] = $render;
                 $query['view']['code'] = 200;
                 $request = $request->withParsedBody($query);
             }
             return $next($request, $response);
         }
     } else {
         $render = $this->template->render('app::login', ['error' => null]);
         $query = $request->getParsedBody();
         $query['view']['render'] = $render;
         $query['view']['code'] = 200;
         $request = $request->withParsedBody($query);
         return $next($request, $response);
     }
 }
 /**
  * Index action shows install tool / step installer or redirect to action to enable install tool
  *
  * @param ServerRequestInterface $request
  * @param ResponseInterface $response
  * @return ResponseInterface
  */
 public function index(ServerRequestInterface $request, ResponseInterface $response)
 {
     /** @var EnableFileService $enableFileService */
     $enableFileService = GeneralUtility::makeInstance(EnableFileService::class);
     /** @var AbstractFormProtection $formProtection */
     $formProtection = FormProtectionFactory::get();
     if ($enableFileService->checkInstallToolEnableFile()) {
         // Install tool is open and valid, redirect to it
         $response = $response->withStatus(303)->withHeader('Location', 'sysext/install/Start/Install.php?install[context]=backend');
     } elseif ($request->getMethod() === 'POST' && $request->getParsedBody()['action'] === 'enableInstallTool') {
         // Request to open the install tool
         $installToolEnableToken = $request->getParsedBody()['installToolEnableToken'];
         if (!$formProtection->validateToken($installToolEnableToken, 'installTool')) {
             throw new \RuntimeException('Given form token was not valid', 1369161225);
         }
         $enableFileService->createInstallToolEnableFile();
         // Install tool is open and valid, redirect to it
         $response = $response->withStatus(303)->withHeader('Location', 'sysext/install/Start/Install.php?install[context]=backend');
     } else {
         // Show the "create enable install tool" button
         /** @var StandaloneView $view */
         $view = GeneralUtility::makeInstance(StandaloneView::class);
         $view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName('EXT:install/Resources/Private/Templates/BackendModule/ShowEnableInstallToolButton.html'));
         $token = $formProtection->generateToken('installTool');
         $view->assign('installToolEnableToken', $token);
         /** @var ModuleTemplate $moduleTemplate */
         $moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class);
         $cssFile = 'EXT:install/Resources/Public/Css/BackendModule/ShowEnableInstallToolButton.css';
         $cssFile = GeneralUtility::getFileAbsFileName($cssFile);
         $moduleTemplate->getPageRenderer()->addCssFile(PathUtility::getAbsoluteWebPath($cssFile));
         $moduleTemplate->setContent($view->render());
         $response->getBody()->write($moduleTemplate->renderContent());
     }
     return $response;
 }
 /**
  * @param Request $request
  * @return JsonResponse|EmptyResponse
  */
 public function handle(Request $request)
 {
     $actor = $request->getAttribute('actor');
     $Referer = $request->getHeader('Referer');
     $params = array_only($request->getParsedBody(), ['identification', 'password']);
     $response = $this->apiClient->send(TokenController::class, $actor, [], $params);
     if ($response->getStatusCode() === 200) {
         $data = json_decode($response->getBody());
         $session = $request->getAttribute('session');
         $this->authenticator->logIn($session, $data->userId);
         $token = AccessToken::find($data->token);
         event(new UserLoggedIn($this->users->findOrFail($data->userId), $token));
         $response = FigResponseCookies::set($response, SetCookie::create("lastLoginName")->withValue($request->getParsedBody()['identification'])->withPath('/'));
         $response = $this->rememberer->remember($response, $token);
     } elseif ($response->getStatusCode() === 401) {
         $responseNew = $this->apiClient->send(PingxxTokenController::class, $actor, [], $params);
         if ($responseNew->getStatusCode() === 200) {
             $data = json_decode($responseNew->getBody());
             $session = $request->getAttribute('session');
             $this->authenticator->logIn($session, $data->userId);
             $token = AccessToken::find($data->token);
             event(new UserLoggedIn($this->users->findOrFail($data->userId), $token));
             $responseNew = FigResponseCookies::set($responseNew, SetCookie::create("lastLoginName")->withValue($request->getParsedBody()['identification'])->withPath('/')->withDomain('dashboard.pingxx.com'));
             $responseNew = $this->rememberer->remember($responseNew, $token);
             return $responseNew;
         } else {
             return $response;
         }
     }
     return $response;
 }
示例#5
0
 /**
  * @param string $name
  * @param array  $options
  *
  * @return bool
  */
 public function isValid($name, array $options = [])
 {
     $options += ['referer' => null, 'token' => null];
     if (null === $options['token']) {
         $params = $this->request->getParsedBody();
         if (!isset($params[$name])) {
             $this->invalidate();
             return false;
         } else {
             $options['token'] = $params[$name];
         }
     }
     $error = false;
     $name .= $options['token'];
     $config = array_get([self::TOKEN_KEY, $name], $this->storage, []);
     $time = isset($config['expire']) ? $config['expire'] : 0;
     if (time() > $time) {
         $error = true;
     }
     if (!$error && null !== $options['referer']) {
         $params = $this->request->getServerParams();
         if (!isset($params['HTTP_REFERER']) || $params['HTTP_REFERER'] !== $options['referer']) {
             $error = true;
         }
     }
     $regenerate = array_key_exists('regenerate', $config) ? $config['regenerate'] : false;
     if ($error || !$regenerate) {
         array_remove([self::TOKEN_KEY, $name], $this->storage);
     } elseif ($regenerate) {
         $config['expire'] = time() + $config['time'];
         array_set([self::TOKEN_KEY, $name], $config, $this->storage);
     }
     $this->invalidate();
     return !$error;
 }
示例#6
0
文件: Util.php 项目: tonis-io/oauth2
 /**
  * Converts a PSR-7 request into an OAuth2 request.
  *
  * @param ServerRequestInterface $psrRequest
  * @return Request
  */
 public static function convertRequestFromPsr7(ServerRequestInterface $psrRequest)
 {
     $headers = [];
     foreach ($psrRequest->getHeaders() as $header => $value) {
         $headers[$header] = implode(';', $value);
     }
     return new Request($psrRequest->getQueryParams(), is_array($psrRequest->getParsedBody()) ? $psrRequest->getParsedBody() : [], $psrRequest->getAttributes(), $psrRequest->getCookieParams(), self::getFiles($psrRequest->getUploadedFiles()), $psrRequest->getServerParams(), $psrRequest->getBody()->__toString(), $headers);
 }
 /**
  * @param ServerRequestInterface $request
  * @param RouterInterface $router
  */
 public function __construct(ServerRequestInterface $request, RouterInterface $router)
 {
     $this->request = $request;
     parent::__construct($this);
     $this->parameters = $this->parseIncomingParams();
     $this->parameters = array_merge($this->parameters, $this->request->getParsedBody(), $this->getParsedAttributes($request, $router), $this->getQueryParams(), $this->request->getUploadedFiles());
     $this->parsedBody = array_merge(parent::getParsedBody(), $this->parameters);
 }
 /**
  * Get the data to be serialized and assigned to the response document.
  *
  * @param ServerRequestInterface $request
  * @param Document               $document
  * @return mixed
  */
 protected function data(ServerRequestInterface $request, Document $document)
 {
     $title = Arr::get($request->getParsedBody(), 'title');
     $start_post_id = Arr::get($request->getParsedBody(), 'start_post_id');
     $end_post_id = Arr::get($request->getParsedBody(), 'end_post_id');
     $actor = $request->getAttribute('actor');
     return $this->bus->dispatch(new SplitDiscussion($title, $start_post_id, $end_post_id, $actor));
 }
 /**
  * The main dispatcher function. Collect data and prepare HTML output.
  *
  * @param ServerRequestInterface $request
  * @param ResponseInterface $response
  * @return ResponseInterface
  */
 public function getHelpAction(ServerRequestInterface $request, ResponseInterface $response)
 {
     $params = isset($request->getParsedBody()['params']) ? $request->getParsedBody()['params'] : $request->getQueryParams()['params'];
     if ($params['action'] === 'getContextHelp') {
         $result = $this->getContextHelp($params['table'], $params['field']);
         $response->getBody()->write(json_encode(['title' => $result['title'], 'content' => $result['description'], 'link' => $result['moreInfo']]));
     }
     return $response;
 }
 /**
  * Renders/Echoes the ajax output
  *
  * @param ServerRequestInterface $request
  * @param ResponseInterface $response
  * @return ResponseInterface|NULL
  * @throws \InvalidArgumentException
  */
 public function processRequest(ServerRequestInterface $request, ResponseInterface $response)
 {
     $action = isset($request->getParsedBody()['action']) ? $request->getParsedBody()['action'] : (isset($request->getQueryParams()['action']) ? $request->getQueryParams()['action'] : '');
     if (!in_array($action, array('route', 'getAPI'), true)) {
         return null;
     }
     $this->routeAction($action);
     return $this->ajaxObject->render();
 }
示例#11
0
 /**
  * Validates CSRF token in given PSR-7 Request instance.
  *
  * @param ServerRequestInterface $request PSR-7 Request instance.
  *
  * @throws \Students\Exception\BadRequestException If CSRF check failed.
  *
  * @return boolean True if CSRF check was successful.
  */
 public function validateCsrfToken(ServerRequestInterface $request)
 {
     $formToken = isset($request->getParsedBody()['csrf']) ? strval($request->getParsedBody()['csrf']) : '';
     $cookie = FigRequestCookies::get($request, 'csrf');
     if ($cookie->getValue() !== $formToken) {
         throw new BadRequestException($request);
     }
     return true;
 }
 /**
  * Validates the request
  * @param ServerRequestInterface $requestInterface
  * @return bool|ValidationResult
  */
 public function validate(ServerRequestInterface $requestInterface)
 {
     $this->decoratedRequest = new RequestValidator($requestInterface, $this->router);
     $validatorProvider = $this->getValidatorObject($this->decoratedRequest);
     if ($validatorProvider == null) {
         return true;
     } else {
         return new ValidationResult($this->decoratedRequest->getParsedBody(), $validatorProvider, $this->entityManagerInterface, $this->decoratedRequest);
     }
 }
示例#13
0
 public function __construct(ServerRequestInterface $request)
 {
     $this->request = $request;
     if ($request->getParsedBody()) {
         $this->data = json_decode(json_encode($request->getParsedBody()), true);
     } else {
         $this->data = json_decode($request->getBody(), true);
     }
     $this->validateSchema();
 }
示例#14
0
 /**
  * Injects the request object for the current request or subrequest
  * As this controller goes only through the main() method, it is rather simple for now
  * This will be split up in an abstract controller once proper routing/dispatcher is in place.
  *
  * @param ServerRequestInterface $request the current request
  * @param ResponseInterface $response
  * @return ResponseInterface the response with the content
  */
 public function logoutAction(ServerRequestInterface $request, ResponseInterface $response)
 {
     $this->logout();
     $redirectUrl = isset($request->getParsedBody()['redirect']) ? $request->getParsedBody()['redirect'] : $request->getQueryParams()['redirect'];
     $redirectUrl = GeneralUtility::sanitizeLocalUrl($redirectUrl);
     if (empty($redirectUrl)) {
         /** @var \TYPO3\CMS\Backend\Routing\UriBuilder $uriBuilder */
         $uriBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\UriBuilder::class);
         $redirectUrl = (string) $uriBuilder->buildUriFromRoute('login', array(), $uriBuilder::ABSOLUTE_URL);
     }
     return $response->withStatus(303)->withHeader('Location', GeneralUtility::locationHeaderUrl($redirectUrl));
 }
示例#15
0
 /**
  * Saves the sorting order of tasks in the backend user's uc
  *
  * @param ServerRequestInterface $request
  * @param ResponseInterface $response
  * @return ResponseInterface
  */
 public function saveSortingState(ServerRequestInterface $request, ResponseInterface $response)
 {
     $sort = array();
     $data = isset($request->getParsedBody()['data']) ? $request->getParsedBody()['data'] : $request->getQueryParams()['data'];
     $items = explode('&', $data);
     foreach ($items as $item) {
         $sort[] = substr($item, 12);
     }
     $this->getBackendUserAuthentication()->uc['taskcenter']['sorting'] = serialize($sort);
     $this->getBackendUserAuthentication()->writeUC();
     return $response;
 }
示例#16
0
 /**
  * Checks if the request token is valid. This is checked to see if the route is really
  * created by the same instance. Should be called for all routes in the backend except
  * for the ones that don't require a login.
  *
  * @param \Psr\Http\Message\ServerRequestInterface $request
  * @return bool
  * @see \TYPO3\CMS\Backend\Routing\UriBuilder where the token is generated.
  */
 protected function isValidRequest($request)
 {
     $route = $request->getAttribute('route');
     if ($route->getOption('access') === 'public') {
         return true;
     } elseif ($route->getOption('ajax')) {
         $token = (string) (isset($request->getParsedBody()['ajaxToken']) ? $request->getParsedBody()['ajaxToken'] : $request->getQueryParams()['ajaxToken']);
         return $this->getFormProtection()->validateToken($token, 'ajaxCall', $route->getOption('_identifier'));
     } else {
         $token = (string) (isset($request->getParsedBody()['token']) ? $request->getParsedBody()['token'] : $request->getQueryParams()['token']);
         return $this->getFormProtection()->validateToken($token, 'route', $route->getOption('_identifier'));
     }
 }
 /**
  * Do the actual login, and procede to site or force back to login page
  * 
  * @param  \Psr\Http\Message\ServerRequestInterface $request  PSR7 request
  * @param  \Psr\Http\Message\ResponseInterface      $response PSR7 response
  * @param  array                                    $args     Args passed in from URL
  * @return \Psr\Http\Message\ResponseInterface                Final PSR7 response
  */
 public function login_action($request, $response, $args)
 {
     $credentials = ['email' => $request->getParsedBody()['email'], 'password' => $request->getParsedBody()['password']];
     try {
         $user = $this->sentinel->authenticate($credentials, true);
     } catch (Exception $e) {
         return $response->withRedirect($this->router->pathFor('login'));
     }
     if ($user === false) {
         return $response->withRedirect($this->router->pathFor('login'));
     }
     return $response->withRedirect($this->router->pathFor('list-resources'));
 }
示例#18
0
 /**
  * {@inheritdoc}
  */
 protected function data(ServerRequestInterface $request, Document $document)
 {
     $id = array_get($request->getQueryParams(), 'id');
     $actor = $request->getAttribute('actor');
     $data = array_get($request->getParsedBody(), 'data', []);
     // Require the user's current password if they are attempting to change
     // their own email address.
     if (isset($data['attributes']['email']) && $actor->id == $id) {
         $password = array_get($request->getParsedBody(), 'meta.password');
         if (!$actor->checkPassword($password)) {
             throw new PermissionDeniedException();
         }
     }
     return $this->bus->dispatch(new EditUser($id, $actor, $data));
 }
示例#19
0
 public function getKohanaRequest(ServerRequestInterface $request)
 {
     parse_str($request->getUri()->getQuery(), $query);
     $kohanaRequest = new Request((string) $request->getUri());
     $kohanaRequest->method($request->getMethod());
     $kohanaRequest->body((string) $request->getBody());
     $kohanaRequest->query($query);
     if ($request->getParsedBody()) {
         $kohanaRequest->post($request->getParsedBody());
     }
     if ($this->current) {
         $kohanaRequest->referrer((string) $this->current->getUri());
     }
     return $kohanaRequest;
 }
 /**
  * @interitdoc
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     $payload = null;
     $messageName = 'UNKNOWN';
     try {
         $payload = $request->getParsedBody();
         if (is_array($payload) && isset($payload['message_name'])) {
             $messageName = $payload['message_name'];
         }
         MessageDataAssertion::assert($payload);
         $message = $this->messageFactory->createMessageFromArray($payload['message_name'], $payload);
         switch ($message->messageType()) {
             case Message::TYPE_COMMAND:
                 $this->commandBus->dispatch($message);
                 return $response->withStatus(Middleware::STATUS_CODE_ACCEPTED);
             case Message::TYPE_EVENT:
                 $this->eventBus->dispatch($message);
                 return $response->withStatus(Middleware::STATUS_CODE_ACCEPTED);
             case Message::TYPE_QUERY:
                 return $this->responseStrategy->fromPromise($this->queryBus->dispatch($message));
             default:
                 return $next($request, $response, new RuntimeException(sprintf('Invalid message type "%s" for message "%s".', $message->messageType(), $messageName), Middleware::STATUS_CODE_BAD_REQUEST));
         }
     } catch (\Assert\InvalidArgumentException $e) {
         return $next($request, $response, new RuntimeException($e->getMessage(), Middleware::STATUS_CODE_BAD_REQUEST, $e));
     } catch (\Exception $e) {
         return $next($request, $response, new RuntimeException(sprintf('An error occurred during dispatching of message "%s"', $messageName), Middleware::STATUS_CODE_INTERNAL_SERVER_ERROR, $e));
     }
 }
示例#21
0
 public function it_errors_on_invalid_data_in_request(ServerRequestInterface $httpRequest)
 {
     $post = ['data' => ['type' => 'pages', 'attributes' => ['title' => 'Long title', 'slug' => 'long_title', 'short_title' => '', 'parent_uuid' => null, 'sort_order' => 42, 'status' => 'concept']]];
     $httpRequest->getHeaderLine('Accept')->willReturn('application/json');
     $httpRequest->getParsedBody()->willReturn($post);
     $this->shouldThrow(ValidationFailedException::class)->duringParseHttpRequest($httpRequest, []);
 }
示例#22
0
 public function __construct(ServerRequestInterface $request)
 {
     $this->body = $request->getParsedBody();
     foreach ($request->getQueryParams() as $param => $value) {
         switch ($param) {
             case 'sort':
                 $parts = explode(',', $value);
                 foreach ($parts as $part) {
                     preg_match_all('/^(\\-)?([\\w]+)$/', $part, $matches);
                     if (empty($matches[0])) {
                         throw new \Exception('Invalid sort format.', 1);
                     }
                     $name = $matches[2][0];
                     $order = $matches[1][0];
                     $this->sort[$name] = $order;
                 }
                 break;
             case 'pageSize':
             case 'pageNumber':
                 $this->{$param} = $value;
                 break;
             default:
                 $this->userFilters[$param] = $value;
         }
     }
 }
示例#23
0
 /**
  * Sets the TYPO3 Backend context to a certain workspace,
  * called by the Backend toolbar menu
  *
  * @param ServerRequestInterface $request
  * @param ResponseInterface $response
  * @return ResponseInterface
  */
 public function switchWorkspaceAction(ServerRequestInterface $request, ResponseInterface $response)
 {
     $parsedBody = $request->getParsedBody();
     $queryParams = $request->getQueryParams();
     $workspaceId = (int) (isset($parsedBody['workspaceId']) ? $parsedBody['workspaceId'] : $queryParams['workspaceId']);
     $pageId = (int) (isset($parsedBody['pageId']) ? $parsedBody['pageId'] : $queryParams['pageId']);
     $finalPageUid = 0;
     $originalPageId = $pageId;
     $this->getBackendUser()->setWorkspace($workspaceId);
     while ($pageId) {
         $page = BackendUtility::getRecordWSOL('pages', $pageId, '*', ' AND pages.t3ver_wsid IN (0, ' . $workspaceId . ')');
         if ($page) {
             if ($this->getBackendUser()->doesUserHaveAccess($page, 1)) {
                 break;
             }
         } else {
             $page = BackendUtility::getRecord('pages', $pageId);
         }
         $pageId = $page['pid'];
     }
     if (isset($page['uid'])) {
         $finalPageUid = (int) $page['uid'];
     }
     $ajaxResponse = ['title' => \TYPO3\CMS\Workspaces\Service\WorkspaceService::getWorkspaceTitle($workspaceId), 'workspaceId' => $workspaceId, 'pageId' => $finalPageUid && $originalPageId == $finalPageUid ? null : $finalPageUid];
     $response->getBody()->write(json_encode($ajaxResponse));
     return $response;
 }
 /**
  * Constructor
  *
  * @param string $action Type of action to validate
  * @param ServerRequestInterface $request Request Http
  * @param ContainerInterface $container Dependency Injection
  */
 public function __construct($action, ServerRequestInterface $request, ContainerInterface $container)
 {
     $this->action = $action;
     $this->idUser = $request->getAttribute('id');
     $this->data = $request->getParsedBody();
     $this->entityManager = $container->get('EntityManager');
 }
示例#25
0
 public function adminEditSidecarPOST(Request $request, Response $response, $args)
 {
     // unpack json body
     $json = $request->getParsedBody();
     //        var_dump($json);
     $service = new SearchService();
     $return = 'return';
     $unit = 'disk:default';
     $terms = ['uuid:' . $json['uuid']];
     $asset = $service->search(compact('return', 'unit', 'terms'));
     $asset = $asset[$terms[0]][$json['uuid']];
     $path = 'default://' . $asset->parent()->parent()->name() . DS . $asset->parent()->name() . DS . $json['uuid'] . '.png';
     $this->logger->info(__CLASS__ . '::' . __FUNCTION__ . ': BUILT path: ' . $path);
     $assignedProps = $asset->assignedProperties();
     // this will reload the asset from json file
     // create this before we attempt to overwrite the props
     $assetService = new AssetService($asset, ['path' => $path, 'filename' => $json['uuid']]);
     $this->logger->info(__CLASS__ . '::' . __FUNCTION__ . ': asset service is setup and loaded');
     unset($json['uuid']);
     // overwrite each edited (submitted) prop
     // readonly props are not submittable
     foreach ($json as $key => $value) {
         $assignedProps->{'properties'}->{$key} = $value;
     }
     $asset->assignedProperties($assignedProps);
     //        $this->logger->info(__CLASS__.'::'.__FUNCTION__.': asset to json: '.$asset->toJson());
     $resp = [];
     // commit changes to file
     if ($assetService->storeJsonData()) {
         $resp['response'] = 'updated';
     } else {
         $resp['response'] = 'failed';
     }
     return $response->getBody()->write(json_encode($resp));
 }
示例#26
0
 /**
  * Auth/Login route for logging a user in.
  *
  * @param ServerRequestInterface ServerRequestInterface $request  PSR-7 standard for receiving client request
  * @param ResponseInterface      ResponseInterface      $response PSR-& standard for sending server response
  *
  * @return ResponseInterface HTTP response of client request
  */
 public function login(ServerRequestInterface $request, ResponseInterface $response)
 {
     $data = $request->getParsedBody();
     //Check to make sure user sends username and password
     if (isset($data['username'], $data['password'])) {
         //Authenticate that username and password are correct
         $user = User::auth($data['username'], $data['password']);
         //Check if username exits
         if ((bool) $user) {
             //Ensures user is not logged out from other device
             $user->jit = $user->jit == null ? rand(1000, 999999999) : $user->jit;
             //Generate token
             $token = $this->buildToken($user->jit, $user->id, $user->username);
             $user->save();
             $message = ['token' => $token];
         } else {
             //Message when username or password is incorrect
             $response = $response->withStatus(401);
             $message = ['message' => 'username or password incorrect'];
         }
     } else {
         $response = $response->withStatus(400);
         $message = ['message' => 'Username or password not set'];
     }
     $response->getBody()->write(json_encode($message));
     return $response;
 }
示例#27
0
 /**
  * @param ServerRequestInterface $request
  * @param ResponseInterface      $response
  * @param callable|null          $next
  *
  * @return HtmlResponse
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
 {
     /* @var \PSR7Session\Session\SessionInterface $session */
     $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);
     // Generate csrf token
     if (!$session->get('csrf')) {
         $session->set('csrf', md5(uniqid(rand(), true)));
     }
     // Generate form and inject csrf token
     $form = FormFactory::fromHtml($this->template->render('app::contact-form', ['token' => $session->get('csrf')]));
     // Get request data
     $data = $request->getParsedBody() ?: [];
     if ($request->getMethod() !== 'POST') {
         // Display form
         return new HtmlResponse($this->template->render('app::contact', ['form' => $form->asString()]), 200);
     }
     // Validate form
     $validationResult = $form->validate($data);
     if (!$validationResult->isValid()) {
         // Display form and inject error messages and submitted values
         return new HtmlResponse($this->template->render('app::contact', ['form' => $form->asString($validationResult)]), 200);
     }
     // Create the message
     $message = Swift_Message::newInstance()->setFrom($this->config['from'])->setReplyTo($data['email'], $data['name'])->setTo($this->config['to'])->setSubject('[xtreamwayz-contact] ' . $data['subject'])->setBody($data['body']);
     if ($this->config['transport']['debug'] !== true) {
         $this->mailer->send($message);
     }
     // Display thank you page
     return new HtmlResponse($this->template->render('app::contact-thank-you'), 200);
 }
 /**
  * {@inheritdoc}
  */
 protected function data(ServerRequestInterface $request, Document $document)
 {
     $id = array_get($request->getQueryParams(), 'id');
     $actor = $request->getAttribute('actor');
     $data = array_get($request->getParsedBody(), 'data');
     return $this->bus->dispatch(new EditLink($id, $actor, $data));
 }
 protected function getSourceParams(ServerRequestInterface $request)
 {
     $request_method = $request->getServerParams()['REQUEST_METHOD'];
     switch (strtolower($request_method)) {
         case 'options':
         case 'head':
         case 'get':
             return array_merge($request->getParsedBody(), $request->getQueryParams());
         case 'post':
         case 'put':
         case 'delete':
             return array_merge($request->getQueryParams(), $request->getParsedBody());
         default:
             return [];
     }
 }
 /**
  * Executes the modules configured via Extbase
  *
  * @param string $moduleName
  * @return Response A PSR-7 response object
  * @throws \RuntimeException
  */
 protected function dispatchModule($moduleName)
 {
     $moduleConfiguration = $this->getModuleConfiguration($moduleName);
     // Check permissions and exit if the user has no permission for entry
     $this->backendUserAuthentication->modAccess($moduleConfiguration, true);
     $id = isset($this->request->getQueryParams()['id']) ? $this->request->getQueryParams()['id'] : $this->request->getParsedBody()['id'];
     if ($id && MathUtility::canBeInterpretedAsInteger($id)) {
         // Check page access
         $permClause = $this->backendUserAuthentication->getPagePermsClause(true);
         $access = is_array(BackendUtility::readPageAccess((int) $id, $permClause));
         if (!$access) {
             throw new \RuntimeException('You don\'t have access to this page', 1289917924);
         }
     }
     /** @var Response $response */
     $response = GeneralUtility::makeInstance(Response::class);
     // Use Core Dispatching
     if (isset($moduleConfiguration['routeTarget'])) {
         $dispatcher = GeneralUtility::makeInstance(Dispatcher::class);
         $this->request = $this->request->withAttribute('target', $moduleConfiguration['routeTarget']);
         $response = $dispatcher->dispatch($this->request, $response);
     } else {
         // extbase module
         $configuration = array('extensionName' => $moduleConfiguration['extensionName'], 'pluginName' => $moduleName);
         if (isset($moduleConfiguration['vendorName'])) {
             $configuration['vendorName'] = $moduleConfiguration['vendorName'];
         }
         // Run Extbase
         $bootstrap = GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Core\Bootstrap::class);
         $content = $bootstrap->run('', $configuration);
         $response->getBody()->write($content);
     }
     return $response;
 }