Example #1
0
    def process_response(self, request, response):
        if hasattr(request, 'session'):
            if request.session.get_expire_at_browser_close():
                max_age = None
                expires = None
            else:
                max_age = request.session.get_expiry_age()
                expires_time = time.time() + max_age
                expires = cookie_date(expires_time)
        else:
            max_age = None
            expires_time = time.time()+1209960
            expires = cookie_date(expires_time)
        unicID = request.COOKIES[settings.UNIC_TMP_USER_ID] if settings.UNIC_TMP_USER_ID in request.COOKIES  else uuid.uuid1()
        user_city = request.COOKIES[settings.UNIC_TMP_USER_CITY] if settings.UNIC_TMP_USER_CITY in request.COOKIES else 1
        response.set_cookie(settings.UNIC_TMP_USER_ID, unicID, max_age=max_age,
                            expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
                            path=settings.SESSION_COOKIE_PATH,
                            secure=settings.SESSION_COOKIE_SECURE or None,
                            httponly=settings.SESSION_COOKIE_HTTPONLY or None)
        response.set_cookie(settings.UNIC_TMP_USER_CITY, user_city, max_age=max_age,
                            expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
                            path=settings.SESSION_COOKIE_PATH,
                            secure=settings.SESSION_COOKIE_SECURE or None)


        return response
Example #2
0
def index(request, message_pk=None):
    user = request.user
    qs = Message.objects.for_user(user)

    extra_context = {
        'send_message_form': SendMessageForm(request.user, auto_id='message_form_id_%s'),
        'messages_display': True
    }
    
    reply = request.GET.get('reply')

    if reply:
        try:
            reply_msg = Message.objects.get(pk=reply, user=user)
            reply_msg.read = True
            reply_msg.save()
            extra_context['reply_msg'] = reply_msg
        except (Message.DoesNotExist, ValueError):
            pass

    response = object_list(request, queryset=qs,
                       paginate_by=MESSAGES_ON_PAGE,
                       template_name='messages/index.html',
                       template_object_name='message',
                       extra_context=extra_context)
    try:
        last_message = qs[:1].get()
        max_age = 60*60*24*365
        expires = cookie_date(time.time()+max_age)
        response.set_cookie(Message.hide_cookie_name, last_message.pk, max_age, expires)
    except Message.DoesNotExist:
        pass
    
    return response
Example #3
0
 def process_response(self, request, response):
     try:
         accessed = request.session.accessed
         modified = request.session.modified
         empty = request.session.is_empty()
     except AttributeError:
         pass
     else:
         # First check if we need to delete this cookie.
         # The session should be deleted only if the session is entirely empty
         if settings.SESSION_COOKIE_NAME in request.COOKIES and empty:
             response.delete_cookie(settings.SESSION_COOKIE_NAME)
         else:
             if accessed:
                 patch_vary_headers(response, ('Cookie',))
             if modified or settings.SESSION_SAVE_EVERY_REQUEST:
                 if request.session.get_expire_at_browser_close():
                     max_age = None
                     expires = None
                 else:
                     max_age = request.session.get_expiry_age()
                     expires_time = time.time() + max_age
                     expires = cookie_date(expires_time)
                 # Save the session data and refresh the client cookie.
                 # Skip session save for 500 responses, refs #3881.
                 if response.status_code != 500:
                     request.session.save()
                     response.set_cookie(settings.SESSION_COOKIE_NAME,
                                         request.session.session_key, max_age=max_age,
                                         expires=expires,
                                         domain=get_cookie_domain(request),
                                         path=settings.SESSION_COOKIE_PATH,
                                         secure=request.scheme == 'https',
                                         httponly=settings.SESSION_COOKIE_HTTPONLY or None)
     return response
Example #4
0
    def process_request(self, request):
        if not getattr(settings, 'MOBILE_DOMAIN', False):
            return 

        # test for mobile browser
        if (
                # check for override cookie, do not check if present
                request.COOKIES.get('ismobile', '0') == '1' or (
                    # browser info present
                    'HTTP_USER_AGENT' in request.META
                    and 
                    # desktop browser override not set
                    request.COOKIES.get('isbrowser', '0') != '1' 
                    and 
                    # check browser type
                    is_mobile(request.META['HTTP_USER_AGENT'])
                )
            ):
            # redirect to mobile domain
            response = HttpResponseRedirect(settings.MOBILE_DOMAIN)

            # set cookie to identify the browser as mobile
            max_age = getattr(settings, 'MOBILE_COOKIE_MAX_AGE', DEFAULT_COOKIE_MAX_AGE)
            expires_time = time.time() + max_age
            expires = cookie_date(expires_time)
            response.set_cookie('ismobile', '1', domain=settings.SESSION_COOKIE_DOMAIN, max_age=max_age, expires=expires)
            return response
Example #5
0
    def process_request(self, request):
        if not getattr(settings, "MOBILE_DOMAIN", False) or request.GET.get("_isbrowser", False):
            return

        # test for mobile browser
        if (
            # check for override cookie, do not check if present
            request.COOKIES.get("ismobile", "0") == "1"
            or (
                # browser info present
                "HTTP_USER_AGENT" in request.META
                and
                # desktop browser override not set
                request.COOKIES.get("isbrowser", "0") != "1"
                and
                # check browser type
                is_mobile(request.META["HTTP_USER_AGENT"])
            )
        ):
            redirect = settings.MOBILE_DOMAIN
            if getattr(settings, "MOBILE_REDIRECT_PRESERVE_URL", False):
                redirect = redirect.rstrip("/") + request.path_info
            # redirect to mobile domain
            response = HttpResponseRedirect(redirect)

            # set cookie to identify the browser as mobile
            max_age = getattr(settings, "MOBILE_COOKIE_MAX_AGE", DEFAULT_COOKIE_MAX_AGE)
            expires_time = time.time() + max_age
            expires = cookie_date(expires_time)
            response.set_cookie(
                "ismobile", "1", domain=settings.SESSION_COOKIE_DOMAIN, max_age=max_age, expires=expires
            )
            return response
Example #6
0
 def set_persistent_login(request,response):
     max_age = settings.SESSION_COOKIE_AGE
     expires = cookie_date(time.time() + max_age)
     #cookie中加入用户自动登录标志, persistent_login:uuid
     value = uuid.uuid4()
     response.set_cookie(Cookie.c_login,value,max_age=max_age,expires=expires)
     request.session[Cookie.s_login] = value
Example #7
0
def set_logged_in_cookie(request, response):
    """Set a cookie indicating that the user is logged in.

    Some installations have an external marketing site configured
    that displays a different UI when the user is logged in
    (e.g. a link to the student dashboard instead of to the login page)

    Arguments:
        request (HttpRequest): The request to the view, used to calculate
            the cookie's expiration date based on the session expiration date.
        response (HttpResponse): The response on which the cookie will be set.

    Returns:
        HttpResponse

    """
    if request.session.get_expire_at_browser_close():
        max_age = None
        expires = None
    else:
        max_age = request.session.get_expiry_age()
        expires_time = time.time() + max_age
        expires = cookie_date(expires_time)

    response.set_cookie(
        settings.EDXMKTG_COOKIE_NAME, 'true', max_age=max_age,
        expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
        path='/', secure=None, httponly=None,
    )

    return response
Example #8
0
File: tests.py Project: 10sr/hue
 def test_max_age_expiration(self):
     "Cookie will expire if max_age is provided"
     response = HttpResponse()
     response.set_cookie('max_age', max_age=10)
     max_age_cookie = response.cookies['max_age']
     self.assertEqual(max_age_cookie['max-age'], 10)
     self.assertEqual(max_age_cookie['expires'], cookie_date(time.time()+10))
Example #9
0
 def process_response(self, request, response):
     # If request.session was modified, or if response.session was set, save
     # those changes and set a session cookie.
     agent = self.get_agent(request)
     try:
         accessed = request.session.accessed
         modified = request.session.modified
     except AttributeError:
         pass
     else:
         if accessed:
             patch_vary_headers(response, ('Cookie',))
         if modified or settings.SESSION_SAVE_EVERY_REQUEST:
             if request.session.get_expire_at_browser_close():
                 max_age = None
                 expires = None
             else:
                 max_age = request.session.get_expiry_age()
                 expires_time = time.time() + max_age
                 expires = cookie_date(expires_time)
             # Save the session data and refresh the client cookie.
             request.session.save()
             if not agent.is_docomo():
                 response.set_cookie(settings.SESSION_COOKIE_NAME,
                         request.session.session_key, max_age=max_age,
                         expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
                         path=settings.SESSION_COOKIE_PATH,
                         secure=settings.SESSION_COOKIE_SECURE or None)
             else:
                 if agent.guid:
                     # memcacheにセッションキーをセット
                     session_key = cache.set(self.get_cache_key(agent.guid), request.session.session_key, settings.SESSION_COOKIE_AGE)
     return response
