View for setting cookies on spammers.
172633
def spammer_view(request):
    """"""

    # Permits use of CSRF middleware
    context = RequestContext(request, {})
    template = Template("")

    response = HttpResponse(template.render(context))
    # Sets a cookie with a 10 years lifetime, accessible only via HTTP:
    response.set_cookie(COOKIE_KEY, value=COOKIE_SPAM, httponly=True,
                        expires=datetime.now()+timedelta(days=3650))
    
    if DJANGOSPAM_LOG:
        log("BLOCK RESPONSE", request.method, request.path_info,
            request.META.get("HTTP_USER_AGENT", "undefined"))

    return response
776242
def cookies(self):
        
        cookies = SimpleCookie(self.environ.get('HTTP_COOKIE','')).values()
        if len(cookies) > self.MAX_PARAMS:
            raise HTTPError(413, 'Too many cookies')
        return FormsDict((c.key, c.value) for c in cookies)
1005056
public function cookiesAction() {
        $config       = Zend_Registry::get('config');
        $viewBasePath = $config->resources->view->basePath ?:
            APPLICATION_PATH . '/modules/default/views';

        $this->_helper->layout->setLayoutPath($viewBasePath . '/layouts/');
        $this->view->title = 'Cookies';
    }
712446
def filter_cookies(self, request_url: URL=URL()) -> 'BaseCookie[str]':
        """"""
        self._do_expiration()
        request_url = URL(request_url)
        filtered = SimpleCookie()
        hostname = request_url.raw_host or ""
        is_not_secure = request_url.scheme not in ("https", "wss")

        for cookie in self:
            name = cookie.key
            domain = cookie["domain"]

            # Send shared cookies
            if not domain:
                filtered[name] = cookie.value
                continue

            if not self._unsafe and is_ip_address(hostname):
                continue

            if (domain, name) in self._host_only_cookies:
                if domain != hostname:
                    continue
            elif not self._is_domain_match(domain, hostname):
                continue

            if not self._is_path_match(request_url.path, cookie["path"]):
                continue

            if is_not_secure and cookie["secure"]:
                continue

            # It's critical we use the Morsel so the coded_value
            # (based on cookie version) is preserved
            mrsl_val = cast('Morsel[str]', cookie.get(cookie.key, Morsel()))
            mrsl_val.set(cookie.key, cookie.value, cookie.coded_value)
            filtered[name] = mrsl_val

        return filtered
1220661
def make_cookies(self, response, request):
        """"""
        # get cookie-attributes for RFC 2965 and Netscape protocols
        headers = response.info()
        rfc2965_hdrs = headers.get_all("Set-Cookie2", [])
        ns_hdrs = headers.get_all("Set-Cookie", [])

        rfc2965 = self._policy.rfc2965
        netscape = self._policy.netscape

        if ((not rfc2965_hdrs and not ns_hdrs) or
            (not ns_hdrs and not rfc2965) or
            (not rfc2965_hdrs and not netscape) or
            (not netscape and not rfc2965)):
            return []  # no relevant cookie headers: quick exit

        try:
            cookies = self._cookies_from_attrs_set(
                split_header_words(rfc2965_hdrs), request)
        except Exception:
            _warn_unhandled_exception()
            cookies = []

        if ns_hdrs and netscape:
            try:
                # RFC 2109 and Netscape cookies
                ns_cookies = self._cookies_from_attrs_set(
                    parse_ns_headers(ns_hdrs), request)
            except Exception:
                _warn_unhandled_exception()
                ns_cookies = []
            self._process_rfc2109_cookies(ns_cookies)

            # Look for Netscape cookies (from Set-Cookie headers) that match
            # corresponding RFC 2965 cookies (from Set-Cookie2 headers).
            # For each match, keep the RFC 2965 cookie and ignore the Netscape
            # cookie (RFC 2965 section 9.1).  Actually, RFC 2109 cookies are
            # bundled in with the Netscape cookies for this purpose, which is
            # reasonable behaviour.
            if rfc2965:
                lookup = {}
                for cookie in cookies:
                    lookup[(cookie.domain, cookie.path, cookie.name)] = None

                def no_matching_rfc2965(ns_cookie, lookup=lookup):
                    key = ns_cookie.domain, ns_cookie.path, ns_cookie.name
                    return key not in lookup
                ns_cookies = filter(no_matching_rfc2965, ns_cookies)

            if ns_cookies:
                cookies.extend(ns_cookies)

        return cookies
