Cookie

 view release on metacpan or  search on metacpan

README  view on Meta::CPAN

NAME
    Cookie::Jar - Cookie Jar Class for Server & Client

SYNOPSIS
        use Cookie::Jar;
        my $jar = Cookie::Jar->new( request => $r ) ||
            die( "An error occurred while trying to get the cookie jar:", Cookie::Jar->error );
        # set the default host
        $jar->host( 'www.example.com' );
        $jar->fetch;
        # or using a HTTP::Request object
        # Retrieve cookies from Cookie header sent from client
        $jar->fetch( request => $http_request );
        if( $jar->exists( 'my-cookie' ) )
        {
            # do something
        }
        # get the cookie
        my $sid = $jar->get( 'my-cookie' );
        # get all cookies
        my @all = $jar->get( 'my-cookie', 'example.com', '/' );
        # set a new Set-Cookie header
        $jar->set( 'my-cookie' => $cookie_object );
        # Remove cookie from jar
        $jar->delete( 'my-cookie' );
        # or using the object itself:
        $jar->delete( $cookie_object );

        # Create and add cookie to jar
        $jar->add(
            name => 'session',
            value => 'lang=en-GB',
            path => '/',
            secure => 1,
            same_site => 'Lax',
        ) || die( $jar->error );
        # or add an existing cookie
        $jar->add( $some_cookie_object );

        my $c = $jar->make({
            name => 'my-cookie',
            domain => 'example.com',
            value => 'sid1234567',
            path => '/',
            expires => '+10D',
            # or alternatively
            maxage => 864000
            # to make it exclusively accessible by regular http request and not ajax
            http_only => 1,
            # should it be used under ssl only?
            secure => 1,
        });

        # Add the Set-Cookie headers
        $jar->add_response_header;
        # Alternatively, using a HTTP::Response object or equivalent
        $jar->add_response_header( $http_response );
        $jar->delete( 'some_cookie' );
        $jar->do(sub
        {
            # cookie object is available as $_ or as first argument in @_
        });

        # For client side
        # Takes a HTTP::Response object or equivalent
        # Extract cookies from Set-Cookie headers received from server
        $jar->extract( $http_response );
        # get by domain; by default sort it
        my $all = $jar->get_by_domain( 'example.com' );
        # Reverse sort
        $all = $jar->get_by_domain( 'example.com', sort => 0 );

README  view on Meta::CPAN


        # Save encrypted
        $jar->save( '/some/where/mycookies.json',
        {
            encrypt => 1,
            key => $key,
            iv => $iv,
            algo => 'AES',
        }) || die( $jar->error );
        # Load cookies from encrypted file
        $jar->load( '/some/where/mycookies.json',
        {
            decrypt => 1,
            key => $key,
            iv  => $iv,
            algo => 'AES'
        }) || die( $jar->error );

        # Merge repository
        $jar->merge( $jar2 ) || die( $jar->error );
    
        # For autosave
        my $jar = Cookie::Jar->new(
            file => '/some/where/cookies.json',
            # True by default
            autosave => 1,
            encrypt => 1,
            secret => 'My big secret',
            algo => 'AES',
        ) || die( Cookie::Jar->error );

        say "There are ", $jar->length, " cookies in the repository.";
    
        # Take a string from a Set-Cookie header and get a Cookie object
        my $c = $jar->extract_one( $cookie_string );

VERSION
        v0.3.1

DESCRIPTION
    This is a module to handle cookies, according to the latest standard as
    set by rfc6265 <https://datatracker.ietf.org/doc/html/rfc6265>, both by
    the http server and the client. Most modules out there are either
    antiquated, i.e. they do not support latest cookie rfc6265
    <https://datatracker.ietf.org/doc/html/rfc6265>, or they focus only on
    http client side.

    For example, Apache2::Cookie does not work well in decoding cookies, and
    Cookie::Baker "Set-Cookie" timestamp format is wrong. They use
    Mon-09-Jan 2020 12:17:30 GMT where it should be, as per rfc 6265 Mon, 09
    Jan 2020 12:17:30 GMT

    Also APR::Request::Cookie and Apache2::Cookie which is a wrapper around
    APR::Request::Cookie return a cookie object that returns the value of
    the cookie upon stringification instead of the full "Set-Cookie"
    parameters. Clearly they designed it with a bias leaned toward
    collecting cookies from the browser.

    This module supports modperl and uses a Apache2::RequestRec if provided,
    or can use package objects that implement similar interface as
    HTTP::Request and HTTP::Response, or if none of those above are
    available or provided, this module returns its results as a string.

    This module is also compatible with LWP::UserAgent, so you can use like
    this:

        use LWP::UserAgent;
        use Cookie::Jar;
 
        my $ua = LWP::UserAgent->new(
            cookie_jar => Cookie::Jar->new
        );

    It is also compatible with HTTP::Promise, such as:

        use HTTP::Promise;
        my $ua = HTTP::Promise->new( cookie_jar => Cookie::Jar->new );

    This module does not die upon error, but instead returns "undef" and
    sets an error, so you should always check the return value of a method.

