def _get_user(self): '''Get user instance for this identity.''' visit = self.visit_link if not visit: self._user = None else: if (not '_csrf_token' in cherrypy.request.params or cherrypy.request.params['_csrf_token'] != hash_constructor(self.visit_key).hexdigest()): log.info("Bad _csrf_token") if '_csrf_token' in cherrypy.request.params: log.info("visit: %s token: %s" % (self.visit_key, cherrypy.request.params['_csrf_token'])) else: log.info('No _csrf_token present') cherrypy.request.fas_identity_failure_reason = 'bad_csrf' self._user = None try: return self._user except AttributeError: # User hasn't already been set # Attempt to load the user. After this code executes, there # *will* be a _user attribute, even if the value is None. self._user = self.__retrieve_user(visit) return self._user
def _get_user(self): '''Get user instance for this identity.''' visit = self.visit_key if not visit: # No visit, no user self._user = None else: if not (self.username and self.password): # Unless we were given the user_name and password to login on # this request, a CSRF token is required if (not '_csrf_token' in cherrypy.request.params or cherrypy.request.params['_csrf_token'] != hash_constructor(self.visit_key).hexdigest()): self.log.info("Bad _csrf_token") if '_csrf_token' in cherrypy.request.params: self.log.info("visit: %s token: %s" % (self.visit_key, cherrypy.request.params['_csrf_token'])) else: self.log.info('No _csrf_token present') cherrypy.request.fas_identity_failure_reason = 'bad_csrf' self._user = None # pylint: disable-msg=W0704 try: return self._user except AttributeError: # User hasn't already been set # Attempt to load the user. After this code executes, there # *will* be a _user attribute, even if the value is None. self._user = self.__retrieve_user() self._groups = frozenset( [g['name'] for g in self._user.approved_memberships] ) # pylint: enable-msg=W0704 return self._user
def _get_user(self): """Get user instance for this identity.""" try: return self._user except AttributeError: # User hasn't already been set pass # Attempt to load the user. After this code executes, there *will* be # a _user attribute, even if the value is None. visit = self.visit_link if not visit: # No visit, no user self._user = None else: # Unless we were given the user_name and password to login on # this request, a CSRF token is required if (not '_csrf_token' in cherrypy.request.params or cherrypy.request.params['_csrf_token'] != hash_constructor(self.visit_key).hexdigest()): log.info("Bad _csrf_token") if '_csrf_token' in cherrypy.request.params: log.info("visit: %s token: %s" % (self.visit_key, cherrypy.request.params['_csrf_token'])) else: log.info('No _csrf_token present') cherrypy.request.fas_identity_failure_reason = 'bad_csrf' self._user = None try: return self._user except AttributeError: # User hasn't already been set # Attempt to load the user. After this code executes, there # *will* be a _user attribute, even if the value is None. self._user = self.__retrieve_user() return self._user
def make_hash_key(report, objects_list): """This function make a hash key from a list of objects. Situation 1 ----------- If the objects have an method 'repr_for_cache_hash_key', it is called to get their string repr value. This is the default way to get repr strings from rendered pages and objects. Situation 2 ----------- Otherwise, if exists, the method 'get_cache_relevant_attributes' from report will be called to request what attributes have to be used from the object list to make the string. If the method above does't exists, then all attributes explicitly found in report elements will be used. The result list will be transformed to a long concatenated string and a hash key will be generated from it.""" global get_report_cache_attributes result = [] # Get attributes for cache from report if hasattr(report, 'get_cache_relevant_attributes'): report_attrs = report.get_cache_relevant_attributes else: report_attrs = lambda: get_report_cache_attributes(report) for obj in objects_list: # Situation 1 - mostly report pages and geraldo objects if hasattr(obj, 'repr_for_cache_hash_key'): result.append(obj.repr_for_cache_hash_key()) # Situation 2 - mostly queryset objects list else: result.append(u'/'.join([ unicode(get_attr_value(obj, attr)) for attr in report_attrs() ])) # Makes the hash key m = hash_constructor() m.update(u'\n'.join(result)) return '%s-%s' % (report.cache_prefix, m.hexdigest())
def make_hash_key(report, objects_list): """This function make a hash key from a list of objects. Situation 1 ----------- If the objects have an method 'repr_for_cache_hash_key', it is called to get their string repr value. This is the default way to get repr strings from rendered pages and objects. Situation 2 ----------- Otherwise, if exists, the method 'get_cache_relevant_attributes' from report will be called to request what attributes have to be used from the object list to make the string. If the method above does't exists, then all attributes explicitly found in report elements will be used. The result list will be transformed to a long concatenated string and a hash key will be generated from it.""" global get_report_cache_attributes result = [] # Get attributes for cache from report if hasattr(report, 'get_cache_relevant_attributes'): report_attrs = report.get_cache_relevant_attributes else: report_attrs = lambda: get_report_cache_attributes(report) for obj in objects_list: # Situation 1 - mostly report pages and geraldo objects if hasattr(obj, 'repr_for_cache_hash_key'): result.append(obj.repr_for_cache_hash_key()) # Situation 2 - mostly queryset objects list else: result.append(u'/'.join([unicode(get_attr_value(obj, attr)) for attr in report_attrs()])) # Makes the hash key m = hash_constructor() m.update(u'\n'.join(result)) return '%s-%s'%(report.cache_prefix, m.hexdigest())
def _get_user(self): '''Get user instance for this identity.''' visit = self.visit_key if not visit: # No visit, no user self._user = None else: if not (self.username and self.password): # Unless we were given the user_name and password to login on # this request, a CSRF token is required if (not '_csrf_token' in cherrypy.request.params or cherrypy.request.params['_csrf_token'] != hash_constructor(self.visit_key).hexdigest()): self.log.info("Bad _csrf_token") if '_csrf_token' in cherrypy.request.params: self.log.info("visit: %s token: %s" % ( self.visit_key, cherrypy.request.params['_csrf_token'])) else: self.log.info('No _csrf_token present') cherrypy.request.fas_identity_failure_reason = 'bad_csrf' self._user = None # pylint: disable-msg=W0704 try: return self._user except AttributeError: # User hasn't already been set # Attempt to load the user. After this code executes, there # *will* be a _user attribute, even if the value is None. self._user = self.__retrieve_user() if self._user: self._groups = frozenset( [g['name'] for g in self._user.approved_memberships] ) else: self._groups = frozenset() # pylint: enable-msg=W0704 return self._user
def validate_identity(self, user_name, password, visit_key, otp=None): ''' Look up the identity represented by user_name and determine whether the password is correct. Must return either None if the credentials weren't valid or an object with the following properties: user_name: original user name user: a provider dependant object (TG_User or similar) groups: a set of group IDs permissions: a set of permission IDs Side Effects: :cherrypy.request.fas_provided_username: set to user_name :cherrypy.request.fas_identity_failure_reason: if we fail to validate the user, set to the reason validation failed. Values can be: :no_user: The username was not present in the db. :status_inactive: User is disabled but can reset their password to restore service. :status_expired: User is expired, account is no more. :status_admin_disabled: User is disabled and has to talk to an admin before they are re-enabled. :bad_password: The username and password do not match. Arguments: :arg user_name: user_name we're authenticating. If None, we'll try to lookup a username from SSL variables :arg password: password to authenticate user_name with :arg visit_key: visit_key from the user's session :arg otp: One Time Password key to authenticate within the password This is an extras argument we add to request parameters in order to add 2nd factor authentication to TG1. ''' # Save the user provided username so we can do other checks on it in # outside of this method. cherrypy.request.fas_provided_username = user_name cherrypy.request.fas_identity_failure_reason = None using_ssl = False if not user_name: if cherrypy.request.headers['X-Client-Verify'] == 'SUCCESS': user_name = cherrypy.request.headers['X-Client-CN'] cherrypy.request.fas_provided_username = user_name using_ssl = True email_domain = '@' + config.get('email_host', '') if email_domain != '@' and user_name.endswith(email_domain): user_name = user_name[:-len(email_domain)] if '@' in user_name: user = user_class.query.filter_by(email=user_name).first() else: user = user_class.query.filter_by(username=user_name).first() if not user: log.warning("No such user: %s", user_name) cherrypy.request.fas_identity_failure_reason = 'no_user' return None if user.status in ('inactive', 'expired', 'admin_disabled'): log.warning("User %(username)s has status %(status)s" % { 'username': user_name, 'status': user.status }) cherrypy.request.fas_identity_failure_reason = 'status_%s' % user.status return None if not using_ssl: # Get extras args from request params to increase auth check # then pop it out if found to don't mess with other object's method if 'otp' in cherrypy.request.params: otp = cherrypy.request.params.pop('otp') if not self.validate_password(user, user_name, password, otp): log.info("Passwords don't match for user: %s", user_name) cherrypy.request.fas_identity_failure_reason = 'bad_password' return None # user + password is sufficient to prove the user is in # control cherrypy.request.params['_csrf_token'] = hash_constructor( visit_key).hexdigest() log.info("Associating user (%s) with visit (%s)", user_name, visit_key) user.last_seen = datetime.now(pytz.utc) return SaFasIdentity(visit_key, user, using_ssl)
def _get_token(self): if self.visit_key: return hash_constructor(self.visit_key).hexdigest() else: return ''
def _get_token(self): '''Get the csrf token for this identity''' if self.visit_key: return hash_constructor(self.visit_key).hexdigest() else: return ''
def _collect_variant_resources(self, resource_filter): # yes, this is sick, but it happens # that some imports can have that as # a side-effect cwd = os.getcwd() map(self._load_widgets, self.distributions) os.chdir(cwd) package = self.package filebase = None if package is not None and "/" in package: package, filebase = package.split("/", 1) def in_package(widget, filename): if package is None: return True if widget.modname.startswith(package): if filebase is None: return True return filename.startswith(filebase) return False variant_filename = tempfile.mktemp() resource_aggregator = ResourceAggregator(self, variant_filename) def widget_name(widget): filename = widget.filename if isinstance(filename, dict): filename = filename[registry.DEFAULT_VARIANT] return widget.modname, filename widgets = sorted(registry._widgets, key=widget_name) dependency_ordered_widgets = [] for widget in widgets: for resource in widget.retrieve_resources()["head"]: if resource_filter(resource) and resource not in dependency_ordered_widgets: dependency_ordered_widgets.append(resource) from tw.api import (AggregatedJSLink, AggregatedCSSLink) for widget in dependency_ordered_widgets: # don't collect other aggregates. if isinstance(widget, (AggregatedJSLink, AggregatedCSSLink)): continue variant_mapping = widget.filename # this can happen for e.g. the ThemedCSSLinks from # abl.jquery.ui if variant_mapping is None: continue if isinstance(variant_mapping, basestring): variant_mapping = {registry.DEFAULT_VARIANT : variant_mapping} if self.variant in variant_mapping: filename = variant_mapping[self.variant] else: filename = variant_mapping[registry.DEFAULT_VARIANT] _, ext = os.path.splitext(filename) if ext.lower()[1:] != self.kind: continue if not in_package(widget, filename): continue modname = widget.modname self.announce("Processing %s %s" % (modname, filename)) resource_aggregator.add_file(modname, filename) if resource_aggregator: # make the aggregator do it's actual work. # this must result in an existing variant_filename resource_aggregator.flush() inf = open(variant_filename) hash = hash_constructor() while True: block = inf.read(4096) if not block: break hash.update(block) hex = hash.hexdigest()[1:-1] dest_name = "%s-%s.%s" % (hex, self.variant, self.kind) dest_name = os.path.join(self.output, dest_name) os.rename(variant_filename, dest_name) self.announce("Created concatenatenated file: %s" % dest_name, log.INFO) dest_name = "%s-%s.%s.map" % (hex, self.variant, self.kind) dest_name = os.path.join(self.output, dest_name) outf = open(dest_name, "w") resource_aggregator.write_mapfile(outf) outf.close() resource_aggregator.post_hook(dest_name) self.announce("Created mapping file: %s" % dest_name, log.INFO)
def validate_identity(self, user_name, password, visit_key): ''' Look up the identity represented by user_name and determine whether the password is correct. Must return either None if the credentials weren't valid or an object with the following properties: user_name: original user name user: a provider dependant object (TG_User or similar) groups: a set of group IDs permissions: a set of permission IDs Side Effects: :cherrypy.request.fas_provided_username: set to user_name :cherrypy.request.fas_identity_failure_reason: if we fail to validate the user, set to the reason validation failed. Values can be: :no_user: The username was not present in the db. :status_inactive: User is disabled but can reset their password to restore service. :status_expired: User is expired, account is no more. :status_admin_disabled: User is disabled and has to talk to an admin before they are re-enabled. :bad_password: The username and password do not match. Arguments: :arg user_name: user_name we're authenticating. If None, we'll try to lookup a username from SSL variables :arg password: password to authenticate user_name with :arg visit_key: visit_key from the user's session ''' # Save the user provided username so we can do other checks on it in # outside of this method. cherrypy.request.fas_provided_username = user_name cherrypy.request.fas_identity_failure_reason = None using_ssl = False if not user_name: if cherrypy.request.headers['X-Client-Verify'] == 'SUCCESS': user_name = cherrypy.request.headers['X-Client-CN'] cherrypy.request.fas_provided_username = user_name using_ssl = True user = user_class.query.filter_by(username=user_name).first() if not user: log.warning("No such user: %s", user_name) cherrypy.request.fas_identity_failure_reason = 'no_user' return None if user.status in ('inactive', 'expired', 'admin_disabled'): log.warning("User %(username)s has status %(status)s" % \ { 'username': user_name, 'status': user.status }) cherrypy.request.fas_identity_failure_reason = 'status_%s' \ % user.status return None if not using_ssl: if not self.validate_password(user, user_name, password): log.info("Passwords don't match for user: %s", user_name) cherrypy.request.fas_identity_failure_reason = 'bad_password' return None # user + password is sufficient to prove the user is in # control cherrypy.request.params['_csrf_token'] = hash_constructor( visit_key).hexdigest() log.info("Associating user (%s) with visit (%s)", user_name, visit_key) user.last_seen = datetime.now(pytz.utc) return SaFasIdentity(visit_key, user, using_ssl)
def validate_identity(self, user_name, password, visit_key, otp=None): ''' Look up the identity represented by user_name and determine whether the password is correct. Must return either None if the credentials weren't valid or an object with the following properties: user_name: original user name user: a provider dependant object (TG_User or similar) groups: a set of group IDs permissions: a set of permission IDs Side Effects: :cherrypy.request.fas_provided_username: set to user_name :cherrypy.request.fas_identity_failure_reason: if we fail to validate the user, set to the reason validation failed. Values can be: :no_user: The username was not present in the db. :status_inactive: User is disabled but can reset their password to restore service. :status_expired: User is expired, account is no more. :status_admin_disabled: User is disabled and has to talk to an admin before they are re-enabled. :bad_password: The username and password do not match. Arguments: :arg user_name: user_name we're authenticating. If None, we'll try to lookup a username from SSL variables :arg password: password to authenticate user_name with :arg visit_key: visit_key from the user's session :arg otp: One Time Password key to authenticate within the password This is an extras argument we add to request parameters in order to add 2nd factor authentication to TG1. ''' # Save the user provided username so we can do other checks on it in # outside of this method. cherrypy.request.fas_provided_username = user_name cherrypy.request.fas_identity_failure_reason = None using_ssl = False email_domain = '@' + config.get('email_host', '') if email_domain != '@' and user_name.endswith(email_domain): user_name = user_name[:-len(email_domain)] if '@' in user_name: user = user_class.query.filter_by(email=user_name).first() else: user = user_class.query.filter_by(username=user_name).first() if not user: log.warning("No such user: %s", user_name) cherrypy.request.fas_identity_failure_reason = 'no_user' return None if user.status not in active_statuses: log.warning("User %(username)s has status %(status)s" % {'username': user_name, 'status': user.status}) cherrypy.request.fas_identity_failure_reason = 'status_%s'% user.status return None # Get extras args from request params to increase auth check # then pop it out if found to don't mess with other object's method if 'otp' in cherrypy.request.params: otp = cherrypy.request.params.pop('otp') if not self.validate_password(user, user_name, password, otp): log.info("Passwords don't match for user: %s", user_name) cherrypy.request.fas_identity_failure_reason = 'bad_password' return None # user + password is sufficient to prove the user is in # control cherrypy.request.params['_csrf_token'] = hash_constructor( visit_key).hexdigest() log.info("Associating user (%s) with visit (%s)", user_name, visit_key) user.last_seen = datetime.now(pytz.utc) if config.get('ipa_sync_enabled', False): self.sync_user_to_ipa(user, user_name, password) return SaFasIdentity(visit_key, user, using_ssl)
def _collect_variant_resources(self, resource_filter): # yes, this is sick, but it happens # that some imports can have that as # a side-effect cwd = os.getcwd() map(self._load_widgets, self.distributions) os.chdir(cwd) package = self.package filebase = None if package is not None and "/" in package: package, filebase = package.split("/", 1) def in_package(widget, filename): if package is None: return True if widget.modname.startswith(package): if filebase is None: return True return filename.startswith(filebase) return False variant_filename = tempfile.mktemp() resource_aggregator = ResourceAggregator(self, variant_filename) def widget_name(widget): filename = widget.filename if isinstance(filename, dict): filename = filename[registry.DEFAULT_VARIANT] return widget.modname, filename widgets = sorted(registry._widgets, key=widget_name) dependency_ordered_widgets = [] for widget in widgets: for resource in widget.retrieve_resources()["head"]: if resource_filter( resource ) and resource not in dependency_ordered_widgets: dependency_ordered_widgets.append(resource) from tw.api import (AggregatedJSLink, AggregatedCSSLink) for widget in dependency_ordered_widgets: # don't collect other aggregates. if isinstance(widget, (AggregatedJSLink, AggregatedCSSLink)): continue variant_mapping = widget.filename # this can happen for e.g. the ThemedCSSLinks from # abl.jquery.ui if variant_mapping is None: continue if isinstance(variant_mapping, basestring): variant_mapping = {registry.DEFAULT_VARIANT: variant_mapping} if self.variant in variant_mapping: filename = variant_mapping[self.variant] else: filename = variant_mapping[registry.DEFAULT_VARIANT] _, ext = os.path.splitext(filename) if ext.lower()[1:] != self.kind: continue if not in_package(widget, filename): continue modname = widget.modname self.announce("Processing %s %s" % (modname, filename)) resource_aggregator.add_file(modname, filename) if resource_aggregator: # make the aggregator do it's acutal work. # this must result in an existing variant_filename resource_aggregator.flush() inf = open(variant_filename) hash = hash_constructor() while True: block = inf.read(4096) if not block: break hash.update(block) hex = hash.hexdigest()[1:-1] dest_name = "%s-%s.%s" % (hex, self.variant, self.kind) dest_name = os.path.join(self.output, dest_name) os.rename(variant_filename, dest_name) self.announce("Created concatenatenated file: %s" % dest_name, log.INFO) dest_name = "%s-%s.%s.map" % (hex, self.variant, self.kind) dest_name = os.path.join(self.output, dest_name) outf = open(dest_name, "w") resource_aggregator.write_mapfile(outf) outf.close() resource_aggregator.post_hook(dest_name) self.announce("Created mapping file: %s" % dest_name, log.INFO)