1007023
def view_cookies(self):
        
        return_list = []
        for cookie in self._session.cookies:
            return_list.append(vars(cookie))

        return return_list
315894
def view_cookies(hide_env=True):
    

    cookies = dict(request.cookies.items())

    if hide_env and ("show_env" not in request.args):
        for key in ENV_COOKIES:
            try:
                del cookies[key]
            except KeyError:
                pass

    return jsonify(cookies=cookies)
107685
public void setCookies(List<HttpCookie> cookies) {
        if (cookies.isEmpty()) {
            setHeader(HttpHeader.COOKIE, null);
        }

        StringBuilder sbData = new StringBuilder();

        for (HttpCookie c : cookies) {
            sbData.append(c.getName());
            sbData.append('=');
            sbData.append(c.getValue());
            sbData.append("; ");
        }

        if (sbData.length() <= 3) {
            setHeader(HttpHeader.COOKIE, null);
            return;
        }

        final String data = sbData.substring(0, sbData.length() - 2);
        setHeader(HttpHeader.COOKIE, data);
    }
144529
def set_cookie(  # type: ignore
            self,
            key: str,
            value: AnyStr='',
            max_age: Optional[Union[int, timedelta]]=None,
            expires: Optional[datetime]=None,
            path: str='/',
            domain: Optional[str]=None,
            secure: bool=False,
            httponly: bool=False,
    ) -> None:
        
        if isinstance(value, bytes):
            value = value.decode()  # type: ignore
        cookie = create_cookie(key, value, max_age, expires, path, domain, secure, httponly)  # type: ignore  # noqa: E501
        self.headers.add('Set-Cookie', cookie.output(header=''))
643549
def clean_cookie(self):
        """"""
        if not self.is_cookie_necessary:
            return self
        headers = self.request.get('headers', {})
        cookies = SimpleCookie(headers['Cookie'])
        for k, v in cookies.items():
            new_cookie = '; '.join(
                [i.OutputString() for i in cookies.values() if i != v])
            new_request = deepcopy(self.request)
            new_request['headers']['Cookie'] = new_cookie
            self._add_task('Cookie', k, new_request)
        return self
1005933
def process_response(self, request, response):
        """"""
        if COOKIE_KEY not in request.COOKIES:
        # Unknown user, set cookie and go on...
            response.set_cookie(COOKIE_KEY, COOKIE_PASS, httponly=True,
                                expires=datetime.now()+timedelta(days=30))
            # Only logged if we have to set the PASS cookie
            if DJANGOSPAM_LOG:
                logger.log("PASS RESPONSE", request.method, request.path_info,
                           request.META.get("HTTP_USER_AGENT", "undefined"))                
        return response
754163
def set_cookie_if_ok(self, cookie, request):
        """"""
        self._cookies_lock.acquire()
        try:
            self._policy._now = self._now = int(time.time())

            if self._policy.set_ok(cookie, request):
                self.set_cookie(cookie)


        finally:
            self._cookies_lock.release()
466545
def set_response_cookie(response, cookie_name, cookie_value):
    
    now = timezone.now()
    expire_date = now + datetime.timedelta(days=365)
    response.set_cookie(cookie_name, cookie_value, expires=expire_date)
88724
def set_cookie!
      cookies[:user_session] = {
        :value => self.temporary_token,
        :secure => controller.request.ssl?,
        :httponly => true,
        :expires => self.expires_at
      }
      Authie.config.events.dispatch(:session_cookie_updated, self)
      true
    end