METHODS
  new
    This initiates the package and takes the following parameters:

    *   "request"

        This is an optional parameter to provide a Apache2::RequestRec
        object. When provided, it will be used in various methods to get or
        set cookies from or onto http headers.

            package MyApacheHandler;
            use Apache2::Request ();
            use Cookie::Jar;
    
            sub handler : method
            {
                my( $class, $r ) = @_;
                my $jar = Cookie::Jar->new( $r );
                # Load cookies;
                $jar->fetch;
                $r->log_error( "$class: Found ", $jar->repo->length, " cookies." );
                $jar->add(
                    name => 'session',
                    value => 'lang=en-GB',
                    path => '/',
                    secure => 1,
                    same_site => 'Lax',
                );
                # Will use Apache2::RequestRec object to set the Set-Cookie headers
                $jar->add_response_header || do
                {
                    $r->log_reason( "Unable to add Set-Cookie to response header: ", $jar->error );
                    return( Apache2::Const::HTTP_INTERNAL_SERVER_ERROR );
                };
                # Do some more computing
                return( Apache2::Const::OK );
            }

    *   "debug"

        Optional. If set with a positive integer, this will activate verbose
        debugging message

  add
    Provided with an hash or hash reference of cookie parameters (see
    Cookie) and this will create a new cookie and add it to the cookie
    repository.

    Alternatively, you can also provide directly an existing cookie object

        my $c = $jar->add( $cookie_object ) || die( $jar->error );

  add_cookie_header
    This is an alias for "add_request_header" for backward compatibility
    with HTTP::Cookies

  add_request_header
    Provided with a request object, such as, but not limited to
    HTTP::Request and this will add all relevant cookies in the repository
    into the "Cookie" http request header. The object method needs to have
    the "header" method in order to get, or set the "Cookie" or "Set-Cookie"
    headers and the "uri" method.

    As long as the object provided supports the "uri" and "header" method,
    you can provide any class of object you want.

    Please refer to the rfc6265
    <https://datatracker.ietf.org/doc/html/rfc6265> for more information on
    the applicable rule when adding cookies to the outgoing request header.

    Basically, it will add, for a given domain, first all cookies whose path
    is longest and at path equivalent, the cookie creation date is used,
    with the earliest first. Cookies who have expired are not sent, and
    there can be cookies bearing the same name for the same domain in
    different paths.

  add_response_header
        # Adding cookie to the repository
        $jar->add(
            name => 'session',
            value => 'lang=en-GB',
            path => '/',
            secure => 1,
            same_site => 'Lax',
        ) || die( $jar->error );
        # then placing it onto the response header
        $jar->add_response_header;

    This is the alter ego to "add_request_header", in that it performs the
    equivalent function, but for the server side.

    You can optionally provide, as unique argument, an object, such as but
    not limited to, HTTP::Response, as long as that class supports the
    "header" method

    Alternatively, if an Apache object has been set upon object
    instantiation or later using the "request" method, then it will be used
    to set the outgoing "Set-Cookie" headers (there is one for every cookie
    sent).

    If no response, nor Apache2 object were set, then this will simply
    return a list of "Set-Cookie" in list context, or a string of possibly
    multiline "Set-Cookie" headers, or an empty string if there is no cookie
    found to be sent.

    Be careful not to do the following:

        # get cookies sent by the http client
        $jar->fetch || die( $jar->error );
        # set the response headers with the cookies from our repository
        $jar->add_response_header;

    Why? Well, because "fetch" retrieves the cookies sent by the http client
    and store them into the repository. However, cookies sent by the http
    client only contain the cookie name and value, such as:

        GET /my/path/ HTTP/1.1
        Host: www.example.org
        Cookie: session_token=eyJleHAiOjE2MzYwNzEwMzksImFsZyI6IkhTMjU2In0.eyJqdGkiOiJkMDg2Zjk0OS1mYWJmLTRiMzgtOTE1ZC1hMDJkNzM0Y2ZmNzAiLCJmaXJzdF9uYW1lIjoiSm9obiIsImlhdCI6MTYzNTk4NDYzOSwiYXpwIjoiNGQ0YWFiYWQtYmJiMy00ODgwLThlM2ItNTA0OWMwZTczNjBlIiwiaXNz...