Example #10
0
def use_token(request, token_str=None, **kwargs):
    if not token_str is None:
        #print "use_token: {}".format(token_str)
        token = get_object_or_404(Token, token=token_str)
        response = HttpResponseRedirect(token.url)
        if True or not token.used:
            # our tokens are not single use so never lock them out
            response = HttpResponseRedirect(token.url)
            token.used = True
            token.save()
            signal_token_used.send(sender=use_token, request=request, token=token)
            max_age = 2592000
            expires_time = time.time() + max_age
            expires = cookie_date(expires_time)
            tokens_list = list(set(get_tokens_from_cookie(request) + [token.token]))
            tokens = '|'.join(tokens_list)
            response.set_cookie(TOKEN_COOKIE, tokens, max_age=max_age, expires=expires)
        # if token is used but user doesn't have token cookie so tell them NO
        elif not user_has_token_cookie(request, token_str=token.token):
            response = HttpResponseRedirect(
                reverse('token_used', kwargs={'token_str':token.token,}))
        # cookie's expired... answer is still no
        elif not token.valid_until is None and token.valid_until <= datetime.datetime.now():
            response = HttpResponseRedirect(reverse('token_expired'))
        # user has a cookie with that token and it's still valid
        elif token.single_use:
            token.delete()
        signal_token_visited.send(sender=use_token, request=request, token=token)
        return response
    else:
        return direct_to_template(request, template='token_auth/token_invalid.html', **kwargs)
 def process_response(self, request, response):
     """
     If request.session was modified, or if the configuration is to save the
     session every time, save the changes and set a session cookie.
     """
     try:
         accessed = request.session.accessed
         modified = request.session.modified
     except AttributeError:
         pass
     else:
         if accessed:
             patch_vary_headers(response, ('Cookie',))
         if modified or settings.SESSION_SAVE_EVERY_REQUEST:
             if request.session.get_expire_at_browser_close():
                 max_age = None
                 expires = None
             else:
                 max_age = request.session.get_expiry_age()
                 expires_time = time.time() + max_age
                 expires = cookie_date(expires_time)
             # Save the session data and refresh the client cookie.
             # Skip session save for 500 responses, refs #3881.
             if response.status_code != 500:
                 request.session.save()
                 paths = getattr(settings, 'EPO_SESSION_ACCESS_PATHS', [settings.SESSION_COOKIE_PATH])
                 for p in paths:
                     response.set_cookie(cookie_name_gen(p) if p != settings.SESSION_COOKIE_PATH else p,
                                         request.session.session_key, max_age=max_age,
                                         expires=expires, domain=get_domain(),
                                         path=p,
                                         secure=settings.SESSION_COOKIE_SECURE or None,
                                         httponly=settings.SESSION_COOKIE_HTTPONLY or None)
     return response
Example #12
0
def process_response(request, response):
    """
    If request.session was modified, or if the configuration is to save the
    session every time, save the changes and set a session cookie.
    """
    try:
        accessed = request.session.accessed
        modified = request.session.modified
    except AttributeError:
        pass
    else:
        if accessed:
            patch_vary_headers(response, ("Cookie",))
        if modified or settings.SESSION_SAVE_EVERY_REQUEST:
            if request.session.get_expire_at_browser_close():
                max_age = None
                expires = None
            else:
                max_age = request.session.get_expiry_age()
                expires_time = time.time() + max_age
                expires = cookie_date(expires_time)
                # Save the session data and refresh the client cookie.
            request.session.save()
            response.set_cookie(
                settings.SESSION_COOKIE_NAME,
                request.session.session_key,
                max_age=max_age,
                expires=expires,
                domain=settings.SESSION_COOKIE_DOMAIN,
                path=settings.SESSION_COOKIE_PATH,
                secure=settings.SESSION_COOKIE_SECURE or None,
                httponly=settings.SESSION_COOKIE_HTTPONLY or None,
            )
    return response
Example #13
0
 def process_response(self, request, response):
     if self.is_workstation_request(request):
         """
         If request.session was modified, or if the configuration is to save the
         session every time, save the changes and set a session cookie.
         """
         try:
             accessed = request.session.accessed
             modified = request.session.modified
         except AttributeError:
             pass
         else:
             if accessed:
                 patch_vary_headers(response, ('Cookie',))
             if modified or settings.SESSION_SAVE_EVERY_REQUEST:
                 if request.session.get_expire_at_browser_close():
                     max_age = None
                     expires = None
                 else:
                     max_age = request.session.get_expiry_age()
                     expires_time = time.time() + max_age
                     expires = cookie_date(expires_time)
                     # Save the session data and refresh the client cookie.
                 request.session.save()
                 response.set_cookie(self.get_session_cookie_name(request), # WB: this is the only line we changed here, all the rest is the same as original SessionMiddleware
                                     request.session.session_key, max_age=max_age,
                                     expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
                                     path=settings.SESSION_COOKIE_PATH,
                                     secure=settings.SESSION_COOKIE_SECURE or None,
                                     httponly=settings.SESSION_COOKIE_HTTPONLY or None)
         return response
     else:
         return self.django_session_middleware.process_response(request, response)
Example #14
0
    def process_response(self, request, response):
        if 'visitor_id' in request.session:
            visitor_id = request.session['visitor_id']
        elif hasattr(request, 'visitor'):
            visitor_id = request.visitor.pk
        else:
            visitor_id = None

        if visitor_id:
            # Set a cookie for the visitor ID using roughly
            # the same parameters as the session cookie
            max_age = request.session.get_expiry_age()

            response.set_cookie(
                'visitor_id',
                visitor_id,
                max_age=max_age,
                expires=cookie_date(time.time() + max_age),
                domain=settings.SESSION_COOKIE_DOMAIN,
                path=settings.SESSION_COOKIE_PATH,
                secure=False,
                httponly=False,
            )

        return response
Example #15
0
 def process_response(self, request, response):
     try:
         session = request.session
     except AttributeError:
         return response # 404 page, for instance
     if session.deleted:
         response.delete_cookie(settings.SESSION_COOKIE_NAME)
     else:
         if session.accessed:
             patch_vary_headers(response, ('Cookie',))
         if session.modified or settings.SESSION_SAVE_EVERY_REQUEST:
             if session.get_expire_at_browser_close():
                 max_age = None
                 expires = None
             else:
                 max_age = session.get_expiry_age()
                 expires = cookie_date(time() + max_age)
             cookie = session.encode(session._session)
             if len(cookie) <= MAX_COOKIE_SIZE:
                 response.set_cookie(settings.SESSION_COOKIE_NAME, cookie,
                     max_age = max_age, expires=expires,
                     domain = settings.SESSION_COOKIE_DOMAIN,
                     path = settings.SESSION_COOKIE_PATH,
                     secure = settings.SESSION_COOKIE_SECURE or None
                 )
             else:
                 # The data doesn't fit into a cookie, not sure what's the
                 # best thing to do in this case. Right now, we just leave
                 # the old cookie intact if there was one. If Django had
                 # some kind of standard logging interface, we could also
                 # log a warning here.
                 pass
     return response
Example #16
0
def standard_cookie_settings(request):
    """ Returns the common cookie settings (e.g. expiration time). """

    if request.session.get_expire_at_browser_close():
        max_age = None
        expires = None
    else:
        max_age = request.session.get_expiry_age()
        _expires_time = time.time() + max_age
        expires = cookie_date(_expires_time)

    cookie_settings = {
        'max_age': max_age,
        'expires': expires,
        'domain': settings.SESSION_COOKIE_DOMAIN,
        'path': '/',
        'httponly': None,
    }

    # In production, TLS should be enabled so that this cookie is encrypted
    # when we send it.  We also need to set "secure" to True so that the browser
    # will transmit it only over secure connections.
    #
    # In non-production environments (acceptance tests, devstack, and sandboxes),
    # we still want to set this cookie.  However, we do NOT want to set it to "secure"
    # because the browser won't send it back to us.  This can cause an infinite redirect
    # loop in the third-party auth flow, which calls `is_logged_in_cookie_set` to determine
    # whether it needs to set the cookie or continue to the next pipeline stage.
    cookie_settings['secure'] = request.is_secure()

    return cookie_settings
