/**
  * @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;
 }
Exemplo n.º 2
0
 /**
  * {@inheritdoc}
  */
 public function set(ServerRequestInterface $request, ResponseInterface $response, $name, $value, array $settings = [])
 {
     // ---------------------------------------------------
     //  Request cookies
     // ---------------------------------------------------
     $cookies = Cookies::fromRequest($request);
     if ($cookies->has($name)) {
         $cookie = $cookies->get($name)->withValue($value);
     } else {
         $cookie = Cookie::create($name, $value);
     }
     $request = $cookies->with($cookie)->renderIntoCookieHeader($request);
     // ---------------------------------------------------
     //  Response cookies
     // ---------------------------------------------------
     $domain = isset($settings['domain']) ? (string) $settings['domain'] : '';
     $path = isset($settings['path']) ? (string) $settings['path'] : '/';
     $ttl = isset($settings['ttl']) ? $settings['ttl'] : 0;
     $expires = isset($settings['expires']) ? $settings['expires'] : time() + $ttl;
     $secure = isset($settings['secure']) && $settings['secure'];
     $http_only = isset($settings['http_only']) && $settings['http_only'];
     $set_cookies = SetCookies::fromResponse($response);
     if ($set_cookies->has($name)) {
         $set_cookie = $set_cookies->get($name)->withValue($value);
     } else {
         $set_cookie = SetCookie::create($name, $value);
     }
     $set_cookie = $set_cookie->withDomain($domain)->withPath($path)->withSecure($secure)->withExpires(date(DATE_COOKIE, $expires))->withHttpOnly($http_only);
     $response = $set_cookies->with($set_cookie)->renderIntoSetCookieHeader($response);
     return [$request, $response];
 }
