Code Monkey home page Code Monkey logo

mezzio-session's Introduction

mezzio-session

Build Status

🇷🇺 Русским гражданам

Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм.

У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую.

Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите "Нет войне!"

🇺🇸 To Citizens of Russia

We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism.

One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences.

You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say "stop the war!"

This library provides session handling middleware for PSR-7 applications, using an adapter-based approach that will allow usage of ext-session, JWT, or other approaches.

Installation

Run the following to install this library:

$ composer require mezzio/mezzio-session

However, the package is not immediately useful unless you have a persistence adapter. If you are okay with using ext-session, you can install the following package as well:

$ composer require mezzio/mezzio-session-ext

Documentation

Documentation is in the doc tree, and can be compiled using mkdocs:

$ mkdocs build

You may also browse the documentation online.

mezzio-session's People

Contributors

alexmerlin avatar boesing avatar dependabot[bot] avatar froschdesign avatar geerteltink avatar ghostwriter avatar gsteel avatar hannesvdvreken avatar harikt avatar kynx avatar laminas-bot avatar michaelgooden avatar michalbundyra avatar ocramius avatar pine3ree avatar renovate[bot] avatar samsonasik avatar thexpand avatar weierophinney avatar xerkus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mezzio-session's Issues

Remove session set value will convert to an array/obj value.

I saw the Session::extractSerializableValue method comment

This value should be used by set() operations to ensure that the values
within a session are serializable across any session adapter.

But most of adapters can store string after using serialize() function . And I think this is adapter layer.

And then, I think can remove it.

Code to reproduce the issue

class User extends \ArrayObject {
}

$session->set(User::class, new User(['id' => 1]))
$user = $session->get(User::class); 

Expected results

$user instanceof User; 

Actual results

$user; 
// Is array:
// ['id' => 1]

Originally posted by @Moln at zendframework/zend-expressive-session#37

Deprecate Session as a Request attribute in favor of dedicated Helper

Feature Request

Q A
New Feature yes
RFC yes
BC Break no

Hi, currently the Session instance is set as an attribute of the Request:

$response = $handler->handle($request->withAttribute(self::SESSION_ATTRIBUTE, $session));