Example #17
0
 def process_response(self, request, response):
     # If request.session was modified, or if response.session was set, save
     # those changes and set a session cookie.
     agent = self.get_agent(request)
     try:
         accessed = request.session.accessed
         modified = request.session.modified
     except AttributeError:
         pass
     else:
         if accessed:
             patch_vary_headers(response, ('Cookie',))
         if modified or settings.SESSION_SAVE_EVERY_REQUEST:
             if request.session.get_expire_at_browser_close():
                 max_age = None
                 expires = None
             else:
                 max_age = request.session.get_expiry_age()
                 expires_time = time.time() + max_age
                 expires = cookie_date(expires_time)
             # Save the session data and refresh the client cookie.
             request.session.save()
             #request.session.modified = False  # ここでFalseにするとSessioMiddlewareで2度書きを防げるが、管理画面にログインできなくなる
             # memcacheにセッションキーをセット
             opensocial_owner_id = get_opensocial_owner_id(request)
             if opensocial_owner_id:
                 session_key = cache.set(self.get_cache_key(opensocial_owner_id), request.session.session_key, settings.SESSION_COOKIE_AGE)
     return response
Example #18
0
    def set_cookie(self, key, value="", max_age=None, expires=None, path="/", domain=None, secure=False):
        """
        Sets a cookie.

        ``expires`` can be a string in the correct format or a
        ``datetime.datetime`` object in UTC. If ``expires`` is a datetime
        object then ``max_age`` will be calculated.
        """
        self.cookies[key] = value
        if expires is not None:
            if isinstance(expires, datetime.datetime):
                delta = expires - expires.utcnow()
                # Add one second so the date matches exactly (a fraction of
                # time gets lost between converting to a timedelta and
                # then the date string).
                delta = delta + datetime.timedelta(seconds=1)
                # Just set max_age - the max_age logic will set expires.
                expires = None
                max_age = max(0, delta.days * 86400 + delta.seconds)
            else:
                self.cookies[key]["expires"] = expires
        if max_age is not None:
            self.cookies[key]["max-age"] = max_age
            # IE requires expires, so set it if hasn't been already.
            if not expires:
                self.cookies[key]["expires"] = cookie_date(time.time() + max_age)
        if path is not None:
            self.cookies[key]["path"] = path
        if domain is not None:
            self.cookies[key]["domain"] = domain
        if secure:
            self.cookies[key]["secure"] = True
Example #19
0
def rpc(request, method_name, null=False):
    if method_name[:1] == '_':
        return HttpResponseServerError('cant call private method')
    _log_call(request.browser_id, method_name, request.POST.copy())
    args = { 'request': request }
    try:
        for k, v in request.POST.items():
            args[k.encode('ascii')] = json.loads(v)
    except UnicodeEncodeError:
        return HttpResponseServerError('non-ascii chars received')
    except JSONDecodeError:
        return HttpResponseServerError('invalid json')
    rpc_module = null_rpc_views if null else rpc_views
    try:
        func = getattr(rpc_module, method_name)
    except AttributeError:
        return HttpResponseServerError('no method named ' + method_name)

    try:
        result = func(**args)
    except TypeError:
        result = {'error': 'Incorrect number of arguments'}
    
    user_message = result and result.pop("_user_message", None)
    response = HttpResponse(json.dumps(result), "application/json")
    if user_message is not None:
        response.set_cookie( "_user_message", user_message["body"], expires= cookie_date(time.time() +6), path="/")
    return response
Example #20
0
def set_user_languages_to_cookie(response, languages):
    max_age = 60*60*24
    response.set_cookie(
        settings.USER_LANGUAGES_COOKIE_NAME,
        json.dumps(languages), 
        max_age=max_age,
        expires=cookie_date(time.time() + max_age))
    def process_response(self, request, response):
        """
        If request.session was modified, or if the configuration is to save the
        session every time, save the changes and set a session cookie.
        """
        try:
            accessed = request.session.accessed
        except AttributeError:
            pass
        else:
            if accessed:
                patch_vary_headers(response, ('Cookie',))
            if True or settings.SESSION_SAVE_EVERY_REQUEST:
                if request.session.get_expire_at_browser_close():
                    max_age = None
                    expires = None
                else:
                    max_age = request.session.get_expiry_age()
                    expires_time = time.time() + max_age
                    expires = cookie_date(expires_time)
                # Save the session data and refresh the client cookie.
                request.session.save()

                #saving the user id in the cookie
                #user_info = "{'session_id':" + request.session.session_key +"/"+"anonymous_id:" + request.anonymous_id
                user_info = unicode({'session_id': request.session.session_key, 'anonymous_id': request.anonymous_id})

                user_info = quote(user_info)

                response.set_cookie(settings.SESSION_COOKIE_NAME,
                        user_info, max_age=max_age,
                        expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
                        path=settings.SESSION_COOKIE_PATH,
                        secure=settings.SESSION_COOKIE_SECURE or None)
        return response
Example #22
0
def token_logout(request, **kwargs):
    """Remove all tokens then forward to the standard logout page"""
    response = HttpResponseRedirect(reverse('logout_form'))
    max_age = 2592000
    expires_time = time.time() - max_age
    expires = cookie_date(expires_time)
    response.set_cookie(TOKEN_COOKIE, '', max_age=max_age, expires=expires)
    return response
Example #23
0
 def process_response(self, request, response):
     if not request.COOKIES.get('REFERRER', None):
         referrer = request.META.get('HTTP_REFERER', '')
         max_age = 7*24*60*60 # week
         expires_time = time.time() + max_age
         expires = cookie_date(expires_time)
         response.set_cookie('REFERRER', referrer, max_age=max_age, expires=expires)
     return response
Example #24
0
 def process_response(self, request, response):
     if not request.clienttrack_first_visit:
             max_age = 3*365*24*60*60  # 3 years
             expires_time = time.time() + max_age
             expires = cookie_date(expires_time)
             response.set_cookie('_hda', "%d,%s" % (time.time(), request.clienttrack_uid),
                                 max_age=max_age, expires=expires)
     return response
Example #25
0
    def process_request(self, request):
        if not getattr(settings, "MOBILE_DOMAIN", False):
            return

        # Cookie settings
        max_age = getattr(settings, "MOBILE_COOKIE_MAX_AGE", DEFAULT_COOKIE_MAX_AGE)
        expires_time = time.time() + max_age
        expires = cookie_date(expires_time)

        # test for browser return
        if (
            # is mobile?
            is_mobile(request.META.get("HTTP_USER_AGENT", ""))
            and
            # but has param m2w?
            request.GET.get("m2w", False)
            and
            # does currently not have a is browser cookie with 1
            request.COOKIES.get("isbrowser", "0") == "0"
        ):
            """ Set a cookie for Mobile 2 Web if a mobile browser does not want to browse mobile """
            response = HttpResponseRedirect(request.META.get("PATH_INFO", "/"))
            response.set_cookie(
                "ismobile", "0", domain=settings.SESSION_COOKIE_DOMAIN, max_age=max_age, expires=expires
            )
            response.set_cookie(
                "isbrowser", "1", domain=settings.SESSION_COOKIE_DOMAIN, max_age=max_age, expires=expires
            )
            return response

        # test for mobile browser
        if (
            # check for override cookie, do not check if present
            request.COOKIES.get("ismobile", "0") == "1"
            or (
                # browser info present
                "HTTP_USER_AGENT" in request.META
                and
                # desktop browser override not set
                request.COOKIES.get("isbrowser", "0") != "1"
                and
                # check browser type
                is_mobile(request.META.get("HTTP_USER_AGENT", ""))
                and
                # check whether ipad should be redirected
                self.redirect_ipad(request.META.get("HTTP_USER_AGENT", ""))
            )
        ):
            redirect = settings.MOBILE_DOMAIN
            if getattr(settings, "MOBILE_REDIRECT_PRESERVE_URL", False):
                redirect = redirect.rstrip("/") + request.path_info

            # redirect to mobile domain
            response = HttpResponseRedirect(redirect)
            response.set_cookie(
                "ismobile", "1", domain=settings.SESSION_COOKIE_DOMAIN, max_age=max_age, expires=expires
            )
            return response
