code: def affiliate(self):
          
          try:
              uidentities = api.unique_identities(self.db)
  
              for uid in uidentities:
                  uid.identities.sort(key=lambda x: x.id)
  
                  for identity in uid.identities:
                      # Only check email address to find new affiliations
                      if not identity.email:
                          continue
                      if not EMAIL_ADDRESS_PATTERN.match(identity.email):
                          continue
  
                      domain = identity.email.split('@')[-1]
  
                      try:
                          doms = api.domains(self.db, domain=domain, top=True)
                      except NotFoundError as e:
                          continue
  
                      if len(doms) > 1:
                          doms.sort(key=lambda d: len(d.domain), reverse=True)
  
                          msg = "multiple top domains for %s sub-domain. Domain %s selected."
                          msg = msg % (domain, doms[0].domain)
                          self.warning(msg)
  
                      organization = doms[0].organization.name
  
                      # Check enrollments to avoid insert affiliation twice
                      enrollments = api.enrollments(self.db, uid.uuid,
                                                    organization)
  
                      if enrollments:
                          continue
  
                      api.add_enrollment(self.db, uid.uuid, organization)
  
                      self.display('affiliate.tmpl', id=uid.uuid,
                                   email=identity.email, organization=organization)
          except (NotFoundError, InvalidValueError) as e:
              self.error(str(e))
              return e.code
  
          return CMD_SUCCESS
docs: Affiliate unique identities.
  
          This method enrolls unique identities to organizations using email
          addresses and top/sub domains data. Only new enrollments will be created.