README  view on Meta::CPAN


    It returns 1 if it does, or 0 if it does not.

  extract
    Provided with a response object, such as, but not limited to
    HTTP::Response, and this will retrieve any cookie sent from the remote
    server, parse them and add their respective to the repository.

    As per the rfc6265, section 5.3.11 specifications
    <https://datatracker.ietf.org/doc/html/rfc6265#section-5.3> if there are
    duplicate cookies for the same domain and path, only the last one will
    be retained.

    If the cookie received does not contain any "Domain" specification,
    then, in line with rfc6265 specifications, it will take the root of the
    current domain as the default domain value. Since finding out what is
    the root for a domain name is a non-trivial exercise, this method relies
    on Cookie::Domain.

  extract_cookies
    This is an alias for "extract" for backward compatibility with
    HTTP::Cookies

  extract_one
    This method takes a cookie string, which can be found in the
    "Set-Cookie" header, parse it, and returns a Cookie object if
    successful, or sets an error and return "undef" or an empty list
    depending on the context.

    It also takes an hash or hash reference of options.

    The following options are supported:

    *   "host"

        If provided, it will be used to find out the host's root domain, and
        to set the cookie object "domain" property if none is specified in
        the cookie string.

    *   "path"

        If provided, it will be used to set the cookie object "path"
        property.

    *   "port"

        If provided, it will be used to set the cookie object "port"
        property.

  fetch
    This method does the equivalent of "extract", but for the server.

    It retrieves all possible cookies from the http request received from
    the web browser.

    It takes an optional hash or hash reference of parameters, such as
    "host". If it is not provided, the value set with "host" is used
    instead.

    If the parameter "request" containing an http request object, such as,
    but not limited to HTTP::Request, is provided, it will use it to get the
    "Cookie" header value. The object method needs to have the "header"
    method in order to get, or set the "Cookie" or "Set-Cookie" headers.

    Alternatively, if a value for "request" has been set, it will use it to
    get the "Cookie" header value from Apache modperl.

    You can also provide the "Cookie" string to parse by providing the
    "string" option to this method.

        $jar->fetch( string => q{foo=bar; site_prefs=lang%3Den-GB} ) ||
            die( $jar->error );

    Ultimately, if none of those are available, it will use the environment
    variable "HTTP_COOKIE"

    If the option "store" is true (by default it is true), this method will
    add the fetched cookies to the repository.

    It returns an hash reference of cookie key => cookie object

    A cookie key is made of the host (possibly empty), the path and the
    cookie name separated by ";"

        # Cookies added to the repository
        $jar->fetch || die( $jar->error );
        # Cookies returned, but NOT added to the repository
        my $cookies = $jar->fetch || die( $jar->error );

  file
    Sets or gets the file path to the cookie jar file.

    If provided upon instantiation, and if the file exists on the filesystem
    and is not empty, "Cookie::Jar" will load all the cookies from it.

    If "autosave" is set to a true, "Cookie::Jar" will automatically save
    all cookies to the specified cookie jar file, possibly encrypting it if
    "algo" and "secret" are set.

  get
    Given a cookie name, an optional host and an optional path, this will
    retrieve its corresponding cookie object and return it.

    If not found, it will try to return a value with just the cookie name.

    If nothing is found, this will return and empty list in list context or
    "undef" in scalar context.

    You can "get" multiple cookie object and this method will return a list
    in list context and the first cookie object found in scalar context.

        # Wrong, an undefined returned value here only means there is no such cookie
        my $c = $jar->get( 'my-cookie' );
        die( $jar->error ) if( !defined( $c ) );
        # Correct
        my $c = $jar->get( 'my-cookie' ) || die( "No cookie my-cookie found\n" );
        # Possibly get multiple cookie object for the same name
        my @cookies = $jar->get( 'my_same_name' ) || die( "No cookies my_same_name found\n" );
        # or
        my @cookies = $jar->get( 'my_same_name' => 'www.example.org', '/private' ) || die( "No cookies my_same_name found\n" );



( run in 1.560 second using v1.01-cache-2.11-cpan-98e64b0badf )