Example #26
0
    def set_cookie(
        cls,
        message,
        key,
        value="",
        max_age=None,
        expires=None,
        path="/",
        domain=None,
        secure=False,
        httponly=False,
    ):
        """
        Sets a cookie in the passed HTTP response message.

        ``expires`` can be:
        - a string in the correct format,
        - a naive ``datetime.datetime`` object in UTC,
        - an aware ``datetime.datetime`` object in any time zone.
        If it is a ``datetime.datetime`` object then ``max_age`` will be calculated.
        """
        value = force_str(value)
        cookies = SimpleCookie()
        cookies[key] = value
        if expires is not None:
            if isinstance(expires, datetime.datetime):
                if timezone.is_aware(expires):
                    expires = timezone.make_naive(expires, timezone.utc)
                delta = expires - expires.utcnow()
                # Add one second so the date matches exactly (a fraction of
                # time gets lost between converting to a timedelta and
                # then the date string).
                delta = delta + datetime.timedelta(seconds=1)
                # Just set max_age - the max_age logic will set expires.
                expires = None
                max_age = max(0, delta.days * 86400 + delta.seconds)
            else:
                cookies[key]["expires"] = expires
        else:
            cookies[key]["expires"] = ""
        if max_age is not None:
            cookies[key]["max-age"] = max_age
            # IE requires expires, so set it if hasn't been already.
            if not expires:
                cookies[key]["expires"] = cookie_date(time.time() + max_age)
        if path is not None:
            cookies[key]["path"] = path
        if domain is not None:
            cookies[key]["domain"] = domain
        if secure:
            cookies[key]["secure"] = True
        if httponly:
            cookies[key]["httponly"] = True
        # Write out the cookies to the response
        for c in cookies.values():
            message.setdefault("headers", []).append(
                (b"Set-Cookie", bytes(c.output(header=""), encoding="utf-8")),
            )
Example #27
0
    def process_response(self, request, response):
        """
        If request.session was modified, or if the configuration is to save the
        session every time, save the changes and set a session cookie.
        """
        if self.should_process(request):
            try:
                accessed = request.session.accessed
                modified = request.session.modified
            except AttributeError:
                pass
            else:
                if accessed:
                    patch_vary_headers(response, ('Cookie',))
                if modified or settings.SESSION_SAVE_EVERY_REQUEST:
                    if request.session.get_expire_at_browser_close():
                        max_age = None
                        expires = None
                    else:
                        max_age = request.session.get_expiry_age()
                        expires_time = time.time() + max_age
                        expires = cookie_date(expires_time)
                    # Save the session data and refresh the client cookie.
                    request.session.save()
                    response["P3P"] = "CP=CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"
                    response.set_cookie(settings.SESSION_COOKIE_NAME,
                                        request.session.session_key, max_age=max_age,
                                        expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
                                        path=settings.SESSION_COOKIE_PATH,
                                        secure=settings.SESSION_COOKIE_SECURE or None,
                                        httponly=settings.SESSION_COOKIE_HTTPONLY or None)

                    if not (settings.TMP_SESSION_COOKIE_NAME in request.session and request.session[settings.TMP_SESSION_COOKIE_NAME]):
                        # processing data
                        (is_verified, data) = get_and_verify_data(request)
                        if is_verified:
                            # create temp session key, refresh everytime when users close their browser.
                                token = data.get('k')
                                project = Project.objects.get(token=token)
                                tmp_obj = Session.objects.create_new(project)
                                tmp_obj.project = project
                                tmp_obj.permanent_session_key = request.session.session_key
                                tmp_obj.ipaddress = request.META.get('REMOTE_ADDR', '0.0.0.0')
                                tmp_obj.user_timezone = request.META.get('TZ', '')
                                tmp_obj.set_user_agent(request.META.get('HTTP_USER_AGENT', ''))
                                tmp_obj.set_referrer(data.get('r'))
                                tmp_obj.save()

                                request.session[settings.TMP_SESSION_COOKIE_NAME] = tmp_obj.session_key
                                response.set_cookie(settings.TMP_SESSION_COOKIE_NAME,
                                                    request.session[settings.TMP_SESSION_COOKIE_NAME], max_age=None,
                                                    expires=None, domain=settings.SESSION_COOKIE_DOMAIN,
                                                    path=settings.SESSION_COOKIE_PATH,
                                                    secure=settings.SESSION_COOKIE_SECURE or None,
                                                    httponly=settings.SESSION_COOKIE_HTTPONLY or None)
            
                analysis(request, response)
        return response
Example #28
0
    def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse:
        try:
            request.get_host()
        except DisallowedHost:
            # If we get a DisallowedHost exception trying to access
            # the host, (1) the request is failed anyway and so the
            # below code will do nothing, and (2) the below will
            # trigger a recursive exception, breaking things, so we
            # just return here.
            return response

        if (not request.path.startswith("/static/") and not request.path.startswith("/api/") and
                not request.path.startswith("/json/")):
            subdomain = get_subdomain(request)
            if subdomain != Realm.SUBDOMAIN_FOR_ROOT_DOMAIN:
                realm = get_realm(subdomain)
                if (realm is None):
                    return render(request, "zerver/invalid_realm.html")
        """
        If request.session was modified, or if the configuration is to save the
        session every time, save the changes and set a session cookie.
        """
        try:
            accessed = request.session.accessed
            modified = request.session.modified
        except AttributeError:
            pass
        else:
            if accessed:
                patch_vary_headers(response, ('Cookie',))
            if modified or settings.SESSION_SAVE_EVERY_REQUEST:
                if request.session.get_expire_at_browser_close():
                    max_age = None
                    expires = None
                else:
                    max_age = request.session.get_expiry_age()
                    expires_time = time.time() + max_age
                    expires = cookie_date(expires_time)
                # Save the session data and refresh the client cookie.
                # Skip session save for 500 responses, refs #3881.
                if response.status_code != 500:
                    request.session.save()
                    host = request.get_host().split(':')[0]

                    # The subdomains feature overrides the
                    # SESSION_COOKIE_DOMAIN setting, since the setting
                    # is a fixed value and with subdomains enabled,
                    # the session cookie domain has to vary with the
                    # subdomain.
                    session_cookie_domain = host
                    response.set_cookie(settings.SESSION_COOKIE_NAME,
                                        request.session.session_key, max_age=max_age,
                                        expires=expires, domain=session_cookie_domain,
                                        path=settings.SESSION_COOKIE_PATH,
                                        secure=settings.SESSION_COOKIE_SECURE or None,
                                        httponly=settings.SESSION_COOKIE_HTTPONLY or None)
        return response
Example #29
0
    def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse:
        try:
            request.get_host()
        except DisallowedHost:
            # If we get a DisallowedHost exception trying to access
            # the host, (1) the request is failed anyway and so the
            # below code will do nothing, and (2) the below will
            # trigger a recursive exception, breaking things, so we
            # just return here.
            return response

        if (not request.path.startswith("/static/") and not request.path.startswith("/api/") and
                not request.path.startswith("/json/")):
            subdomain = get_subdomain(request)
            if subdomain != Realm.SUBDOMAIN_FOR_ROOT_DOMAIN:
                realm = get_realm(subdomain)
                if (realm is None):
                    return render(request, "zerver/invalid_realm.html")
        """
        If request.session was modified, or if the configuration is to save the
        session every time, save the changes and set a session cookie.
        """
        try:
            accessed = request.session.accessed
            modified = request.session.modified
        except AttributeError:
            pass
        else:
            if accessed:
                patch_vary_headers(response, ('Cookie',))
            if modified or settings.SESSION_SAVE_EVERY_REQUEST:
                if request.session.get_expire_at_browser_close():
                    max_age = None
                    expires = None
                else:
                    max_age = request.session.get_expiry_age()
                    expires_time = time.time() + max_age
                    expires = cookie_date(expires_time)
                # Save the session data and refresh the client cookie.
                # Skip session save for 500 responses, refs #3881.
                if response.status_code != 500:
                    request.session.save()
                    host = request.get_host().split(':')[0]

                    # The subdomains feature overrides the
                    # SESSION_COOKIE_DOMAIN setting, since the setting
                    # is a fixed value and with subdomains enabled,
                    # the session cookie domain has to vary with the
                    # subdomain.
                    session_cookie_domain = host
                    response.set_cookie(settings.SESSION_COOKIE_NAME,
                                        request.session.session_key, max_age=max_age,
                                        expires=expires, domain=session_cookie_domain,
                                        path=settings.SESSION_COOKIE_PATH,
                                        secure=settings.SESSION_COOKIE_SECURE or None,
                                        httponly=settings.SESSION_COOKIE_HTTPONLY or None)
        return response
