Пример #1
0
    def setCookie(self,
                  name,
                  value,
                  path='/',
                  expires='ONCLOSE',
                  secure=False):
        """Set a cookie.

        You can also set the path (which defaults to /).

        You can also set when it expires. It can expire:

        - 'NOW': this is the same as trying to delete it, but it
          doesn't really seem to work in IE
        - 'ONCLOSE': the default behavior for cookies (expires when
          the browser closes)
        - 'NEVER': some time in the far, far future.
        - integer: a timestamp value
        - tuple or struct_time: a tuple, as created by the time module
        - datetime: a datetime.datetime object for the time (if without
          time zone, assumed to be *local*, not GMT time)
        - timedelta: a duration counted from the present, e.g.,
          datetime.timedelta(days=14) (2 weeks in the future)
        - '+...': a time in the future, '...' should be something like
          1w (1 week), 3h46m (3:45), etc.  You can use y (year),
          b (month), w (week), d (day), h (hour), m (minute),
          s (second). This is done by the MiscUtils.DateInterval.
        """
        cookie = Cookie(name, value)
        t = expires
        if isinstance(t, str):
            if t == 'ONCLOSE':
                t = None
            elif t == 'NOW':
                cookie.delete()
                return
            elif t == 'NEVER':
                t = gmtime()
                t = (t[0] + 10, ) + t[1:]
            elif t.startswith('+'):
                t = time() + timeDecode(t[1:])
        if t:
            if isinstance(t, (int, float)):
                t = gmtime(t)
            if isinstance(t, (tuple, struct_time)):
                t = strftime("%a, %d-%b-%Y %H:%M:%S GMT", t)
            if isinstance(t, timedelta):
                t = datetime.now() + t
            if isinstance(t, datetime):
                d = t.utcoffset()
                if d is None:
                    d = localTimeDelta()
                t -= d
                t = t.strftime("%a, %d-%b-%Y %H:%M:%S GMT")
            cookie.setExpires(t)
        if path:
            cookie.setPath(path)
        if secure:
            cookie.setSecure(secure)
        self.addCookie(cookie)
Пример #2
0
	def setCookie(self, name, value, path='/', expires='ONCLOSE',
			secure=False):
		"""Set a cookie.

		You can also set the path (which defaults to /).
		You can also set when it expires. It can expire:
		  'NOW': this is the same as trying to delete it, but it
		    doesn't really seem to work in IE
		  'ONCLOSE': the default behavior for cookies (expires when
		             the browser closes)
		  'NEVER': some time in the far, far future.
		  integer: a timestamp value
		  tuple: a tuple, as created by the time module
		  DateTime: an mxDateTime object for the time (assumed to
		    be *local*, not GMT time)
		  DateTimeDelta: a interval from the present, e.g.,
		    DateTime.DateTimeDelta(month=1) (1 month in the future)
		    '+...': a time in the future, '...' should be something like
		    1w (1 week), 3h46m (3:45), etc.  You can use y (year),
		    b (month), w (week), d (day), h (hour), m (minute),
		    s (second). This is done by the MiscUtils.DateInterval.

		"""
		cookie = Cookie(name, value)
		if expires == 'ONCLOSE' or not expires:
			pass # this is already default behavior
		elif expires == 'NOW':
			cookie.delete()
			return
		elif expires == 'NEVER':
			t = time.gmtime(time.time())
			if expires == 'NEVER':
				t = (t[0] + 10,) + t[1:]
			t = time.strftime("%a, %d-%b-%Y %H:%M:%S GMT", t)
			cookie.setExpires(t)
		else:
			t = expires
			if type(t) is StringType and t and t[0] == '+':
				interval = timeDecode(t[1:])
				t = time.time() + interval
			if type(t) in (IntType, LongType, FloatType):
				t = time.gmtime(t)
			if type(t) in (TupleType, TimeTupleType):
				t = time.strftime("%a, %d-%b-%Y %H:%M:%S GMT", t)
			if DateTime and \
					(type(t) is DateTime.DateTimeDeltaType
				or isinstance(t, DateTime.RelativeDateTime)):
				t = DateTime.now() + t
			if DateTime and type(t) is DateTime.DateTimeType:
				t = (t - t.gmtoffset()).strftime("%a, %d-%b-%Y %H:%M:%S GMT")
			cookie.setExpires(t)
		if path:
			cookie.setPath(path)
		if secure:
			cookie.setSecure(secure)
		self.addCookie(cookie)
Пример #3
0
    def recordSession(self):
        """Record session ID.

        Invoked by commit() to record the session ID in the response
        (if a session exists). This implementation sets a cookie for
        that purpose. For people who don't like sweets, a future version
        could check a setting and instead of using cookies, could parse
        the HTML and update all the relevant URLs to include the session ID
        (which implies a big performance hit). Or we could require site
        developers to always pass their URLs through a function which adds
        the session ID (which implies pain). Personally, I'd rather just
        use cookies. You can experiment with different techniques by
        subclassing Session and overriding this method. Just make sure
        Application knows which "session" class to use.

        It should be also considered to automatically add the server port
        to the cookie name in order to distinguish application instances
        running on different ports on the same server, or to use the port
        cookie-attribute introduced with RFC 2965 for that purpose.
        """
        trans = self._transaction
        app = trans.application()
        if not app.setting('UseCookieSessions'):
            return
        session = trans._session
        if not session:
            if debug:
                print('>> recordSession: Did not set SID.')
            return
        request = trans.request()
        sessionName = app.sessionName(trans)
        identifier = session.identifier()
        if session.isExpired() or session.timeout() == 0:
            self.delCookie(
                sessionName, app.sessionCookiePath(trans),
                request.isSecure() and app.setting('SecureSessionCookie'))
            if debug:
                print('>> recordSession: Removing SID', identifier)
            return
        if request.hasCookie(sessionName):
            if request.cookie(sessionName) == identifier:
                if debug:
                    print('>> recordSession: Using SID', identifier)
                return
        cookie = Cookie(app.sessionName(trans), identifier)
        cookie.setPath(app.sessionCookiePath(trans))
        if request.isSecure():
            cookie.setSecure(app.setting('SecureSessionCookie'))
        if app.setting('HttpOnlySessionCookie'):
            cookie.setHttpOnly()
        sameSite = app.setting('SameSiteSessionCookie')
        if sameSite:
            cookie.setSameSite(sameSite)
        self.addCookie(cookie)
        if debug:
            print('>> recordSession: Setting SID', identifier)