In my humble opinion this is an anti-pattern:

  1. Session has nothing to do with the pure concept of a Request; it leverages the Cookie functionalities, but it's not stritcly coupled to the Request itself
  2. As an attribute, is basically injected everywhere, even to following Middlewares and Handlers that don't need it and shouldn't be aware of it
  3. It breaks typing (and that's a smell by itself): every Request attributes derives from a HTTP Request so theoretically only scalar types are allowed; Session instead needs a non-scalar type but cannot be enforced by the PSR-7 specifications

What I propose here is the same approach used by Mezzio Helpers like ServerUrlMiddleware: a dedicated SessionHelper is filled and the Request untouched; if a class needs the Session, its factory must inject the SessionHelper to it, otherwise the Session is unreachable.

The same issue affects other components (see AuthenticationMiddleware.php) but Session seems to me the first one to start topic with.

Ping @Ocramius for https://twitter.com/Ocramius/status/1244964513578876928

avoid code duplication in persistence impl.

Feature Request

Q A
New Feature yes (refactoring)
RFC no
BC Break no

Summary

Hello, having implemented the cache-limiter generation feature in mezzio-session-ext, I found out that the same code is duplicated in mezzio-session-cache.
This is because php-session is one extension that generates a response cookie and cache-header always in the same way (with custom params) and allowing us to attach different save-handlers, while mezzio-session persistence layer is more generic and takes care both of the persistence of the session-data and the session-identification in the client-browser. mezzio-session does not assume that phpsession-like headers must be used in all persistence implementations.

Some of these implementations may have common codebase.
IMO it would be better to have either traits for such common features or cache-headers-generator/set-cookie-header-generator services as dependencies for the persistence implementations that require them.

kind regards

PHP 8.0 support

Feature Request

Q A
New Feature yes

Summary

To be prepared for the december release of PHP 8.0, this repository has some additional TODOs to be tested against the new major version.

In order to make this repository compatible, one has to follow these steps:

  • Modify composer.json to provide support for PHP 8.0 by adding the constraint ~8.0.0
  • Modify composer.json to drop support for PHP less than 7.3
  • Modify composer.json to implement phpunit 9.3 which supports PHP 7.3+
  • Modify .travis.yml to ignore platform requirements when installing composer dependencies (simply add --ignore-platform-reqs to COMPOSER_ARGS env variable)
  • Modify .travis.yml to add PHP 8.0 to the matrix (NOTE: Do not allow failures as PHP 8.0 has a feature freeze since 2020-08-04!)
  • Modify source code in case there are incompatibilities with PHP 8.0

Psalm integration

Feature Request

Q A
QA yes

Summary

As decided during the Technical-Steering-Committee Meeting on August 3rd, 2020, Laminas wants to implement vimeo/psalm in all packages.

Implementing psalm is quite easy.

Required

  • Create a psalm.xml in the project root
  • Copy and paste the contents from this psalm.xml.dist
  • Run $ composer require --dev vimeo/psalm
  • Run $ vendor/bin/psalm --set-baseline=psalm-baseline.xml
  • Add a composer script static-analysis with the command psalm --shepherd --stats
  • Add a new line to script: in .travis.yml: - if [[ $TEST_COVERAGE == 'true' ]]; then composer static-analysis ; fi
  • Remove phpstan from the project (phpstan.neon.dist, .travis.yml entry, composer.json require-dev and scripts)
Optional
  • Fix as many psalm errors as possible.

mezzio-session-ext vs php-ext-session

Feature Request

Q A
New Features yes
BC Break maybe

Summary

This is more a comparison of behavior of mezzio-session-ext implementation vs the php ext-session.

  1. calling session_start() via php-ext-session always sets a session-cookie in the first session-aware script's response even if no data is actually stored in the session. mezzio-session-ext only sets a response session-cookie if the session-data is changed or the session is regenerated. see (*)

  2. php-ext-session sets the session-cookie in the response only if the session-id is changed either when the session is fresh (new) or its id is regenerated. mezzio-session-ext always sets the response session cookie if the session-data has been altered even if the session-id is unchanged. see (*)

  3. php-ext-session always sends cache-limiters headers after a session_start() call. mezzio-session-ext only sends cache-limiters headers when the session-data ( or the session is regenerated) has been changed (*)

  4. after calling session_start()(or session_regenerate_id()) the actual session id is available right away and may be used programmatically to identify the client browser session in the first fresh-session-generating script execution. With mezzio-session-ext in a fresh session or a regenerated session context the actual/final session-id is only available inside PhpSessionPersistence::persistSession() . see (**)

  5. feature/maybe BC: php-ext-session does not set a new session-cookie (with same id) if we only change the session-cookie-lifetime. It would be useful to make mezzio-session-ext always send a new cooki when the session-lifetime is changed ($session->persistSessionFor()). This could be achieved allowing null to be returned in SessionCookiePersistenceInterface::getSessionLifetime(). A null value could be used to indicate that the cookie-lifetime has not been changed, any unsigned int to programmatically set the cookie-lifetime, 0 for restoring to a session-cookie.

  6. BC renaming of SessionCookiePersistenceInterface methods
    we now have:

  • SessionIdentifierAwareInterface::getID()
  • SessionCookiePersistenceInterface::persistSessionFor(int $duration)
  • SessionCookiePersistenceInterface::getSessionLifetime()

In my opinion we should have for consistency:

  • SessionCookiePersistenceInterface::persistFor(int $duration)
  • SessionCookiePersistenceInterface::getLifetime()

so that we can make calls call $session->getLifetime() and $session->persistFor(86400). The word 'Session' in the method seems redundant to me, same as $session->getSessionID() would seem.

(*) behaviours 1 and 2 (and 3) could be achieved in PhpSessionPersistence::persistSession() by comparing the initial session-id (from the request) with the final value and by calling PhpSessionPersistence::regenerateSession() even if only $id === '' or by triggering a $session = $session->regenerate() when $id === '' and then checking $session->isRegenerated().

(**) behavior 3 could be achieved partially using a new SessionIsNewAwareInterface featuring an isNew() method. The new session id would be generated and set in the session instace along with a $isNew constructor param. But I haven not find a way to get the final id from the session instance after a regenerate() call in the inner handler. A SessionIsNewAwareInterface is the solution I have been adopted in my code, to both achieve fresh data-less session and session-id availability inside my handlers code. About that, php session books states that:

  • Session support in PHP consists of a way to preserve certain data across subsequent accesses.
  • A visitor accessing your web site is assigned a unique id, the so-called session id. (...)
  • The session support allows you to store data between requests...

So php-ext-session always assigns a unique id and allows you to store data. I interpret this as 'data-less' an only 'client-identifying' session behavior

kind regards

Hi there! I have a similar library.

Hey. I have followed you on Github and, today, I noticed that you were working on this repo.
I had worked on somewhat similar library a few months back. It's called ps7-session.

It is not completely dependent on expressive. It's a php7 based session library with added support for interop middleware-based applications. Check this

I was wondering if we could talk about whether these two could complement each other. If using that library as a dependency is a good idea. I am open to moving it to zend organization if it's good enough for you people :D
Or, maybe, this library can take some ideas from my library.

The reason I created that library because I was trying to run an expressive based application with reactphp/http and $_SESSION was not usable. Running the expressive application with reactphp was actually experimental and won't make it to production(atleast for now). But, on the process, I was motivated enough to write that library.

Best Regards,
Your long-time fan and follower,
Ujjwal Ojha


Originally posted by @ojhaujjwal at zendframework/zend-expressive-session#1

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • Lock file maintenance

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

composer
composer.json
  • php ~8.1.0 || ~8.2.0 || ~8.3.0
  • dflydev/fig-cookies ^3.0
  • psr/container ^1.0 || ^2.0
  • psr/http-server-middleware ^1.0
  • laminas/laminas-coding-standard ~2.5.0
  • laminas/laminas-diactoros ^3.3.0
  • phpunit/phpunit ^10.5.10
  • psalm/plugin-phpunit ^0.19.0
  • vimeo/psalm ^5.21.1
github-actions
.github/workflows/continuous-integration.yml
.github/workflows/docs-build.yml
.github/workflows/release-on-milestone-closed.yml

  • Check this box to trigger a request for Renovate to run again on this repository

Allow dflydev/fig-cookies v3.0

Bug Report

Q A
Version(s) >= 1.4.0

Summary

Installation on PHP 8 is broken due to external dependency

dflydev/fig-cookies released the PHP 8 support as a new major version for whatever reason. I see no other API or requirement changes there. The tests seem to pass too

Session destroy

I see that SessionInterface does not provide the ability to session destroy .

I am writing my session handler that works with the database.

I created my middleware, which is called before zend-expressive-session-ext and zend-expressive-session:

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $sessionHandler = new DatabaseSessionHandler($this->pdo);
        session_set_save_handler($sessionHandler, true);

        return $handler->handle($request);
    }

It all works, the difference is not noticeable.
But I had a problem with logout.

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        /** @var LazySession $session */
        $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);

        $session->clear(); // does not destroy the session (only clearing data)

        return new RedirectResponse($this->urlHelper->generate('home'), ResponseInfo::HTTP_FOUND);
    }

Solution to the problem:

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        /** @var LazySession $session */
        $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);

        $session->clear(); // does not destroy the session (only clearing data)
        session_destroy(); // everything works however we don't use SessionInterface

        return new RedirectResponse($this->urlHelper->generate('home'), ResponseInfo::HTTP_FOUND);
    }

So, why the SessionInterface doesn't have a destroy method? I think this can be a problem in some cases.


Originally posted by @nepster-web at zendframework/zend-expressive-session#29

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.