Example #30
0
 def process_response(self, request, response):
     """Set location cookie."""
     location = getattr(request, 'location', None)
     if location:
         max_age = settings.LOCATION_COOKIE_AGE_SECONDS
         expires_time = time.time() + max_age
         expires = cookie_date(expires_time)
         response.set_cookie(settings.LOCATION_COOKIE_NAME, location, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN)
     return response
Example #31
0
def _set_cookie(response, name, value, duration):
    max_age = duration
    expires_time = time.time() + max_age
    expires = cookie_date(expires_time)
    response.set_cookie(name,
                        value,
                        max_age=max_age,
                        expires=expires)
    return response
Example #32
0
def set_auth_cookie(response,
                    auth_token,
                    expires=AUTH_EXPIRES,
                    domain=AUTH_COOKIE_DOMAIN):
    expire_date = cookie_date(int(time() + expires)) if expires > 0 else None
    response.set_cookie(AUTH_COOKIE_KEY,
                        auth_token,
                        expires=expire_date,
                        domain=domain)
Example #33
0
 def test_max_age_expiration(self):
     "Cookie will expire if max_age is provided"
     response = HttpResponse()
     set_cookie_time = time.time()
     with freeze_time(set_cookie_time):
         response.set_cookie('max_age', max_age=10)
     max_age_cookie = response.cookies['max_age']
     self.assertEqual(max_age_cookie['max-age'], 10)
     self.assertEqual(max_age_cookie['expires'], cookie_date(set_cookie_time + 10))
Example #34
0
    def __init__(self, redirect_to, msg):
        HttpResponseRedirect.__init__(self, redirect_to)
        if msg:
            # We just keep the message two seconds.
            max_age = 2
            expires_time = time.time() + max_age
            expires = cookie_date(expires_time)

            self.set_cookie("message", lfs_quote(msg), max_age=max_age, expires=expires)
Example #35
0
    def process_response(self, request, response):
        """
        If request.session was modified, or if the configuration is to save the
        session every time, save the changes and set a session cookie or delete
        the session cookie if the session has been emptied.
        """
        try:
            accessed = request.session.accessed
            modified = request.session.modified
            empty = request.session.is_empty()
        except AttributeError:
            pass  #对于没有request.session的response直接放行
        else:
            # First check if we need to delete this cookie.
            # The session should be deleted only if the session is entirely empty
            if settings.SESSION_COOKIE_NAME in request.COOKIES and empty:
                response.delete_cookie(
                    settings.SESSION_COOKIE_NAME,
                    path=settings.SESSION_COOKIE_PATH,
                    domain=settings.SESSION_COOKIE_DOMAIN,
                )
            else:
                if accessed:
                    patch_vary_headers(response, ('Cookie', ))

                # 对改变的session或every_request才更新session data并更新session cookie
                if (modified
                        or settings.SESSION_SAVE_EVERY_REQUEST) and not empty:
                    if request.session.get_expire_at_browser_close():
                        max_age = None
                        expires = None
                    else:
                        max_age = request.session.get_expiry_age()
                        expires_time = time.time() + max_age
                        expires = cookie_date(expires_time)
                    # Save the session data and refresh the client cookie.
                    # Skip session save for 500 responses, refs #3881.
                    if response.status_code != 500:
                        try:
                            request.session.save()
                        except UpdateError:
                            raise SuspiciousOperation(
                                "The request's session was deleted before the "
                                "request completed. The user may have logged "
                                "out in a concurrent request, for example.")
                        response.set_cookie(  # 更新会话cookie
                            settings.SESSION_COOKIE_NAME,
                            request.session.session_key,
                            max_age=max_age,
                            expires=expires,
                            domain=settings.SESSION_COOKIE_DOMAIN,
                            path=settings.SESSION_COOKIE_PATH,
                            secure=settings.SESSION_COOKIE_SECURE or None,
                            httponly=settings.SESSION_COOKIE_HTTPONLY or None,
                        )
        return response
Example #36
0
def set_message_to(response, msg):
    """Sets message cookie with passed message to passed response.
    """
    # We just keep the message two seconds.
    max_age = 2
    expires_time = time.time() + max_age
    expires = cookie_date(expires_time)
    if msg:
        response.set_cookie("message", lfs_quote(msg), max_age=max_age, expires=expires)
    return response
Example #37
0
 def set_persistent_login(request, response):
     max_age = settings.SESSION_COOKIE_AGE
     expires = cookie_date(time.time() + max_age)
     #cookie中加入用户自动登录标志, persistent_login:uuid
     value = uuid.uuid4()
     response.set_cookie(Cookie.c_login,
                         value,
                         max_age=max_age,
                         expires=expires)
     request.session[Cookie.s_login] = value
Example #38
0
    def process_response(self, request, response):
        """
        process the response, adding appropriate set-cookie
        headers if necessary.

        If there is an authenticated user, a cookie should be added
        representing that user's login information to pluck.

        If the authenticated user disappears but the at cookie remains,
        the at cookie should be deleted.
        """
        logger.debug('Starting SharedAuthProviderMiddleware.process_response')

        # get a handle to the get_cookie_domain function
        get_cookie_domain = getattr(settings,
            'SHARED_AUTH_GET_COOKIE_DOMAIN',
            get_cookie_domain_from_settings
        )
        try:
            modify = False
            if 'UPDATE_SHAREDAUTH_COOKIE' in dict(response.items()):
                response.__delitem__('UPDATE_SHAREDAUTH_COOKIE')
                modify = True
                logger.debug('modifying cookie')

            if getattr(request, 'session', None) and \
                    hasattr(request, 'user') and \
                    request.user.is_authenticated() and \
                    (modify or not request.COOKIES.has_key(settings.COOKIE_NAME)):

                if request.session.get_expire_at_browser_close():
                    max_age = None
                    expires = None
                else:
                    max_age = request.session.get_expiry_age()
                    expires_time = time.time() + max_age
                    expires = cookie_date(expires_time)
                response.set_cookie(settings.COOKIE_NAME,
                        SharedAuthBackend.getCookieStr(request.user),
                        max_age=max_age,
                        expires=expires,
                        domain=get_cookie_domain(request),
                        path=settings.COOKIE_PATH,
                        secure=settings.SECURE)
            if getattr(request, 'session', None) and \
                    not (hasattr(request, 'user') and \
                    request.user.is_authenticated()) and \
                    request.COOKIES.has_key(settings.COOKIE_NAME):
                response.delete_cookie(settings.COOKIE_NAME,
                    path=settings.COOKIE_PATH,
                    domain=get_cookie_domain(request))
            return response
        except Exception, e:
            logger.exception(e)
            return response