Пример #4
0
    def setCookie(self, name, value, path='/', expires='ONCLOSE',
            secure=False):
        """Set a cookie.

        You can also set the path (which defaults to /).
        You can also set when it expires. It can expire:
          'NOW': this is the same as trying to delete it, but it
            doesn't really seem to work in IE
          'ONCLOSE': the default behavior for cookies (expires when
            the browser closes)
          'NEVER': some time in the far, far future.
          integer: a timestamp value
          tuple or struct_time: a tuple, as created by the time module
          datetime: a datetime.datetime object for the time (if without
            time zone, assumed to be *local*, not GMT time)
          timedelta: a duration counted from the present, e.g.,
            datetime.timedelta(days=14) (2 weeks in the future)
          '+...': a time in the future, '...' should be something like
            1w (1 week), 3h46m (3:45), etc.  You can use y (year),
            b (month), w (week), d (day), h (hour), m (minute),
            s (second). This is done by the MiscUtils.DateInterval.

        """
        cookie = Cookie(name, value)
        t = expires
        if isinstance(t, basestring):
            if t == 'ONCLOSE':
                t = None
            elif t == 'NOW':
                cookie.delete()
                return
            elif t == 'NEVER':
                t = gmtime()
                t = (t[0] + 10,) + t[1:]
            elif t.startswith('+'):
                t = time() + timeDecode(t[1:])
        if t:
            if isinstance(t, (int, long, float)):
                t = gmtime(t)
            if isinstance(t, (tuple, struct_time)):
                t = strftime("%a, %d-%b-%Y %H:%M:%S GMT", t)
            if isinstance(t, timedelta):
                t = datetime.now() + t
            if isinstance(t, datetime):
                d = t.utcoffset()
                if d is None:
                    d = localTimeDelta()
                t -= d
                t = t.strftime("%a, %d-%b-%Y %H:%M:%S GMT")
            cookie.setExpires(t)
        if path:
            cookie.setPath(path)
        if secure:
            cookie.setSecure(secure)
        self.addCookie(cookie)
Пример #5
0
    def recordSession(self):
        """Record session ID.

        Invoked by commit() to record the session ID in the response
        (if a session exists). This implementation sets a cookie for
        that purpose. For people who don't like sweets, a future version
        could check a setting and instead of using cookies, could parse
        the HTML and update all the relevant URLs to include the session ID
        (which implies a big performance hit). Or we could require site
        developers to always pass their URLs through a function which adds
        the session ID (which implies pain). Personally, I'd rather just
        use cookies. You can experiment with different techniques by
        subclassing Session and overriding this method. Just make sure
        Application knows which "session" class to use.

        It should be also considered to automatically add the server port
        to the cookie name in order to distinguish application instances
        running on different ports on the same server, or to use the port
        cookie-attribute introduced with RFC 2965 for that purpose.

        """
        trans = self._transaction
        app = trans.application()
        if not app.setting('UseCookieSessions'):
            return
        session = trans._session
        if not session:
            if debug:
                print '>> recordSession: Did not set SID.'
            return
        request = trans.request()
        sessionName = app.sessionName(trans)
        identifier = session.identifier()
        if session.isExpired() or session.timeout() == 0:
            self.delCookie(sessionName, app.sessionCookiePath(trans),
                request.isSecure() and app.setting('SecureSessionCookie'))
            if debug:
                print '>> recordSession: Removing SID', identifier
            return
        # Temporary fix for bug 65471
        #if request.hasCookie(sessionName):
        if False:
            if request.cookie(sessionName) == identifier:
                if debug:
                    print '>> recordSession: Using SID', identifier
                return
        cookie = Cookie(app.sessionName(trans), identifier)
        cookie.setPath(app.sessionCookiePath(trans))
        if trans.request().isSecure():
            cookie.setSecure(app.setting('SecureSessionCookie'))
        self.addCookie(cookie)
        if debug:
            print '>> recordSession: Setting SID', identifier
Пример #6
0
    def delCookie(self, name, path='/', secure=False):
        """Delete a cookie at the browser.

        To do so, one has to create and send to the browser a cookie with
        parameters that will cause the browser to delete it.
        """
        if name in self._cookies:
            self._cookies[name].delete()
        else:
            cookie = Cookie(name, None)
            if path:
                cookie.setPath(path)
            if secure:
                cookie.setSecure(secure)
            cookie.delete()
            self.addCookie(cookie)
Пример #7
0
    def delCookie(self, name, path='/', secure=False):
        """Delete a cookie at the browser.

        To do so, one has to create and send to the browser a cookie with
        parameters that will cause the browser to delete it.
        """
        if name in self._cookies:
            self._cookies[name].delete()
        else:
            cookie = Cookie(name, None)
            if path:
                cookie.setPath(path)
            if secure:
                cookie.setSecure(secure)
            cookie.delete()
            self.addCookie(cookie)