def has_session(self): if self.session is not None: return True cookies = request.get_cookies(self.environ) if cookies.has_key(self.cookie_name): return True return False
def identify(self, environ): cookies = get_cookies(environ) cookie = cookies.get(self.cookie_name) if cookie is None or not cookie.value: return None try: tkt = binascii.a2b_base64(urllib.unquote(cookie.value)) except binascii.Error: return None if self.include_ip: remote_addr = environ['REMOTE_ADDR'] else: remote_addr = '0.0.0.0' validation = validateTicket(self.secret, tkt, remote_addr, timeout=self.timeout, mod_auth_tkt=not self.enhanced_hashing) if validation: ignore, userid, tokens, user_data, timestamp = validation else: return None if cookie is None or not cookie.value: return None identity = {} identity['timestamp'] = timestamp identity['repoze.who.plugins.plone_session_tkt.userid'] = userid identity['tokens'] = tokens identity['userdata'] = user_data return identity
def identify(self, request): """ Return a dictionary with authentication information, or ``None`` if no valid auth_tkt is attached to ``request``""" environ = request.environ cookies = get_cookies(environ) cookie = cookies.get(self.cookie_name) if cookie is None or not cookie.value: return None if self.include_ip: remote_addr = environ['REMOTE_ADDR'] else: remote_addr = '0.0.0.0' try: timestamp, userid, tokens, user_data = self.auth_tkt.parse_ticket( self.secret, cookie.value, remote_addr) except self.auth_tkt.BadTicket: return None now = self.now # service tests if now is None: now = time.time() if self.timeout and ( (timestamp + self.timeout) < now ): # the auth_tkt data has expired return None userid_typename = 'userid_type:' user_data_info = user_data.split('|') for datum in filter(None, user_data_info): if datum.startswith(userid_typename): userid_type = datum[len(userid_typename):] decoder = self.userid_type_decoders.get(userid_type) if decoder: userid = decoder(userid) reissue = self.reissue_time is not None if reissue and not hasattr(request, '_authtkt_reissued'): if ( (now - timestamp) > self.reissue_time ): # work around https://github.com/Pylons/pyramid/issues#issue/108 tokens = filter(None, tokens) headers = self.remember(request, userid, max_age=self.max_age, tokens=tokens) add_global_response_headers(request, headers) request._authtkt_reissued = True environ['REMOTE_USER_TOKENS'] = tokens environ['REMOTE_USER_DATA'] = user_data environ['AUTH_TYPE'] = 'cookie' identity = {} identity['timestamp'] = timestamp identity['userid'] = userid identity['tokens'] = tokens identity['userdata'] = user_data return identity
def __call__(self): self.used = True print '<br>[session]in session call' if self.session is not None: return self.session.data() cookies = request.get_cookies(self.environ) session = None if cookies.has_key(self.cookie_name): self.sid = cookies[self.cookie_name].value try: session = self.session_class(self.sid, create=False, **self.session_class_kw) except KeyError: # Invalid SID pass if session is None: self.created = True self.sid = self.make_sid() session = self.session_class(self.sid, create=True, **self.session_class_kw) session.clean_up() self.session = session return session.data()
def remember(self, environ, identity): log.debug("cookieAuth remember") if self.include_ip: remote_addr = environ.get('REMOTE_ADDR', '0.0.0.0') else: remote_addr = '0.0.0.0' cookies = get_cookies(environ) old_cookie = cookies.get(self.cookie_name) existing = cookies.get(self.cookie_name) old_cookie_value = getattr(existing, 'value', None) max_age = identity.get('max_age', None) timestamp, userid, tokens, userdata = None, '', '', '' if old_cookie_value: try: timestamp,userid,tokens,userdata = auth_tkt.parse_ticket( self.secret, old_cookie_value, remote_addr) except auth_tkt.BadTicket: pass who_userid = identity['midgard.user.guid'] + "|" + identity.get('login') who_tokens = identity.get('tokens', '') who_userdata = identity.get('userdata', '') encoding_data = self.userid_type_encoders.get(type(who_userid)) if encoding_data: encoding, encoder = encoding_data who_userid = encoder(who_userid) who_userdata = 'userid_type:%s' % encoding if not isinstance(tokens, basestring): tokens = ','.join(tokens) if not isinstance(who_tokens, basestring): who_tokens = ','.join(who_tokens) old_data = (userid, tokens, userdata) new_data = (who_userid, who_tokens, who_userdata) if old_data != new_data or (self.reissue_time and ( (timestamp + self.reissue_time) < time.time() )): ticket = auth_tkt.AuthTicket( self.secret, who_userid, remote_addr, tokens=who_tokens, user_data=who_userdata, cookie_name=self.cookie_name, secure=self.secure) new_cookie_value = ticket.cookie_value() cur_domain = environ.get('HTTP_HOST', environ.get('SERVER_NAME')) wild_domain = '.' + cur_domain if old_cookie_value != new_cookie_value: if "auth_remember_allow" in environ and environ["auth_remember_allow"] == False: return None # return a set of Set-Cookie headers return self._get_cookies(environ, new_cookie_value, max_age)
def identify(self, environ): if environ.has_key('rwpc.logout'): return uri = environ.get('REQUEST_URI', construct_url(environ)) query = parse_dict_querystring(environ) cookies = get_cookies(environ) cookie = cookies.get('auth_tkt') if cookie is None or not cookie.value: return None remote_addr = '0.0.0.0' identity = {} try: timestamp, userid, tokens, user_data = auth_tkt.parse_ticket( self.ticket_secret, cookie.value, remote_addr) except auth_tkt.BadTicket as e: return None #userObj = model.Session.query(model.User).filter_by(id=userid).first() #if userObj is None: # return None #identity['login'] = userObj.name identity['login'] = userid return identity
def remember(self, environ, identity): if self.include_ip: remote_addr = environ['REMOTE_ADDR'] else: remote_addr = '0.0.0.0' cookies = get_cookies(environ) old_cookie = cookies.get(self.cookie_name) existing = cookies.get(self.cookie_name) old_cookie_value = getattr(existing, 'value', None) timestamp, userid, tokens, userdata = None, '', (), '' if old_cookie_value: validation = validateTicket(self.secret, old_cookie_value, remote_addr, timeout=self.timeout, mod_auth_tkt=not self.enhanced_hashing) if validation: ignore, userid, tokens, user_data, timestamp = validation else: return tokens = tuple(tokens) who_userid = identity['repoze.who.userid'] who_tokens = tuple(identity.get('tokens', ())) who_userdata = identity.get('userdata', '') who_userid = utf_8_encode(who_userid)[0] old_data = (userid, tokens, userdata) new_data = (who_userid, who_tokens, who_userdata)
def has_session(self): if self.session is not None: return True cookies = request.get_cookies(self.environ) if self.cookie_name in cookies: return True return False
def remember(self, environ, identity): ''' Remember the user. ''' if self.include_ip: remote_addr = environ['REMOTE_ADDR'] else: remote_addr = '0.0.0.0' cookies = get_cookies(environ) #old_cookie = cookies.get(self.cookie_name) existing = cookies.get(self.cookie_name) old_cookie_value = getattr(existing, 'value', None) max_age = identity.get('max_age', None) timestamp, userid, tokens, userdata = None, '', '', '' if old_cookie_value: try: timestamp, userid, tokens, userdata = auth_tkt.parse_ticket( self.secret, old_cookie_value, remote_addr) except auth_tkt.BadTicket: pass who_userid = identity['repoze.who.userid'] who_tokens = identity.get('tokens', '') who_userdata = identity.get('userdata', '') encoding_data = self.userid_type_encoders.get(type(who_userid)) if encoding_data: encoding, encoder = encoding_data who_userid = encoder(who_userid) who_userdata = 'userid_type:%s' % encoding if not isinstance(tokens, basestring): tokens = ','.join(tokens) if not isinstance(who_tokens, basestring): who_tokens = ','.join(who_tokens) old_data = (userid, tokens, userdata) new_data = (who_userid, who_tokens, who_userdata) if old_data != new_data or (self.reissue_time and ( (timestamp + self.reissue_time) < time.time())): ticket = auth_tkt.AuthTicket(self.secret, who_userid, remote_addr, tokens=who_tokens, user_data=who_userdata, cookie_name=self.cookie_name, secure=self.secure) new_cookie_value = ticket.cookie_value() #cur_domain = environ.get('HTTP_HOST', environ.get('SERVER_NAME')) #wild_domain = '.' + cur_domain if old_cookie_value != new_cookie_value: # return a set of Set-Cookie headers return self._get_cookies(environ, new_cookie_value, max_age)
def remember(self, environ, identity): cookie_value = '%s' % identity['repoze.who.userid'] cookie_value = cookie_value.encode('base64').rstrip() cookie = get_cookies(environ).get(self.cookie_name) value = getattr(cookie, 'value', None) if value != cookie_value: # return a Set-Cookie header cookie = '%s=%s; Path=/; Max-Age=3600;' % (self.cookie_name, cookie_value) return [('Set-Cookie', cookie)]
def remember(self, environ, identity): cookie_value = '%(login)s:%(password)s' % identity cookie_value = cookie_value.encode('base64').rstrip() cookies = get_cookies(environ) existing = cookies.get(self.cookie_name) value = getattr(existing, 'value', None) if value != cookie_value: # return a Set-Cookie header set_cookie = '%s=%s; Path=/;' % (self.cookie_name, cookie_value) return [('Set-Cookie', set_cookie)]
def remember(self, environ, identity): cookie_value = '%(login)s:%(password)s' % identity from paste.request import get_cookies cookies = get_cookies(environ) existing = cookies.get(self.cookie_name) value = getattr(existing, 'value', None) if value != cookie_value: set_cookies = '%s=%s; Path=/;' % (self.cookie_name, cookie_value) return [('Set-Cookie', set_cookies)]
def __call__(self, environ, start_response): if self.environ_name in environ: raise AssertionError("AuthCookie already installed!") scanlist = self.environ_class(self, self.scanlist) jar = get_cookies(environ) if self.cookie_name in jar: content = self.signer.auth(jar[self.cookie_name].value) if content: for pair in content.split(";"): (k, v) = pair.split("=") k = decode(k) if k not in scanlist: scanlist.append(k) if k in environ: continue environ[k] = decode(v) if 'REMOTE_USER' == k: environ['AUTH_TYPE'] = 'cookie' environ[self.environ_name] = scanlist if "paste.httpexceptions" in environ: warnings.warn( "Since paste.httpexceptions is hooked in your " "processing chain before paste.auth.cookie, if an " "HTTPRedirection is raised, the cookies this module sets " "will not be included in your response.\n") def response_hook(status, response_headers, exc_info=None): """ Scan the environment for keys specified in the scanlist, pack up their values, signs the content and issues a cookie. """ scanlist = environ.get(self.environ_name) assert scanlist and isinstance(scanlist, self.environ_class) content = [] for k in scanlist: v = environ.get(k) if v is not None: if type(v) is not str: raise ValueError( "The value of the environmental variable %r " "is not a str (only str is allowed; got %r)" % (k, v)) content.append("%s=%s" % (encode(k), encode(v))) if content: content = ";".join(content) content = self.signer.sign(content) if six.PY3: content = content.decode('utf8') cookie = '%s=%s; Path=/;' % (self.cookie_name, content) if 'https' == environ['wsgi.url_scheme']: cookie += ' secure;' response_headers.append(('Set-Cookie', cookie)) return start_response(status, response_headers, exc_info) return self.application(environ, response_hook)
def __call__(self, environ, start_response): if self.environ_name in environ: raise AssertionError("AuthCookie already installed!") scanlist = self.environ_class(self, self.scanlist) jar = get_cookies(environ) if jar.has_key(self.cookie_name): content = self.signer.auth(jar[self.cookie_name].value) if content: for pair in content.split(";"): (k, v) = pair.split("=") k = decode(k) if k not in scanlist: scanlist.append(k) if k in environ: continue environ[k] = decode(v) if "REMOTE_USER" == k: environ["AUTH_TYPE"] = "cookie" environ[self.environ_name] = scanlist if "paste.httpexceptions" in environ: warnings.warn( "Since paste.httpexceptions is hooked in your " "processing chain before paste.auth.cookie, if an " "HTTPRedirection is raised, the cookies this module sets " "will not be included in your response.\n" ) def response_hook(status, response_headers, exc_info=None): """ Scan the environment for keys specified in the scanlist, pack up their values, signs the content and issues a cookie. """ scanlist = environ.get(self.environ_name) assert scanlist and isinstance(scanlist, self.environ_class) content = [] for k in scanlist: v = environ.get(k) if v is not None: if type(v) is not str: raise ValueError( "The value of the environmental variable %r " "is not a str (only str is allowed; got %r)" % (k, v) ) content.append("%s=%s" % (encode(k), encode(v))) if content: content = ";".join(content) content = self.signer.sign(content) cookie = "%s=%s; Path=/;" % (self.cookie_name, content) if "https" == environ["wsgi.url_scheme"]: cookie += " secure;" response_headers.append(("Set-Cookie", cookie)) return start_response(status, response_headers, exc_info) return self.application(environ, response_hook)
def remember(self, environ, identity): cookie_value = '%(login)s:%(password)s' % identity cookie_value = cookie_value.encode('base64').rstrip() cookies = get_cookies(environ) existing = cookies.get(self.cookie_name) value = getattr(existing, 'value', None) if value != cookie_value: # return a Set-Cookie header set_cookie = '%s=%s; Path=%s;' % (self.cookie_name, cookie_value, self.cookie_path) return [('Set-Cookie', set_cookie)]
def identify(self, environ): ''' Identify the user ''' remotes = environ['REMOTE_ADDR'].split(', ') environ['REMOTE_ADDR'] = remotes[0] environ['auth'] = False cookies = get_cookies(environ) cookie = cookies.get(self.cookie_name) if cookie is None or not cookie.value: return None if self.include_ip: remote_addr = environ['REMOTE_ADDR'] else: remote_addr = '0.0.0.0' try: timestamp, userid, tokens, user_data = auth_tkt.parse_ticket( self.secret, cookie.value, remote_addr) except auth_tkt.BadTicket as e: print e print "Bad cookie signature. I think the IP change." #import os #print os.environ['REMOTEHOST'] return None if self.userid_checker and not self.userid_checker(userid): return None if self.timeout and ((timestamp + self.timeout) < time.time()): return None userid_typename = 'userid_type:' user_data_info = user_data.split('|') for datum in filter(None, user_data_info): if datum.startswith(userid_typename): userid_type = datum[len(userid_typename):] decoder = self.userid_type_decoders.get(userid_type) if decoder: userid = decoder(userid) environ['REMOTE_USER_TOKENS'] = tokens environ['REMOTE_USER_DATA'] = user_data environ['AUTH_TYPE'] = 'cookie' identity = {} identity['timestamp'] = timestamp identity['repoze.who.userid'] = userid identity['tokens'] = tokens identity['userdata'] = user_data environ['auth'] = True return identity
def identify(self, environ): ''' Identify the user ''' remotes = environ['REMOTE_ADDR'].split(', ') environ['REMOTE_ADDR'] = remotes[0] environ['auth'] = False cookies = get_cookies(environ) cookie = cookies.get(self.cookie_name) if cookie is None or not cookie.value: return None if self.include_ip: remote_addr = environ['REMOTE_ADDR'] else: remote_addr = '0.0.0.0' try: timestamp, userid, tokens, user_data = auth_tkt.parse_ticket( self.secret, cookie.value, remote_addr) except auth_tkt.BadTicket as e: print e print "Bad cookie signature. I think the IP change." #import os #print os.environ['REMOTEHOST'] return None if self.userid_checker and not self.userid_checker(userid): return None if self.timeout and ( (timestamp + self.timeout) < time.time() ): return None userid_typename = 'userid_type:' user_data_info = user_data.split('|') for datum in filter(None, user_data_info): if datum.startswith(userid_typename): userid_type = datum[len(userid_typename):] decoder = self.userid_type_decoders.get(userid_type) if decoder: userid = decoder(userid) environ['REMOTE_USER_TOKENS'] = tokens environ['REMOTE_USER_DATA'] = user_data environ['AUTH_TYPE'] = 'cookie' identity = {} identity['timestamp'] = timestamp identity['repoze.who.userid'] = userid identity['tokens'] = tokens identity['userdata'] = user_data environ['auth'] = True return identity
def __call__(self, environ, start_response): """ If the remote browser has a cookie that claims to contain a browser id value, and that value hasn't been tampered with, set the browser id portion of the cookie value as 'repoze.browserid' in the environ and call the downstream application. Otherwise, create one and set that as 'repoze.browserid' in the environ, then call the downstream application. On egress, set a Set-Cookie header with the value+hmac so we can retrieve it next time around. We use the secret key and the values in self.vary to compose the 'tamper key' when creating a browser id, which is used as the hmac key. This allows a configurer to vary the tamper key on, e.g. 'REMOTE_ADDR' if he believes that the same browser id should always be sent from the same IP address, or 'HTTP_USER_AGENT' if he believes it should always come from the same user agent, or some arbitrary combination thereof made out of environ keys. """ cookies = get_cookies(environ) cookie = cookies.get(self.cookie_name) if cookie is not None: # this browser returned a cookie value that claims to be # a browser id browser_id = self.from_cookieval(environ, cookie.value) if browser_id is not None: # cookie hasn't been tampered with environ['repoze.browserid'] = browser_id return self.app(environ, start_response) # no browser id cookie or cookie value was tampered with now = self.time() browser_id = self.new(now) environ['repoze.browserid'] = browser_id wrapper = StartResponseWrapper(start_response) app_iter = self.app(environ, wrapper.wrap_start_response) cookie_value = self.to_cookieval(environ, browser_id) set_cookie = '%s=%s; ' % (self.cookie_name, cookie_value) if self.cookie_path: set_cookie += 'Path=%s; ' % self.cookie_path if self.cookie_domain: set_cookie += 'Domain=%s; ' % self.cookie_domain if self.cookie_lifetime: expires = time.gmtime(now + self.cookie_lifetime) expires = time.strftime('%a %d-%b-%Y %H:%M:%S GMT', expires) set_cookie += 'Expires=%s; ' % expires if self.cookie_secure: set_cookie += 'Secure;' wrapper.finish_response([('Set-Cookie', set_cookie)]) return app_iter
def remember(self, environ, identity): if self.include_ip: remote_addr = environ['REMOTE_ADDR'] else: remote_addr = '0.0.0.0' cookies = get_cookies(environ) old_cookie = cookies.get(self.cookie_name) existing = cookies.get(self.cookie_name) old_cookie_value = getattr(existing, 'value', None) max_age = identity.get('max_age', None) timestamp, userid, tokens, userdata = None, '', (), '' if old_cookie_value: try: timestamp,userid,tokens,userdata = auth_tkt.parse_ticket( self.secret, old_cookie_value, remote_addr) except auth_tkt.BadTicket: pass tokens = tuple(tokens) who_userid = identity['repoze.who.userid'] who_tokens = tuple(identity.get('tokens', ())) who_userdata = identity.get('userdata', '') encoding_data = self.userid_type_encoders.get(type(who_userid)) if encoding_data: encoding, encoder = encoding_data who_userid = encoder(who_userid) who_userdata = 'userid_type:%s' % encoding old_data = (userid, tokens, userdata) new_data = (who_userid, who_tokens, who_userdata) if old_data != new_data or (self.reissue_time and ( (timestamp + self.reissue_time) < time.time() )): ticket = auth_tkt.AuthTicket( self.secret, who_userid, remote_addr, tokens=who_tokens, user_data=who_userdata, cookie_name=self.cookie_name, secure=self.secure) new_cookie_value = ticket.cookie_value() cur_domain = environ.get('HTTP_HOST', environ.get('SERVER_NAME')) wild_domain = cur_domain[cur_domain.find('.'):] #wild_domain = '.' + cur_domain if old_cookie_value != new_cookie_value: # return a set of Set-Cookie headers return self._get_cookies(environ, new_cookie_value, max_age)
def identify(self, request): environ = request.environ cookies = get_cookies(environ) cookie = cookies.get(self.cookie_name) if cookie is None or not cookie.value: return None if self.include_ip: remote_addr = environ["REMOTE_ADDR"] else: remote_addr = "0.0.0.0" try: timestamp, userid, tokens, user_data = self.auth_tkt.parse_ticket(self.secret, cookie.value, remote_addr) except self.auth_tkt.BadTicket: return None now = self.now # service tests if now is None: now = time.time() if self.timeout and ((timestamp + self.timeout) < now): return None userid_typename = "userid_type:" user_data_info = user_data.split("|") for datum in filter(None, user_data_info): if datum.startswith(userid_typename): userid_type = datum[len(userid_typename) :] decoder = self.userid_type_decoders.get(userid_type) if decoder: userid = decoder(userid) reissue = self.reissue_time is not None if not hasattr(request, "_authtkt_reissued"): if reissue and ((now - timestamp) > self.reissue_time): headers = self.remember(request, userid, max_age=self.max_age) add_global_response_headers(request, headers) request._authtkt_reissued = True environ["REMOTE_USER_TOKENS"] = tokens environ["REMOTE_USER_DATA"] = user_data environ["AUTH_TYPE"] = "cookie" identity = {} identity["timestamp"] = timestamp identity["userid"] = userid identity["tokens"] = tokens identity["userdata"] = user_data return identity
def _get_token_value(self, environ): """Gets the token value stored in the cookie""" from paste.request import get_cookies cookies = get_cookies(environ) cookie = cookies.get(self._cookie_name) if cookie is None: return None token = cookie.value return token
def cookie_okay(self, req): jar = get_cookies(req.environ) if COOKIE_NAME not in jar: return False try: data = secureUnpack(jar[COOKIE_NAME].value, COOKIE_SECRET) except UnpackException: # cookie is currupted return False for k, v in data.iteritems(): req.environ[k] = v log.debug(STORED_KEYS[0] + " is " + str(req.environ[STORED_KEYS[0]])) return STORED_KEYS[0] in req.environ and bool(req.environ[STORED_KEYS[0]])
def identify(self, request): environ = request.environ cookies = get_cookies(environ) cookie = cookies.get(self.cookie_name) if cookie is None or not cookie.value: return None if self.include_ip: remote_addr = environ['REMOTE_ADDR'] else: remote_addr = '0.0.0.0' try: timestamp, userid, tokens, user_data = self.auth_tkt.parse_ticket( self.secret, cookie.value, remote_addr) except self.auth_tkt.BadTicket: return None now = time.time() if self.timeout and ( (timestamp + self.timeout) < now ): return None userid_typename = 'userid_type:' user_data_info = user_data.split('|') for datum in filter(None, user_data_info): if datum.startswith(userid_typename): userid_type = datum[len(userid_typename):] decoder = self.userid_type_decoders.get(userid_type) if decoder: userid = decoder(userid) reissue = self.reissue_time is not None if not hasattr(request, '_authtkt_reissued'): if reissue and ( (now - timestamp) > self.reissue_time): headers = self.remember(request, userid, max_age=self.max_age) add_global_response_headers(request, headers) request._authtkt_reissued = True environ['REMOTE_USER_TOKENS'] = tokens environ['REMOTE_USER_DATA'] = user_data environ['AUTH_TYPE'] = 'cookie' identity = {} identity['timestamp'] = timestamp identity['userid'] = userid identity['tokens'] = tokens identity['userdata'] = user_data return identity
def challenge(self, environ, status, app_headers, forget_headers): ''' The challenger. ''' cookies = get_cookies(environ) cookie = cookies.get(self.cookie_name) # request = Request(environ) if cookie is None or not cookie.value: pass # redirect to login_form res = Response() res.status = 302 res.location = '/biorepo/login_needed' return res
def __call__(self, environ, start_response): cookies = request.get_cookies(environ) if self.cookie_name in cookies: cookie_value = cookies[self.cookie_name].value else: cookie_value = "" if cookie_value: if self.include_ip: remote_addr = environ["REMOTE_ADDR"] else: # mod_auth_tkt uses this dummy value when IP is not # checked: remote_addr = "0.0.0.0" # @@: This should handle bad signatures better: # Also, timeouts should cause cookie refresh try: timestamp, userid, tokens, user_data = parse_ticket( self.secret, cookie_value, remote_addr, self.digest_algo ) tokens = ",".join(tokens) environ["REMOTE_USER"] = userid if environ.get("REMOTE_USER_TOKENS"): # We want to add tokens/roles to what's there: tokens = environ["REMOTE_USER_TOKENS"] + "," + tokens environ["REMOTE_USER_TOKENS"] = tokens environ["REMOTE_USER_DATA"] = user_data environ["AUTH_TYPE"] = "cookie" except BadTicket: # bad credentials, just ignore without logging the user # in or anything pass set_cookies = [] def set_user(userid, tokens="", user_data=""): set_cookies.extend(self.set_user_cookie(environ, userid, tokens, user_data)) def logout_user(): set_cookies.extend(self.logout_user_cookie(environ)) environ["paste.auth_tkt.set_user"] = set_user environ["paste.auth_tkt.logout_user"] = logout_user if self.logout_path and environ.get("PATH_INFO") == self.logout_path: logout_user() def cookie_setting_start_response(status, headers, exc_info=None): headers.extend(set_cookies) return start_response(status, headers, exc_info) return self.app(environ, cookie_setting_start_response)
def __call__(self, environ, start_response): cookies = request.get_cookies(environ) if self.cookie_name in cookies: cookie_value = cookies[self.cookie_name].value else: cookie_value = '' if cookie_value: if self.include_ip: remote_addr = environ['REMOTE_ADDR'] else: # mod_auth_tkt uses this dummy value when IP is not # checked: remote_addr = '0.0.0.0' # @@: This should handle bad signatures better: # Also, timeouts should cause cookie refresh try: timestamp, userid, tokens, user_data = parse_ticket( self.secret, cookie_value, remote_addr, self.digest_algo) tokens = ','.join(tokens) environ['REMOTE_USER'] = userid if environ.get('REMOTE_USER_TOKENS'): # We want to add tokens/roles to what's there: tokens = environ['REMOTE_USER_TOKENS'] + ',' + tokens environ['REMOTE_USER_TOKENS'] = tokens environ['REMOTE_USER_DATA'] = user_data environ['AUTH_TYPE'] = 'cookie' except BadTicket: # bad credentials, just ignore without logging the user # in or anything pass set_cookies = [] def set_user(userid, tokens='', user_data=''): set_cookies.extend( self.set_user_cookie(environ, userid, tokens, user_data)) def logout_user(): set_cookies.extend(self.logout_user_cookie(environ)) environ['paste.auth_tkt.set_user'] = set_user environ['paste.auth_tkt.logout_user'] = logout_user if self.logout_path and environ.get('PATH_INFO') == self.logout_path: logout_user() def cookie_setting_start_response(status, headers, exc_info=None): headers.extend(set_cookies) return start_response(status, headers, exc_info) return self.app(environ, cookie_setting_start_response)
def identify(self, environ): cookies = get_cookies(environ) cookie = cookies.get('authtkt') username = environ.get('HTTP_REMOTE_USER', '') if username == '' or cookie is not None: return None create_new_user(username, self.config) credentials = { 'login': username, 'max_age': session_validity } referer = environ.get('PATH_INFO') environ['repoze.who.application'] = HTTPFound(location=referer) return credentials
def identify(self, environ): if 'REMOTE_USER' in environ: remote_user = unicode(environ['REMOTE_USER']) # FIXME: use repoze translations for user_name # also in tg.config['sa_auth']['translations']['user_name'] if not self.dbsession.query(self.user_class).filter_by(uid=remote_user).first(): environ['repoze.who.logger'].warn('adding identity for new user "%s"' % remote_user) self.user_class(uid=remote_user, password=remote_user) transaction.commit() return {'repoze.who.userid': remote_user} else: cookie = get_cookies(environ).get(self.cookie_name) if cookie: return {'repoze.who.userid': unicode(cookie.value.decode('base64'))} return None
def identify(self, environ): from paste.request import get_cookies cookies = get_cookies(environ) cookie = cookies.get(self.cookie_name) if cookie is None: return None auth = cookie.value try: login, password = auth.split(':', 1) hashed_passwd = hashlib.md5(password) return {'login':login, 'password':password} except ValueError: # not enough values to unpack return None
def identify(self, environ): cookies = get_cookies(environ) cookie = cookies.get(self.cookie_name) if cookie is None: return None try: auth = cookie.value.decode('base64') except binascii.Error: # can't decode return None try: login, password = auth.split(':', 1) return {'login': login, 'password': password} except ValueError: # not enough values to unpack return None
def identify(self, environ): cookies = get_cookies(environ) cookie = cookies.get(self.cookie_name) if cookie is None: return None try: auth = cookie.value.decode('base64') except binascii.Error: # can't decode return None try: login, password = auth.split(':', 1) return {'login':login, 'password':password} except ValueError: # not enough values to unpack return None
def logout(environ, start_response): """ログアウト処理 """ class UnknownApp(JvnApplication): def __init__(self): super(self.__class__, self).__init__() cookie = get_cookies(environ) if JVN_SID in cookie: sid = cookie.get(JVN_SID) session_file = os.path.join(os.path.abspath(os.path.dirname(__file__)) ,'tmp' ,sid.value) if os.access(session_file,os.R_OK): os.remove(session_file) res = webob.Response() set_response(res, 'jvn_login.j2', UnknownApp()) return res(environ, start_response)
def identify(self, environ): log.debug("cookieAuth identify") cookies = get_cookies(environ) cookie = cookies.get(self.cookie_name) if cookie is None or not cookie.value: return None if self.include_ip: remote_addr = environ['REMOTE_ADDR'] else: remote_addr = '0.0.0.0' try: timestamp, userid, tokens, user_data = auth_tkt.parse_ticket( self.secret, cookie.value, remote_addr) except auth_tkt.BadTicket: return None if self.timeout and ( (timestamp + self.timeout) < time.time() ): return None userid_typename = 'userid_type:' user_data_info = user_data.split('|') for datum in filter(None, user_data_info): if datum.startswith(userid_typename): userid_type = datum[len(userid_typename):] decoder = self.userid_type_decoders.get(userid_type) if decoder: userid = decoder(userid) environ['REMOTE_USER_TOKENS'] = tokens environ['REMOTE_USER_DATA'] = user_data environ['AUTH_TYPE'] = 'cookie' user_guid, login = userid.split("|") identity = {} identity['timestamp'] = timestamp identity['midgard.user.guid'] = user_guid identity['login'] = login identity['tokens'] = tokens identity['userdata'] = user_data return identity
def __call__(self, environ, start_response): cookies = request.get_cookies(environ) if cookies.has_key(self.cookie_name): cookie_value = cookies[self.cookie_name].value else: cookie_value = '' if cookie_value: if self.include_ip: remote_addr = environ['REMOTE_ADDR'] else: # mod_auth_tkt uses this dummy value when IP is not # checked: remote_addr = '0.0.0.0' # @@: This should handle bad signatures better: # Also, timeouts should cause cookie refresh try: timestamp, userid, tokens, user_data = parse_ticket( self.secret, cookie_value, remote_addr) tokens = ','.join(tokens) environ['REMOTE_USER'] = userid if environ.get('REMOTE_USER_TOKENS'): # We want to add tokens/roles to what's there: tokens = environ['REMOTE_USER_TOKENS'] + ',' + tokens environ['REMOTE_USER_TOKENS'] = tokens environ['REMOTE_USER_DATA'] = user_data environ['AUTH_TYPE'] = 'cookie' except BadTicket: # bad credentials, just ignore without logging the user # in or anything pass set_cookies = [] def set_user(userid, tokens='', user_data=''): set_cookies.extend(self.set_user_cookie( environ, userid, tokens, user_data)) def logout_user(): set_cookies.extend(self.logout_user_cookie(environ)) environ['paste.auth_tkt.set_user'] = set_user environ['paste.auth_tkt.logout_user'] = logout_user if self.logout_path and environ.get('PATH_INFO') == self.logout_path: logout_user() def cookie_setting_start_response(status, headers, exc_info=None): headers.extend(set_cookies) return start_response(status, headers, exc_info) return self.app(environ, cookie_setting_start_response)
def challenge(self, environ, status, app_headers, forget_headers): ''' The challenger. ''' cookies = get_cookies(environ) cookie = cookies.get(self.cookie_name) # request = Request(environ) if cookie is None or not cookie.value: pass # redirect to login_form res = Response() res.status = 302 addon = None if 'SCRIPT_NAME' in environ: addon = environ['SCRIPT_NAME'] if addon is not None: res.location = addon + '/login_needed' else: res.location = 'login_needed' return res
def challenge(self, environ, status, app_headers, forget_headers): ''' The challenger. ''' cookies = get_cookies(environ) cookie = cookies.get(self.cookie_name) # request = Request(environ) if cookie is None or not cookie.value: # redirect to login_form res = Response() res.status = 302 res.location = '/login_needed' addon = None if 'SCRIPT_NAME' in environ: addon = environ['SCRIPT_NAME'] if addon is not None: res.location = addon + '/login_needed' else: res.location = 'login_needed' return res
def identify(self, environ): cookies = get_cookies(environ) cookie = cookies.get(self.cookie_name) if cookie is None or not cookie.value: return None if self.include_ip: remote_addr = environ['REMOTE_ADDR'] else: remote_addr = '0.0.0.0' try: timestamp, userid, tokens, user_data = auth_tkt.parse_ticket( self.secret, cookie.value, remote_addr) except auth_tkt.BadTicket: return None if self.timeout and ( (timestamp + self.timeout) < time.time() ): return None userid_typename = 'userid_type:' user_data_info = user_data.split('|') for datum in filter(None, user_data_info): if datum.startswith(userid_typename): userid_type = datum[len(userid_typename):] decoder = self.userid_type_decoders.get(userid_type) if decoder: userid = decoder(userid) environ['REMOTE_USER_TOKENS'] = tokens environ['REMOTE_USER_DATA'] = user_data environ['AUTH_TYPE'] = 'cookie' identity = {} identity['timestamp'] = timestamp identity['repoze.who.plugins.auth_tkt.userid'] = userid identity['tokens'] = tokens identity['userdata'] = user_data return identity
def __call__(self): self.used = True if self.session is not None: return self.session.data() cookies = request.get_cookies(self.environ) session = None if self.cookie_name in cookies: self.sid = cookies[self.cookie_name].value try: session = self.session_class(self.sid, create=False, **self.session_class_kw) except KeyError: # Invalid SID pass if session is None: self.created = True self.sid = self.make_sid() session = self.session_class(self.sid, create=True, **self.session_class_kw) session.clean_up() self.session = session return session.data()
def cookies( self ): return get_cookies( self.environ )
def __call__(self, environ, start_response): # check whether the the request should be logged, i.e. starts with # 'play' and is longer than a mere request for the playable-versions # page request_path = environ.get('PATH_INFO', '') path_parts = request_path.strip('/').split('/', 2) if len(path_parts) == 3 and path_parts[0] == 'play': slug = path_parts[1] if self.gamelist.get_by_slug(slug): file_name = path_parts[2] # find user id on cookies or create a new one cookies = request.get_cookies(environ) if cookies.has_key(self.cookie_session_name): user_id = cookies[self.cookie_session_name].value is_new_user = False else: self.user_id_counter += 1 user_id = '%x' % self.user_id_counter is_new_user = True slug_sessions = MetricsSession.get_sessions(slug) # make sure there is a session when an html file is requested # ignore otherwise session = slug_sessions.get(user_id, None) if file_name.endswith(('.html', '.htm')) or \ (file_name.endswith(('.tzjs', '.canvas.js', '.swf')) and 'HTTP_REFERER' in environ and \ not environ['HTTP_REFERER'].endswith(('.html', '.htm'))): if session: session.finish() session = None try: session = MetricsSession(slug) except IOError: return self.app(environ, start_response) slug_sessions[user_id] = session elif not session: return self.app(environ, start_response) # define function to capture status and headers from response response_headers = [] def metrics_start_response(status, headers, exc_info=None): if is_new_user: headers.append( ('Set-Cookie', '%s=%s; Path=/play/%s/' % (self.cookie_session_name, user_id, slug))) response_headers.append(status) response_headers.append(headers) return start_response(status, headers, exc_info) # pass through request and get response response = self.app(environ, metrics_start_response) status = response_headers[0] file_size = 0 if status.startswith('404'): file_type = 'n/a' else: file_type = None if status.startswith('200'): for k, v in response_headers[1]: if k == 'Content-Length': file_size = v if file_type: break elif k == 'Content-Type': file_type = v if file_size: break else: for k, v in response_headers[1]: if k == 'Content-Type': file_type = v break if not file_type: file_type = mimetypes.guess_type(file_name)[0] if not file_type: file_type = 'n/a' else: file_type = file_type.split(';')[0].split(',')[0] session.append(file_name, file_size, file_type, status) # send the response back up the WSGI layers return response return self.app(environ, start_response)
def __call__(self, environ, start_response): # check whether the the request should be logged, i.e. starts with # 'play' and is longer than a mere request for the playable-versions # page request_path = environ.get('PATH_INFO', '') path_parts = request_path.strip('/').split('/', 2) if len(path_parts) == 3 and path_parts[0] == 'play': slug = path_parts[1] if self.gamelist.get_by_slug(slug): file_name = path_parts[2] # find user id on cookies or create a new one cookies = request.get_cookies(environ) if cookies.has_key(self.cookie_session_name): user_id = cookies[self.cookie_session_name].value is_new_user = False else: self.user_id_counter += 1 user_id = '%x' % self.user_id_counter is_new_user = True slug_sessions = MetricsSession.get_sessions(slug) # make sure there is a session when an html file is requested # ignore otherwise session = slug_sessions.get(user_id, None) if file_name.endswith(('.html', '.htm')) or \ (file_name.endswith(('.tzjs', '.canvas.js', '.swf')) and 'HTTP_REFERER' in environ and \ not environ['HTTP_REFERER'].endswith(('.html', '.htm'))): if session: session.finish() session = None try: session = MetricsSession(slug) except IOError: return self.app(environ, start_response) slug_sessions[user_id] = session elif not session: return self.app(environ, start_response) # define function to capture status and headers from response response_headers = [] def metrics_start_response(status, headers, exc_info=None): if is_new_user: headers.append(('Set-Cookie', '%s=%s; Path=/play/%s/' % (self.cookie_session_name, user_id, slug))) response_headers.append(status) response_headers.append(headers) return start_response(status, headers, exc_info) # pass through request and get response response = self.app(environ, metrics_start_response) status = response_headers[0] file_size = 0 if status.startswith('404'): file_type = 'n/a' else: file_type = None if status.startswith('200'): for k, v in response_headers[1]: if k == 'Content-Length': file_size = v if file_type: break elif k == 'Content-Type': file_type = v if file_size: break else: for k, v in response_headers[1]: if k == 'Content-Type': file_type = v break if not file_type: file_type = mimetypes.guess_type(file_name)[0] if not file_type: file_type = 'n/a' else: file_type = file_type.split(';')[0].split(',')[0] session.append(file_name, file_size, file_type, status) # send the response back up the WSGI layers return response return self.app(environ, start_response)
def cookies(self): return get_cookies(self.environ)