Example #39
0
def message(request, message_id):
    user = request.user
    messages = Message.objects.for_user_or_author(user).filter(id=message_id)
    if len(messages) != 1:
        return HttpResponseForbidden("Not allowed")
    hide_thread = request.GET.get('hide_thread')
    message_thread = Message.objects.thread(messages[0], user)
    message_thread_length = message_thread.count()
    if not hide_thread:
        messages = message_thread

    reply = request.GET.get('reply')

    if reply:
        try:
            reply_msg = Message.objects.get(pk=reply, user=user)
            reply_msg.read = True
            reply_msg.save()
            extra_context['reply_msg'] = reply_msg
        except (Message.DoesNotExist, ValueError):
            pass

    messages.filter(user=user).update(read=True)

    extra_context = {
        'send_message_form':
        SendMessageForm(request.user, auto_id='message_form_id_%s'),
        'messages_display':
        True,
        'user_info':
        user,
        'subject':
        messages[0].subject,
        'mid':
        message_id,
        'thread_length':
        message_thread_length
    }

    response = object_list(request,
                           queryset=messages,
                           paginate_by=MESSAGES_ON_PAGE,
                           template_name='messages/message.html',
                           template_object_name='message',
                           extra_context=extra_context)
    try:
        last_message = messages[0]
        max_age = 60 * 60 * 24 * 365
        expires = cookie_date(time.time() + max_age)
        response.set_cookie(Message.hide_cookie_name, last_message.pk, max_age,
                            expires)
    except Message.DoesNotExist:
        pass
    return response
 def process_response(self, request, response):
     """
     If request.session was modified, or if the configuration is to save the
     session every time, save the changes and set a session cookie or delete
     the session cookie if the session has been emptied.
     """
     try:
         accessed = request.session.accessed
         modified = request.session.modified
         empty = request.session.is_empty()
     except AttributeError:
         pass
     else:
         # First check if we need to delete this cookie.
         # The session should be deleted only if the session is entirely empty
         if settings.SESSION_COOKIE_NAME in request.COOKIES and empty:
             response.delete_cookie(
                 settings.SESSION_COOKIE_NAME,
                 path=settings.SESSION_COOKIE_PATH,
                 domain=settings.SESSION_COOKIE_DOMAIN,
             )
         else:
             if accessed:
                 patch_vary_headers(response, ('Cookie', ))
             if (modified
                     or settings.SESSION_SAVE_EVERY_REQUEST) and not empty:
                 if request.session.get_expire_at_browser_close():
                     max_age = None
                     expires = None
                 else:
                     max_age = request.session.get_expiry_age()
                     expires_time = time.time() + max_age
                     expires = cookie_date(expires_time)
                 # Save the session data and refresh the client cookie.
                 # Skip session save for 500 responses, refs #3881.
                 if response.status_code != 500:
                     try:
                         request.session.save()
                     except UpdateError:
                         # The user is now logged out; redirecting to same
                         # page will result in a redirect to the login page
                         # if required.
                         return redirect(request.path)
                     response.set_cookie(
                         settings.SESSION_COOKIE_NAME,
                         request.session.session_key,
                         max_age=max_age,
                         expires=expires,
                         domain=settings.SESSION_COOKIE_DOMAIN,
                         path=settings.SESSION_COOKIE_PATH,
                         secure=settings.SESSION_COOKIE_SECURE or None,
                         httponly=settings.SESSION_COOKIE_HTTPONLY or None,
                     )
     return response
Example #41
0
 def process_response(self, request, response):
     if not request.clienttrack_first_visit:
         max_age = 3 * 365 * 24 * 60 * 60  # 3 years
         expires_time = time.time() + max_age
         expires = cookie_date(expires_time)
         response.set_cookie('_hda',
                             "%d,%s" %
                             (time.time(), request.clienttrack_uid),
                             max_age=max_age,
                             expires=expires)
     return response
Example #42
0
    def process_response(self, request, response):
        # type: (HttpRequest, HttpResponse) -> HttpResponse
        if settings.REALMS_HAVE_SUBDOMAINS:
            if (not request.path.startswith("/static/") and not request.path.startswith("/api/")
                and not request.path.startswith("/json/")):
                subdomain = get_subdomain(request)
                if (request.get_host() == "127.0.0.1:9991" or request.get_host() == "localhost:9991"):
                    return redirect("%s%s" % (settings.EXTERNAL_URI_SCHEME,
                                              settings.EXTERNAL_HOST))
                if subdomain != "":
                    realm = resolve_subdomain_to_realm(subdomain)
                    if (realm is None):
                        return render_to_response("zerver/invalid_realm.html")
        """
        If request.session was modified, or if the configuration is to save the
        session every time, save the changes and set a session cookie.
        """
        try:
            accessed = request.session.accessed
            modified = request.session.modified
        except AttributeError:
            pass
        else:
            if accessed:
                patch_vary_headers(response, ('Cookie',))
            if modified or settings.SESSION_SAVE_EVERY_REQUEST:
                if request.session.get_expire_at_browser_close():
                    max_age = None
                    expires = None
                else:
                    max_age = request.session.get_expiry_age()
                    expires_time = time.time() + max_age
                    expires = cookie_date(expires_time)
                # Save the session data and refresh the client cookie.
                # Skip session save for 500 responses, refs #3881.
                if response.status_code != 500:
                    request.session.save()
                    host = request.get_host().split(':')[0]

                    session_cookie_domain = settings.SESSION_COOKIE_DOMAIN
                    # The subdomains feature overrides the
                    # SESSION_COOKIE_DOMAIN setting, since the setting
                    # is a fixed value and with subdomains enabled,
                    # the session cookie domain has to vary with the
                    # subdomain.
                    if settings.REALMS_HAVE_SUBDOMAINS:
                        session_cookie_domain = host
                    response.set_cookie(settings.SESSION_COOKIE_NAME,
                            request.session.session_key, max_age=max_age,
                            expires=expires, domain=session_cookie_domain,
                            path=settings.SESSION_COOKIE_PATH,
                            secure=settings.SESSION_COOKIE_SECURE or None,
                            httponly=settings.SESSION_COOKIE_HTTPONLY or None)
        return response
Example #43
0
    def __init__(self, redirect_to, msg):
        HttpResponseRedirect.__init__(self, redirect_to)
        if msg:
            # We just keep the message two seconds.
            max_age = 2
            expires_time = time.time() + max_age
            expires = cookie_date(expires_time)

            self.set_cookie("message",
                            lfs_quote(msg),
                            max_age=max_age,
                            expires=expires)
Example #44
0
def _set_expires_in_cookie_settings(cookie_settings, expires_in):
    """
    Updates the max_age and expires fields of the given cookie_settings,
    based on the value of expires_in.
    """
    expires_time = time.time() + expires_in
    expires = cookie_date(expires_time)

    cookie_settings.update({
        'max_age': expires_in,
        'expires': expires,
    })
Example #45
0
 async def send(self, message):
     """
     Overridden send that also does session saves/cookies.
     """
     # Only save session if we're the outermost session middleware
     if self.activated:
         modified = self.scope["session"].modified
         empty = self.scope["session"].is_empty()
         # If this is a message type that we want to save on, and there's
         # changed data, save it. We also save if it's empty as we might
         # not be able to send a cookie-delete along with this message.
         if message["type"] in self.middleware.save_message_types and \
            message.get("status", 200) != 500 and \
            (modified or settings.SESSION_SAVE_EVERY_REQUEST):
             self.save_session()
             # If this is a message type that can transport cookies back to the
             # client, then do so.
             if message[
                     "type"] in self.middleware.cookie_response_message_types:
                 if empty:
                     # Delete cookie if it's set
                     if settings.SESSION_COOKIE_NAME in self.scope[
                             "cookies"]:
                         CookieMiddleware.delete_cookie(
                             message,
                             settings.SESSION_COOKIE_NAME,
                             path=settings.SESSION_COOKIE_PATH,
                             domain=settings.SESSION_COOKIE_DOMAIN,
                         )
                 else:
                     # Get the expiry data
                     if self.scope["session"].get_expire_at_browser_close():
                         max_age = None
                         expires = None
                     else:
                         max_age = self.scope["session"].get_expiry_age()
                         expires_time = time.time() + max_age
                         expires = cookie_date(expires_time)
                     # Set the cookie
                     CookieMiddleware.set_cookie(
                         message,
                         self.middleware.cookie_name,
                         self.scope["session"].session_key,
                         max_age=max_age,
                         expires=expires,
                         domain=settings.SESSION_COOKIE_DOMAIN,
                         path=settings.SESSION_COOKIE_PATH,
                         secure=settings.SESSION_COOKIE_SECURE or None,
                         httponly=settings.SESSION_COOKIE_HTTPONLY or None,
                     )
     # Pass up the send
     return await self.real_send(message)
Example #46
0
def set_message_cookie(url, msg):
    """Returns a HttpResponseRedirect object with passed url and set cookie
    ``message`` with passed message.
    """
    # We just keep the message two seconds.
    max_age = 2
    expires_time = time.time() + max_age
    expires = cookie_date(expires_time)

    response = HttpResponseRedirect(url)
    response.set_cookie("message", lfs_quote(msg), max_age=max_age, expires=expires)

    return response
