Пример #1
0
def _generate_unique_username_base(txts, regex=None):
    from .account.adapter import get_adapter
    adapter = get_adapter()
    username = None
    regex = regex or r'[^\w\s@+.-]'
    for txt in txts:
        if not txt:
            continue
        username = unicodedata.normalize('NFKD', force_str(txt))
        username = username.encode('ascii', 'ignore').decode('ascii')
        username = force_str(re.sub(regex, '', username).lower())
        # Django allows for '@' in usernames in order to accomodate for
        # project wanting to use e-mail for username. In allauth we don't
        # use this, we already have a proper place for putting e-mail
        # addresses (EmailAddress), so let's not use the full e-mail
        # address and only take the part leading up to the '@'.
        username = username.split('@')[0]
        username = username.strip()
        username = re.sub(r'\s+', '_', username)
        # Finally, validating base username without database lookups etc.
        try:
            username = adapter.clean_username(username, shallow=True)
            break
        except ValidationError:
            pass
    return username or 'user'
Пример #2
0
def _generate_unique_username_base(txts, regex=None):
    from .account.adapter import get_adapter
    adapter = get_adapter()
    username = None
    regex = regex or r'[^\w\s@+.-]'
    for txt in txts:
        if not txt:
            continue
        username = unicodedata.normalize('NFKD', force_str(txt))
        username = username.encode('ascii', 'ignore').decode('ascii')
        username = force_str(re.sub(regex, '', username).lower())
        # Django allows for '@' in usernames in order to accomodate for
        # project wanting to use e-mail for username. In allauth we don't
        # use this, we already have a proper place for putting e-mail
        # addresses (EmailAddress), so let's not use the full e-mail
        # address and only take the part leading up to the '@'.
        username = username.split('@')[0]
        username = username.strip()
        username = re.sub(r'\s+', '_', username)
        # Finally, validating base username without database lookups etc.
        try:
            username = adapter.clean_username(username, shallow=True)
            break
        except ValidationError:
            pass
    return username or 'user'
Пример #3
0
def serialize_instance(instance):
    """
    Since Django 1.6 items added to the session are no longer pickled,
    but JSON encoded by default. We are storing partially complete models
    in the session (user, account, token, ...). We cannot use standard
    Django serialization, as these are models are not "complete" yet.
    Serialization will start complaining about missing relations et al.
    """
    data = {}
    for k, v in instance.__dict__.items():
        if k.startswith('_') or callable(v):
            continue
        try:
            field = instance._meta.get_field(k)
            if isinstance(field, BinaryField):
                v = force_str(base64.b64encode(v))
            elif isinstance(field, FileField):
                if v and not isinstance(v, six.string_types):
                    v = v.name
            # Check if the field is serializable. If not, we'll fall back
            # to serializing the DB values which should cover most use cases.
            try:
                json.dumps(v, cls=DjangoJSONEncoder)
            except TypeError:
                v = field.get_prep_value(v)
                k = SERIALIZED_DB_FIELD_PREFIX + k
        except FieldDoesNotExist:
            pass
        data[k] = v
    return json.loads(json.dumps(data, cls=DjangoJSONEncoder))
Пример #4
0
def serialize_instance(instance):
    """
    Since Django 1.6 items added to the session are no longer pickled,
    but JSON encoded by default. We are storing partially complete models
    in the session (user, account, token, ...). We cannot use standard
    Django serialization, as these are models are not "complete" yet.
    Serialization will start complaining about missing relations et al.
    """
    data = {}
    for k, v in instance.__dict__.items():
        if k.startswith('_') or callable(v):
            continue
        try:
            field = instance._meta.get_field(k)
            if isinstance(field, BinaryField):
                v = force_str(base64.b64encode(v))
            elif isinstance(field, FileField):
                if v and not isinstance(v, six.string_types):
                    v = v.name
            # Check if the field is serializable. If not, we'll fall back
            # to serializing the DB values which should cover most use cases.
            try:
                json.dumps(v, cls=DjangoJSONEncoder)
            except TypeError:
                v = field.get_prep_value(v)
                k = SERIALIZED_DB_FIELD_PREFIX + k
        except FieldDoesNotExist:
            pass
        data[k] = v
    return json.loads(json.dumps(data, cls=DjangoJSONEncoder))
Пример #5
0
 def ajax_response_form(self, form):
     form_spec = {
         'fields': {},
         'field_order': [],
         'errors': form.non_field_errors()
     }
     for field in form:
         field_spec = {
             'label': force_str(field.label),
             'value': field.value(),
             'help_text': force_str(field.help_text),
             'errors': [force_str(e) for e in field.errors],
             'widget': {
                 'attrs': {
                     k: force_str(v)
                     for k, v in field.field.widget.attrs.items()
                 }
             }
         }
         form_spec['fields'][field.html_name] = field_spec
         form_spec['field_order'].append(field.html_name)
     return form_spec
Пример #6
0
 def ajax_response_form(self, form):
     form_spec = {
         'fields': {},
         'field_order': [],
         'errors': form.non_field_errors()
     }
     for field in form:
         field_spec = {
             'label': force_str(field.label),
             'value': field.value(),
             'help_text': force_str(field.help_text),
             'errors': [
                 force_str(e) for e in field.errors
             ],
             'widget': {
                 'attrs': {
                     k: force_str(v)
                     for k, v in field.field.widget.attrs.items()
                 }
             }
         }
         form_spec['fields'][field.html_name] = field_spec
         form_spec['field_order'].append(field.html_name)
     return form_spec
Пример #7
0
def default_user_display(user):
    if app_settings.USER_MODEL_USERNAME_FIELD:
        return getattr(user, app_settings.USER_MODEL_USERNAME_FIELD)
    else:
        return force_str(user)
Пример #8
0
 def format_email_subject(self, subject):
     prefix = app_settings.EMAIL_SUBJECT_PREFIX
     if prefix is None:
         site = get_current_site(self.request)
         prefix = "[{name}] ".format(name=site.name)
     return prefix + force_str(subject)
Пример #9
0
 def __str__(self):
     return force_str(self.user)
Пример #10
0
 def __str__(self):
     return force_str(self.user)
Пример #11
0
 def format_email_subject(self, subject):
     prefix = app_settings.EMAIL_SUBJECT_PREFIX
     if prefix is None:
         site = get_current_site(self.request)
         prefix = "[{name}] ".format(name=site.name)
     return prefix + force_str(subject)