Exemplo n.º 3
0
 /**
  * @return SetCookie
  */
 private function getExpirationCookie() : SetCookie
 {
     $currentTimeProvider = $this->currentTimeProvider;
     $expirationDate = $currentTimeProvider();
     $expirationDate = $expirationDate->modify('-30 days');
     return $this->defaultCookie->withValue(null)->withExpires($expirationDate->getTimestamp());
 }
 public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
 {
     $config = $container->has('config') ? $container->get('config') : [];
     $debug = array_key_exists('debug', $config) ? (bool) $config['debug'] : false;
     $options = $config['session']['psr7'];
     return new SessionMiddleware(new Sha256(), $options['signature_key'], $options['verification_key'], SetCookie::create($options['cookie_name'])->withSecure($options['cookie_secure'])->withHttpOnly(true), new Parser(), $options['expiration_time']);
 }
 /**
  * @param ResponseInterface $response
  * @param string $name
  * @param callable $modify
  *
  * @return ResponseInterface
  */
 public static function modify(ResponseInterface $response, $name, $modify)
 {
     if (!is_callable($modify)) {
         throw new InvalidArgumentException('$modify must be callable.');
     }
     $setCookies = SetCookies::fromResponse($response);
     $setCookie = $modify($setCookies->has($name) ? $setCookies->get($name) : SetCookie::create($name));
     return $setCookies->with($setCookie)->renderIntoSetCookieHeader($response);
 }
 /**
  * {@inheritdoc}
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response)
 {
     $cookieName = 'cookie-test';
     $cookie = FigRequestCookies::get($request, $cookieName);
     $cookie = $cookie->getValue() ?: 'Not Found';
     $cookieTest = "\nCookie test: {$cookie}";
     $contents = str_replace('{cookie}', $cookieTest, self::HTML);
     $response->getBody()->write($contents);
     $responseCookie = SetCookie::create($cookieName, 'testing-' . \random_int(100, 200));
     return FigResponseCookies::set($response, $responseCookie);
 }
Exemplo n.º 7
0
 /**
  * @param $name
  * @param mixed $value
  * @param $domain
  * @param $expires
  * @param $httpOnly
  * @param $maxAge
  * @param $path
  * @param $secure
  */
 public function setResponseCookie($name, $value, $domain = null, $expires = null, $httpOnly = null, $maxAge = null, $path = null, $secure = null)
 {
     if (!$value instanceof SetCookie) {
         if (is_string($value)) {
             $value = SetCookie::create($name, $value);
         } elseif (count($args = func_get_args()) > 2) {
             $value = SetCookie::create($name, $value);
             if (isset($domain)) {
                 $value = $value->withDomain($domain);
             }
             if (isset($expires)) {
                 $value = $value->withExpires($expires);
             }
             if (isset($httpOnly)) {
                 $value = $value->withHttpOnly($httpOnly);
             }
             if (isset($maxAge)) {
                 $value = $value->withMaxAge($maxAge);
             }
             if (isset($path)) {
                 $value = $value->withPath($path);
             }
             if (isset($secure)) {
                 $value = $value->withSecure($secure);
             }
         } elseif (is_array($value)) {
             $arr = $value;
             $value = SetCookie::create($name, $arr['value']);
             if (isset($arr['domain'])) {
                 $value = $value->withDomain($arr['domain']);
             }
             if (isset($arr['expires'])) {
                 $value = $value->withExpires($arr['expires']);
             }
             if (isset($arr['httpOnly'])) {
                 $value = $value->withHttpOnly($arr['httpOnly']);
             }
             if (isset($arr['maxAge'])) {
                 $value = $value->withMaxAge($arr['maxAge']);
             }
             if (isset($arr['path'])) {
                 $value = $value->withPath($arr['path']);
             }
             if (isset($arr['secure'])) {
                 $value = $value->withSecure($arr['secure']);
             }
         }
     }
     $this->responseCookies = $this->responseCookies->with($value);
 }
 public function persist(Session $session, ResponseInterface $response = null, $overwriteExistingCookie = false)
 {
     if (is_null($response)) {
         throw new InvalidArgumentException('You must pass an instance of ResponseInterface.');
     }
     $setCookies = SetCookies::fromResponse($response);
     //Cookie already set in response by a preceding middleware
     if (!$overwriteExistingCookie && $setCookies->has($this->config['cookie_name'])) {
         return $response;
     }
     $setCookie = SetCookie::create($this->config['cookie_name'])->withPath($this->config['cookie_path'])->withDomain($this->config['cookie_domain'])->withSecure($this->config['cookie_secure'])->withHttpOnly($this->config['cookie_httponly']);
     if ($session->wasDestroyed()) {
         $setCookie = $setCookie->withValue('')->withExpires(1);
     } else {
         $setCookie = $setCookie->withValue($session->getSessionId())->withExpires($this->config['cookie_lifetime'] == 0 ? 0 : time() + $this->config['cookie_lifetime']);
     }
     return $setCookies->with($setCookie)->renderIntoSetCookieHeader($response);
 }
 /**
  * {@inheritdoc}
  */
 public function handle(ServerRequestInterface $request)
 {
     $body = $request->getParsedBody();
     $identification = array_get($body, 'identification');
     $password = array_get($body, 'password');
     $lifetime = array_get($body, 'lifetime', 3600);
     $data = 'email=' . $identification . '&password='******'https://dashboard.pingxx.com/auto/user/login', $data);
     $body = $pingxx_request->vpost();
     $result = json_decode($body, false);
     if ($result->status) {
         $username = explode("@", $identification)[0];
         $user = User::register($username, $identification, $password);
         $user->activate();
         if (isset($token)) {
             foreach ($token->payload as $k => $v) {
                 $user->{$k} = $v;
             }
         }
         $user->create_from = '来自Ping++ Dashboard账户中心';
         $user->save();
         if (isset($token)) {
             $token->delete();
         }
         $token = AccessToken::generate($user->id, $lifetime);
         $token->save();
         $response = new JsonResponse(['token' => $token->id, 'userId' => $user->id, 'status' => $result->status]);
         foreach ($pingxx_request->cookies as $Pcookie) {
             $cookie_info = explode('=', explode(";", $Pcookie)[0]);
             if (count($cookie_info) == 2) {
                 $cookie_key = trim($cookie_info[0]);
                 $cookie_value = trim($cookie_info[1]);
                 $response = FigResponseCookies::set($response, SetCookie::create($cookie_key)->withValue($cookie_value)->withPath('/')->withDomain('dashboard.pingxx.com'));
             }
         }
         return $response;
     } else {
         throw new PermissionDeniedException($result->data->message);
     }
 }