Example #47
0
def delete_jwt_cookie(request, response):
    max_age = request.session.get_expiry_age()
    anti_expires_time = cookie_date(time.time() - max_age)

    response.set_cookie(
        jwt_settings.JWT_COOKIE_NAME,
        '',
        domain=settings.COOKIE_DOMAIN,
        expires=anti_expires_time,
        secure=settings.JWT_COOKIE_SECURE or None,
        httponly=settings.JWT_COOKIE_HTTPONLY or None,
        samesite='Lax',
    )
Example #48
0
def expire_token(request, token_str=None, **kwargs):
    response = HttpResponseRedirect(reverse('token_list'))
    if not token_str is None:
        max_age = 2592000
        expires_time = time.time() - max_age
        expires = cookie_date(expires_time)
        token = Token.objects.get(token__exact=token_str)
        token.valid_until = datetime.datetime.now()
        token.save()
        response.set_cookie(TOKEN_COOKIE, '', max_age=max_age, expires=expires)
    else:
        pass
    return response
Example #49
0
 def process_response(self, request, response):
     if hasattr(request, 'browser_id'):
         browser_id = request.browser_id
         if request.COOKIES.get(UUID_COOKIE_NAME) != browser_id:
             max_age = 60 * 60 * 24 * 365
             response.set_cookie(UUID_COOKIE_NAME,
                                 browser_id,
                                 max_age=max_age,
                                 expires=cookie_date(time.time() + max_age),
                                 domain=UUID_COOKIE_DOMAIN)
     # Content varies with the CSRF cookie, so set the Vary header.
     patch_vary_headers(response, ('Cookie', ))
     return response
Example #50
0
    def set_cookie(
        self,
        key,
        value="",
        max_age=None,
        expires=None,
        path="/",
        domain=None,
        secure=False,
        httponly=False,
    ):
        """
        Set a cookie.

        ``expires`` can be:
        - a string in the correct format,
        - a naive ``datetime.datetime`` object in UTC,
        - an aware ``datetime.datetime`` object in any time zone.
        If it is a ``datetime.datetime`` object then calculate ``max_age``.
        """
        self.cookies[key] = value
        if expires is not None:
            if isinstance(expires, datetime.datetime):
                if timezone.is_aware(expires):
                    expires = timezone.make_naive(expires, timezone.utc)
                delta = expires - expires.utcnow()
                # Add one second so the date matches exactly (a fraction of
                # time gets lost between converting to a timedelta and
                # then the date string).
                delta = delta + datetime.timedelta(seconds=1)
                # Just set max_age - the max_age logic will set expires.
                expires = None
                max_age = max(0, delta.days * 86400 + delta.seconds)
            else:
                self.cookies[key]["expires"] = expires
        else:
            self.cookies[key]["expires"] = ""
        if max_age is not None:
            self.cookies[key]["max-age"] = max_age
            # IE requires expires, so set it if hasn't been already.
            if not expires:
                self.cookies[key]["expires"] = cookie_date(time.time() +
                                                           max_age)
        if path is not None:
            self.cookies[key]["path"] = path
        if domain is not None:
            self.cookies[key]["domain"] = domain
        if secure:
            self.cookies[key]["secure"] = True
        if httponly:
            self.cookies[key]["httponly"] = True
Example #51
0
def set_cookie(request, response, domain=COOKIE_DOMAIN, path=COOKIE_PATH):
    """Given request set and AdMob cookie on response.    """
    # Don't make a new cookie if one exists.
    if 'admobuu' in request.COOKIES or 'admobuu' in response.cookies:
        return response

    value = getattr(request, 'admobuu', cookie_value(request))
    expires = cookie_date(0x7fffffff)  # End of 32 bit time.
    response.set_cookie('admobuu',
                        value,
                        expires=expires,
                        path=path,
                        domain=domain)
    return response
Example #52
0
def inbox(request, message_pk=None):
    user = request.user
    qs = Message.objects.for_user(user)

    extra_context = {
        'send_message_form':
        SendMessageForm(request.user, auto_id='message_form_id_%s'),
        'messages_display':
        True,
        'user_info':
        user
    }

    type_filter = request.GET.get('type')
    if type_filter:
        if type_filter != 'any':
            qs = qs.filter(message_type=type_filter)

    reply = request.GET.get('reply')

    if reply:
        try:
            reply_msg = Message.objects.get(pk=reply, user=user)
            reply_msg.read = True
            reply_msg.save()
            extra_context['reply_msg'] = reply_msg
        except (Message.DoesNotExist, ValueError):
            pass
    filtered = bool(set(request.GET.keys()).intersection(['type']))

    extra_context['type_filter'] = type_filter
    extra_context['filtered'] = filtered

    response = object_list(request,
                           queryset=qs,
                           paginate_by=MESSAGES_ON_PAGE,
                           template_name='messages/inbox.html',
                           template_object_name='message',
                           extra_context=extra_context)
    try:
        last_message = qs[:1].get()
        max_age = 60 * 60 * 24 * 365
        expires = cookie_date(time.time() + max_age)
        response.set_cookie(Message.hide_cookie_name, last_message.pk, max_age,
                            expires)
    except Message.DoesNotExist:
        pass

    return response
Example #53
0
 def persist_modernizr(self, request, response):
     data = request.GET
     if settings.MODERNIZR_STORAGE == 'cookie':
         response.set_cookie(settings.MODERNIZR_COOKIE_NAME,
             data.urlencode(),
             max_age=settings.MODERNIZR_COOKIE_AGE,
             expires=cookie_date(settings.MODERNIZR_COOKIE_AGE),
             domain=settings.MODERNIZR_COOKIE_DOMAIN,
             path=settings.MODERNIZR_COOKIE_PATH,
             secure=settings.MODERNIZR_COOKIE_DOMAIN or None)
     elif settings.MODERNIZR_STORAGE == 'session':
         request.session[settings.MODERNIZR_SESSION_KEY] = data
     else:
         raise ValueError("Invalid value for settings.MODERNIZR_STORAGE")
     return response
Example #54
0
    def get(self, request, *args, **kwargs):
        response = HttpResponse('', content_type='text/javascript')
        try:
            message = self.decrypt_payload(
                urlsafe_base64_decode(kwargs.get('message')))

            is_session_empty = request.session.is_empty()

            # replace session cookie only when session is empty or when always replace is set
            if is_session_empty or getattr(
                    settings, 'SHARED_SESSION_ALWAYS_REPLACE', False):
                http_host = request.META['HTTP_HOST']

                if (timezone.now() -
                        parse(message['ts'])).total_seconds() < getattr(
                            settings, 'SHARED_SESSION_TIMEOUT', 30):
                    if request.session.get_expire_at_browser_close():
                        max_age = None
                        expires = None
                    else:
                        max_age = request.session.get_expiry_age()
                        expires_time = time.time() + max_age
                        expires = cookie_date(expires_time)

                    response.set_cookie(
                        settings.SESSION_COOKIE_NAME,
                        message['key'],
                        max_age=max_age,
                        expires=expires,
                        domain=settings.SESSION_COOKIE_DOMAIN,
                        path=settings.SESSION_COOKIE_PATH,
                        secure=settings.SESSION_COOKIE_SECURE or None,
                        httponly=settings.SESSION_COOKIE_HTTPONLY or None,
                    )

                    # ensure CSRF cookie is set
                    get_token(request)

                    # emit signal
                    signals.session_replaced.send(sender=self.__class__,
                                                  request=request,
                                                  was_empty=is_session_empty,
                                                  src_domain=message['src'],
                                                  dst_domain=http_host)
        except (CryptoError, ValueError):
            pass

        return response