904068
private Set<Cookie> doDecode(String header) {
        List<String> names = new ArrayList<String>(8);
        List<String> values = new ArrayList<String>(8);
        extractKeyValuePairs(header, names, values);

        if (names.isEmpty()) {
            return Collections.emptySet();
        }

        int i;
        int version = 0;

        // $Version is the only attribute that can appear before the actual
        // cookie name-value pair.
        if (names.get(0).equalsIgnoreCase(VERSION)) {
            try {
                version = Integer.parseInt(values.get(0));
            } catch (NumberFormatException e) {
                // Ignore.
            }
            i = 1;
        } else {
            i = 0;
        }

        if (names.size() <= i) {
            // There's a version attribute, but nothing more.
            return Collections.emptySet();
        }

        Set<Cookie> cookies = new TreeSet<Cookie>();
        for (; i < names.size(); i ++) {
            String name = names.get(i);
            String value = values.get(i);
            if (value == null) {
                value = "";
            }

            Cookie c = initCookie(name, value);

            if (c == null) {
                break;
            }

            boolean discard = false;
            boolean secure = false;
            boolean httpOnly = false;
            String comment = null;
            String commentURL = null;
            String domain = null;
            String path = null;
            long maxAge = Long.MIN_VALUE;
            List<Integer> ports = new ArrayList<Integer>(2);

            for (int j = i + 1; j < names.size(); j++, i++) {
                name = names.get(j);
                value = values.get(j);

                if (DISCARD.equalsIgnoreCase(name)) {
                    discard = true;
                } else if (CookieHeaderNames.SECURE.equalsIgnoreCase(name)) {
                    secure = true;
                } else if (CookieHeaderNames.HTTPONLY.equalsIgnoreCase(name)) {
                   httpOnly = true;
                } else if (COMMENT.equalsIgnoreCase(name)) {
                    comment = value;
                } else if (COMMENTURL.equalsIgnoreCase(name)) {
                    commentURL = value;
                } else if (CookieHeaderNames.DOMAIN.equalsIgnoreCase(name)) {
                    domain = value;
                } else if (CookieHeaderNames.PATH.equalsIgnoreCase(name)) {
                    path = value;
                } else if (CookieHeaderNames.EXPIRES.equalsIgnoreCase(name)) {
                    Date date = DateFormatter.parseHttpDate(value);
                    if (date != null) {
                        long maxAgeMillis = date.getTime() - System.currentTimeMillis();
                        maxAge = maxAgeMillis / 1000 + (maxAgeMillis % 1000 != 0? 1 : 0);
                    }
                } else if (CookieHeaderNames.MAX_AGE.equalsIgnoreCase(name)) {
                    maxAge = Integer.parseInt(value);
                } else if (VERSION.equalsIgnoreCase(name)) {
                    version = Integer.parseInt(value);
                } else if (PORT.equalsIgnoreCase(name)) {
                    String[] portList = value.split(",");
                    for (String s1: portList) {
                        try {
                            ports.add(Integer.valueOf(s1));
                        } catch (NumberFormatException e) {
                            // Ignore.
                        }
                    }
                } else {
                    break;
                }
            }

            c.setVersion(version);
            c.setMaxAge(maxAge);
            c.setPath(path);
            c.setDomain(domain);
            c.setSecure(secure);
            c.setHttpOnly(httpOnly);
            if (version > 0) {
                c.setComment(comment);
            }
            if (version > 1) {
                c.setCommentUrl(commentURL);
                c.setPorts(ports);
                c.setDiscard(discard);
            }

            cookies.add(c);
        }

        return cookies;
    }
290974
def _extract_cookies(self, response: Response):
        ''''''
        self._cookie_jar.extract_cookies(
            response, response.request, self._get_cookie_referrer_host()
        )
994774
function setcookies()
    {
        for ($x = 0; $x < count($this->headers); $x++) {
            if (preg_match('/^set-cookie:[\s]+([^=]+)=([^;]+)/i', $this->headers[$x], $match))
                $this->cookies[$match[1]] = urldecode($match[2]);
        }
        return $this;
    }