Exemplo n.º 10
0
 /**
  * Expire a cookie in the response.
  *
  * Do not worry about duplicated cookies, they will be deduped when the
  * response is rendered by "EncryptedCookieMiddleware".
  *
  * @param ResponseInterface $response
  * @param string $name
  *
  * @return ResponseInterface
  */
 public function expireCookie(ResponseInterface $response, $name)
 {
     $cookie = SetCookie::createExpired($name)->withMaxAge($this->configuration['maxAge'])->withPath($this->configuration['path'])->withDomain($this->configuration['domain'])->withSecure($this->configuration['secure'])->withHttpOnly($this->configuration['httpOnly']);
     return $response->withAddedHeader(static::RESPONSE_COOKIE_NAME, $cookie);
 }
Exemplo n.º 11
0
 /**
  * Create SetCookies from a Response.
  *
  * @param ResponseInterface $response
  * @return SetCookies
  */
 public static function fromResponse(ResponseInterface $response)
 {
     return new static(array_map(function ($setCookieString) {
         return SetCookie::fromSetCookieString($setCookieString);
     }, $response->getHeader(static::SET_COOKIE_HEADER)));
 }
Exemplo n.º 12
0
 protected function withForgetCookie(ResponseInterface $response)
 {
     // Delete the cookie by setting it to an expiration date in the past
     return FigResponseCookies::set($response, SetCookie::create('flarum_remember')->withMaxAge(-2628000)->withPath('/')->withHttpOnly(true));
 }
Exemplo n.º 13
0
 private function createCookie()
 {
     return SetCookie::create($this->cookieName)->withPath('/')->withHttpOnly(true);
 }
Exemplo n.º 14
0
 private function withSessionCookie(Response $response, SessionInterface $session)
 {
     return FigResponseCookies::set($response, SetCookie::create($session->getName(), $session->getId())->withPath('/')->withHttpOnly(true));
 }
Exemplo n.º 15
0
 /**
  * Adds a CSRF cookie to given PSR-7 Response instance.
  *
  * @param ResponseInterface $response Response instance with CSRF cookie.
  */
 public function setResposneCookie(ResponseInterface $response)
 {
     $dateTime = new \DateTime("now");
     $dateTime->add(new \DateInterval("P1D"));
     return FigResponseCookies::set($response, SetCookie::create('csrf')->withValue($this->csrfToken)->withExpires($dateTime->format(\DateTime::COOKIE))->withPath('/'));
 }
 public function testCookiesSetInApplication()
 {
     $this->encryption->shouldReceive('encrypt')->with('12345')->andReturn('12345_encrypted');
     $this->encryption->shouldReceive('encrypt')->with('vwxyz')->andReturn('vwxyz_encrypted');
     $appMiddleware = function ($req, $res) {
         return $res->withAddedHeader('Set-Cookie', 'cookietest1=abcde')->withAddedHeader('Set-Cookie', SetCookie::create('cookietest2', '12345'))->withAddedHeader('Set-Cookie', new \stdClass())->withAddedHeader('Set-Cookie', SetCookie::create('cookietest4', new OpaqueProperty('vwxyz')));
     };
     $mw = new EncryptedCookiesMiddleware($this->encryption, ['cookietest1'], false);
     $response = $mw($this->request, $this->response, $appMiddleware);
     $resCookie = $response->getHeaderLine('Set-Cookie');
     $this->assertSame('cookietest1=abcde,cookietest2=12345_encrypted,cookietest4=vwxyz_encrypted', $resCookie);
 }
 /**
  * @return SessionMiddleware[][]
  */
 public function validMiddlewaresProvider()
 {
     return [[new SessionMiddleware(new Sha256(), 'foo', 'foo', SetCookie::create(SessionMiddleware::DEFAULT_COOKIE), new Parser(), 100)], [SessionMiddleware::fromSymmetricKeyDefaults('not relevant', 100)], [SessionMiddleware::fromAsymmetricKeyDefaults(file_get_contents(__DIR__ . '/../../keys/private_key.pem'), file_get_contents(__DIR__ . '/../../keys/public_key.pem'), 200)]];
 }
Exemplo n.º 18
0
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license.
 */