Example #55
0
 def process_response(self, request, response):
     """
     If request.session was modified, or if the configuration is to save the
     session every time, save the changes and set a session cookie or delete
     the session cookie if the session has been emptied.
     """
     try:
         accessed = request.session.accessed
         modified = request.session.modified
         empty = request.session.is_empty()
     except AttributeError:
         pass
     else:
         # First check if we need to delete this cookie.
         # The session should be deleted only if the session is entirely empty
         if settings.SESSION_COOKIE_NAME in request.COOKIES and empty:
             response.delete_cookie(settings.SESSION_COOKIE_NAME,
                                    domain=settings.SESSION_COOKIE_DOMAIN)
         else:
             # 访问过就设置Vary Cookie,为什么
             # 分析:猜测的:如果开启了中间件,但是从没访问过session,那么完全没必要设置cookie,
             # 也没必要VaryCookie,没有访问过也就意味着没有修改过,所以不会设置cookie,也不会设置vary on
             # cookie,如果访问过,那么必须设置vary头,如果修改过,则也要重新设置cookie.
             if accessed:
                 patch_vary_headers(response, ('Cookie', ))
             if (modified
                     or settings.SESSION_SAVE_EVERY_REQUEST) and not empty:
                 if request.session.get_expire_at_browser_close():
                     max_age = None
                     expires = None
                 else:
                     max_age = request.session.get_expiry_age()
                     expires_time = time.time() + max_age
                     expires = cookie_date(expires_time)
                 # Save the session data and refresh the client cookie.
                 # Skip session save for 500 responses, refs #3881.
                 if response.status_code != 500:
                     request.session.save()
                     response.set_cookie(
                         settings.SESSION_COOKIE_NAME,
                         request.session.session_key,
                         max_age=max_age,
                         expires=expires,
                         domain=settings.SESSION_COOKIE_DOMAIN,
                         path=settings.SESSION_COOKIE_PATH,
                         secure=settings.SESSION_COOKIE_SECURE or None,
                         httponly=settings.SESSION_COOKIE_HTTPONLY or None)
     return response
Example #56
0
def setcookienumber(request):

    lucky_number = 'No cookie'
    if request.method == "POST" and 'lucky_number' in request.POST.keys():
        print('set cookie page')
        lucky_number_get = request.POST['lucky_number']
        ps('lucky_number_get', lucky_number_get)
        set_c(request, 'lucky_number', lucky_number_get)

        ##設定完cookie後,導向某個功能
        response = HttpResponseRedirect('/testfunc/setcookienumber')

        # set the login cookie for the edx marketing site
        # we want this cookie to be accessed via javascript
        # so httponly is set to None

        if request.session.get_expire_at_browser_close():
            max_age = None
            expires = None
        else:
            max_age = request.session.get_expiry_age()
            ps('max_age', max_age)
            expires_time = time.time() + max_age
            expires = cookie_date(expires_time)

        ps('settings.SESSION_COOKIE_DOMAIN', settings.SESSION_COOKIE_DOMAIN)
        ps('expires', expires)

        response.set_cookie('lucky_number',
                            lucky_number_get,
                            max_age=max_age,
                            expires=expires,
                            domain=settings.SESSION_COOKIE_DOMAIN,
                            path='/',
                            secure=None,
                            httponly=None)
        return response

    print('request.COOKIES.keys()', request.COOKIES)
    if 'lucky_number' in request.COOKIES:
        lucky_number = request.COOKIES['lucky_number']
        ps('lucky_number', lucky_number)

    ##HttpRequest.session.set_test_cookie()
    #HttpRequest.Session.test_cookie_worked()
    return render(request, 'testfunc/setcookienumber.html',
                  {'lucky_number': lucky_number})
Example #57
0
 def process_response(self, request, response):
     """
     If request.session was modified, or if the configuration is to save the
     session every time, save the changes and set a session cookie or delete
     the session cookie if the session has been emptied.
     """
     try:
         accessed = request.session.accessed
         print str(accessed)
         modified = request.session.modified
         print str(modified)
         empty = request.session.is_empty()
         print str(empty)
     except AttributeError:
         pass
     else:
         # First check if we need to delete this cookie.
         # The session should be deleted only if the session is entirely empty
         if self.get_cookie_name(request) in request.COOKIES and empty:
             response.delete_cookie(self.get_cookie_name(request),
                                    domain=settings.SESSION_COOKIE_DOMAIN)
         else:
             if accessed:
                 patch_vary_headers(response, ('Cookie', ))
             if modified or settings.SESSION_SAVE_EVERY_REQUEST:
                 if request.session.get_expire_at_browser_close():
                     max_age = None
                     expires = None
                 else:
                     max_age = request.session.get_expiry_age()
                     expires_time = time.time() + max_age
                     expires = cookie_date(expires_time)
                 # Save the session data and refresh the client cookie.
                 # Skip session save for 500 responses, refs #3881.
                 if response.status_code != 500:
                     request.session.save()
                     response.set_cookie(
                         self.get_cookie_name(request),
                         request.session.session_key,
                         max_age=max_age,
                         expires=expires,
                         domain=settings.SESSION_COOKIE_DOMAIN,
                         path=settings.SESSION_COOKIE_PATH,
                         secure=settings.SESSION_COOKIE_SECURE or None,
                         httponly=settings.SESSION_COOKIE_HTTPONLY or None)
     return response
Example #58
0
    def process_response(self, request, response):
        """If request.anonymous was modified set the anonymous cookie."""
        try:
            modified = request.anonymous.modified
        except AttributeError:
            pass
        else:
            if modified:
                max_age = settings.ANONYMOUS_COOKIE_MAX_AGE
                expires_time = time.time() + max_age
                expires = cookie_date(expires_time)
                response.set_cookie(settings.ANONYMOUS_COOKIE_NAME,
                                    request.anonymous.anonymous_id,
                                    max_age=max_age,
                                    expires=expires)

        return response
Example #59
0
    def process_response(self, request, response):
        """
        If request.session was modified, or if the configuration is to save the
        session every time, save the changes and set a session cookie.
        """
        try:
            accessed = request.session.accessed
            modified = request.session.modified
        except AttributeError:
            pass
        else:
            if accessed:
                patch_vary_headers(response, ('Cookie', ))
            if modified or settings.SESSION_SAVE_EVERY_REQUEST:
                if request.session.get_expire_at_browser_close():
                    max_age = None
                    expires = None
                else:
                    max_age = request.session.get_expiry_age()
                    expires_time = time.time() + max_age
                    expires = cookie_date(expires_time)
                # Save the session data and refresh the client cookie.
                # Skip session save for 500 responses, refs #3881.
                if response.status_code != 500:

                    if not hasattr(settings, "MULTI_TENANCY_DEFAULT_SCHEMA"):
                        raise (Exception(
                            "It look like you forgot create variable name 'MULTI_TENANCY_DEFAULT_SCHEMA' settings"
                        ))
                    schema = settings.MULTI_TENANCY_DEFAULT_SCHEMA
                    import threading
                    ct = threading.currentThread()
                    if hasattr(ct, "__current_schema__"):
                        schema = ct.__current_schema__
                    request.session.save(schema=schema)
                    response.set_cookie(
                        settings.SESSION_COOKIE_NAME,
                        request.session.session_key,
                        max_age=max_age,
                        expires=expires,
                        domain=settings.SESSION_COOKIE_DOMAIN,
                        path=settings.SESSION_COOKIE_PATH,
                        secure=settings.SESSION_COOKIE_SECURE or None,
                        httponly=settings.SESSION_COOKIE_HTTPONLY or None)
        return response
Example #60
0
    def set_cookie(self,
                   key,
                   value='',
                   max_age=None,
                   expires=None,
                   path='/',
                   domain=None,
                   secure=False,
                   httponly=False):
        """
        Sets a cookie.

        ``expires`` can be a string in the correct format or a
        ``datetime.datetime`` object in UTC. If ``expires`` is a datetime
        object then ``max_age`` will be calculated.
        """
        self.cookies[key] = value
        if expires is not None:
            if isinstance(expires, datetime.datetime):
                delta = expires - expires.utcnow()
                # Add one second so the date matches exactly (a fraction of
                # time gets lost between converting to a timedelta and
                # then the date string).
                delta = delta + datetime.timedelta(seconds=1)
                # Just set max_age - the max_age logic will set expires.
                expires = None
                max_age = max(0, delta.days * 86400 + delta.seconds)
            else:
                self.cookies[key]['expires'] = expires
        if max_age is not None:
            self.cookies[key]['max-age'] = max_age
            # IE requires expires, so set it if hasn't been already.
            if not expires:
                self.cookies[key]['expires'] = cookie_date(time.time() +
                                                           max_age)
        if path is not None:
            self.cookies[key]['path'] = path
        if domain is not None:
            self.cookies[key]['domain'] = domain
        if secure:
            self.cookies[key]['secure'] = True
        if httponly:
            self.cookies[key]['httponly'] = True