declare (strict_types=1);
use Dflydev\FigCookies\SetCookie;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response;
use PSR7Session\Http\SessionMiddleware;
use Psr\Http\Message\ResponseInterface;
use Zend\Diactoros\Response\SapiEmitter;
use Zend\Diactoros\ServerRequestFactory;
require_once __DIR__ . '/../vendor/autoload.php';
// the example uses a symmetric key, but asymmetric keys can also be used.
// $privateKey = new Key('file://private_key.pem');
// $publicKey = new Key('file://public_key.pem');
// simply run `php -S localhost:8888 index.php`
// then point your browser at `http://localhost:8888/`
$sessionMiddleware = new SessionMiddleware(new Sha256(), 'a very complex symmetric key', 'a very complex symmetric key', SetCookie::create('an-example-cookie-name')->withSecure(false)->withHttpOnly(true), new Parser(), 1200);
$myMiddleware = function (ServerRequestInterface $request, ResponseInterface $response) : ResponseInterface {
    /* @var \PSR7Session\Session\SessionInterface $session */
    $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);
    $session->set('counter', $session->get('counter', 0) + 1);
    $response->getBody()->write('Counter Value: ' . $session->get('counter'));
    return $response;
};
(new SapiEmitter())->emit($sessionMiddleware(ServerRequestFactory::fromGlobals(), new Response(), $myMiddleware));
 /**
  * Authorizes given Student entity.
  *
  * This method authorizes user using cookies. In details, it adds an
  * authorization cookie to the given response instance. Authorization
  * cookie contains an authorization token, which is unique for every student
  * entity.
  *
  * This method throws an InvalidArgumentException if given student entity does
  * not have an authorization token. You can use createAuthToken() method to generate
  * an auth token for a student entity.
  *
  * @param Student $student Student to authorize
  * @param ResponseInterface $response Response instance for authorization cookie.
  *
  * @throws \InvalidArgumentException If given Student instance does not have an
  * authorization token.
  *
  * @return \Psr\Http\Message\ResponseInterface Response instance with authorization cookie.
  */
 public function authorizeUser(Student $student, ResponseInterface $response)
 {
     if (empty($student->getToken())) {
         throw new \InvalidArgumentException('Student must have an authorization' . ' token in order to complete authorization.');
     }
     $dateTime = new \DateTime("now");
     $dateTime->add(new \DateInterval("P90D"));
     return FigResponseCookies::set($response, SetCookie::create('authorization')->withValue($student->getToken())->withExpires($dateTime->format(\DateTime::COOKIE))->withPath('/'));
 }
Exemplo n.º 20
0
 /**
  * @param ResponseInterface $response
  * @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session
  * @return ResponseInterface
  */
 protected function addCookieToResponse(ResponseInterface $response, $session)
 {
     $s = $session;
     if ($this->sessionIsPersistent($c = $this->manager->getSessionConfig())) {
         $secure = array_get($c, 'secure', false);
         $setCookie = SetCookie::create($s->getName())->withValue($s->getId())->withExpires($this->getCookieLifetime())->withDomain($c['domain'])->withPath($c['path'])->withHttpOnly(true)->withSecure($secure);
         $response = FigResponseCookies::set($response, $setCookie);
     }
     return $response;
 }
Exemplo n.º 21
0
 /**
  * @return SetCookie
  */
 private function getExpirationCookie() : SetCookie
 {
     return $this->defaultCookie->withValue(null)->withExpires((new \DateTime('-30 day'))->getTimestamp());
 }
 /**
  * Parse all cookies set on the response
  *
  * - If string - leave alone (this is expected to be a fully rendered cookie string with expiry, etc)
  * - If instance of "SetCookie" - stringify
  * - If instance of "SetCookie" and OpaqueProperty - stringify
  *
  * Cookies that are "SetCookie" will be encrypted if possible, or not if configured to not encrypt.
  *
  * Cookies will be automatically deduped.
  *
  * @param SetCookie[]|string[] $reqCookies
  *
  * @return string[]
  */
 private function encryptAndRenderCookies($resCookies)
 {
     $renderable = [];
     foreach ($resCookies as $cookie) {
         if (is_string($cookie)) {
             $cookie = SetCookie::fromSetCookieString($cookie);
         }
         if ($cookie instanceof SetCookie) {
             $val = $cookie->getValue();
             if ($val instanceof OpaqueProperty) {
                 $val = $val->getValue();
             }
             if (!in_array($cookie->getName(), $this->unencryptedCookies)) {
                 $val = $this->encryption->encrypt($val);
             }
             $renderable[$cookie->getName()] = (string) $cookie->withValue($val);
         }
     }
     return $renderable;
 }