Esempio n. 1
0
class DomainValidator:

    def __init__(self):
        self.email_validator = EmailValidator()

    def __call__(self, domain):
        if not self.email_validator.validate_domain_part(domain):
            raise ValidationError(_('Enter a valid domain name.'), code='invalid')
    def clean(self, value):
        value = super().clean(value)
        cleaned_values = []
        validator = EmailValidator()

        valid = True
        errors = []

        for email in value:
            if email is not '':
                validator.message = '{} is not a valid email address'.format(email)
                try:
                    validator(email)
                except ValidationError as e:
                    valid = False
                    errors.extend(e.error_list)

                cleaned_values.append(email)

        if valid:
            return cleaned_values
        else:
            raise ValidationError(errors)
Esempio n. 3
0
class WebUser(AbstractBaseUser, PermissionsMixin):

    objects = WebUserManager()

    username = models.CharField(verbose_name='username',
                                max_length=25,
                                unique=True,
                                help_text=_('25文字以下で'),
                                error_messages={'unique': 'すでに同じユーザーがいます'})

    webid = models.CharField(verbose_name='userid',
                             max_length=25,
                             unique=False,
                             help_text=_('25文字以下で'),
                             error_messages={'unique': 'すでに同じidがいます'})

    email: str = models.EmailField(
        verbose_name='email',
        max_length=25,
        unique=True,
        help_text=_('25文字以下'),
        validators=[EmailValidator()],
        error_messages={
            'unique': 'exist same user',
        },
    )

    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_(
            'Designates whether the user can log into this admin site.'),
    )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'),
    )
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    deleted: int = models.BooleanField(verbose_name='削除フラグ',
                                       default=0,
                                       blank=False,
                                       null=False)

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['webid', 'email']

    class Meta:
        verbose_name = _('webuser')
        verbose_name_plural = _('webusers')
        db_table = 'webuser'

    def clean(self):
        super().clean()
        self.email = self.__class__.objects.normalize_email(self.email)

    def email_user(self, subject, message, from_email=None, **kwargs):
        """Send an email to this user."""
        send_mail(subject, message, from_email, [self.email], **kwargs)
Esempio n. 4
0
class User(AbstractBaseUser, PermissionsMixin):
    email_validator = EmailValidator()
    username_validator = UnicodeUsernameValidator()

    email = models.EmailField(_('email address'),
                              validators=[email_validator, ],
                              unique=True)
    username = models.CharField(
        _('username'),
        max_length=150,
        unique=False,
        help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        validators=[username_validator],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=150, blank=True)
    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into this admin site.'),
    )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    EMAIL_FIELD = 'email'
    # REQUIRED_FIELDS = ['username', 'first_name', 'last_name']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def clean(self):
        super().clean()
        self.email = self.__class__.objects.normalize_email(self.email)

    def get_full_name(self):
        """
        Return the first_name plus the last_name, with a space in between.
        """
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        """Return the short name for the user."""
        return self.first_name

    def email_user(self, subject, message, from_email=None, **kwargs):
        """Send an email to this user."""
        send_mail(subject, message, from_email, [self.email], **kwargs)
Esempio n. 5
0
        return phone_number

    def clean(self):
        try:
            password = self.cleaned_data['password']
            password_2 = self.cleaned_data['password_2']
        except KeyError:
            pass
        else:
            if password != password_2:
                raise forms.ValidationError("Passwords do not match")

        return self.cleaned_data


validate_username = EmailValidator(
    message=ugettext_lazy('Username contains invalid characters.'))

_username_help = """
<span ng-if="usernameAvailabilityStatus === 'pending'">
    <i class="fa fa-circle-o-notch fa-spin"></i>
    %(checking)s
</span>
<span ng-if="usernameAvailabilityStatus === 'taken'"
      style="word-wrap:break-word;">
    <i class="fa fa-remove"></i>
    {{ usernameStatusMessage }}
</span>
<span ng-if="usernameAvailabilityStatus === 'available'"
      style="word-wrap:break-word;">
    <i class="fa fa-check"></i>
    {{ usernameStatusMessage }}
Esempio n. 6
0
File: views.py Progetto: boxed/curia
def invite(request):    
    check_access(request.user, obj=request.community, command='administrate users')

    class InviteForm(django.forms.Form):
        emails =  django.forms.CharField(label=_('E-mail addresses of friends to invite'), help_text=_('Separate with comma to invite several people at once, e.g [email protected], [email protected]'))
        message = django.forms.CharField(widget = django.forms.Textarea, required=False, label=_('Personal message'))
        
    if request.POST:
        form = InviteForm(request.POST)
        
        # validate emails
        email_seperator = re.compile(r'[ ,;]')
        emails = email_seperator.split(form.data['emails'])
        for email in emails:
            if email != '':
                if not EmailValidator(email):
                    form.errors['emails'].append(_('%s is not a valid email address') % email)
        
        if form.is_valid():
            emails = email_seperator.split(form.cleaned_data['emails'])
            message = form.cleaned_data['message']
                
            for email in emails:
                if email != '':                 
                    password = None
                    try:
                        user = User.objects.get(email=email)
                        if user in request.community.user_set.all():
                            continue
                        if user.is_active == False:
                            password = user.username
                    except User.DoesNotExist:
                        password = User.objects.make_random_password(20)
                        user = User.objects.create(email=email, username=password, is_active=False)     
                        user.set_password(password)
                        user.save()
                                    
                    if Invite.objects.filter(group=request.community, user=user, choice='-').count() == 0:
                        Invite.objects.create(user=user, group=request.community, inviter=request.user, message=message)

                    from django.template import loader, Context

                    t = loader.get_template('registration/email.html')
                    c = {
                        'password': password,
                        'email': email,
                        'domain': request.domain,
                        'inviter': request.user,
                        'message': form.data['message'],
                        'community': request.community,
                        } 
                    subject =  _('%s has invited you to %s') % (request.user, request.community)
                    html_message = t.render(Context(c))

                    from curia.html2text import html2text
                    from curia.mail import send_html_mail_with_attachments
                    text_message = html2text(html_message)
                    from django.contrib.sites.models import Site
                    send_html_mail_with_attachments(subject=subject, message=text_message, html_message=html_message, from_email='invite@'+Site.objects.get_current().domain, recipient_list=[email])

            return HttpResponseRedirect('/registration/')                
            
    else:
        form = InviteForm(initial={})
    
    return render_to_response(request, 'registration/index.html', {'form':form, 'invited':Invite.objects.filter(group=request.community, choice='-') })
Esempio n. 7
0
 (validate_integer, -42.5, ValidationError),
 (validate_integer, None, ValidationError),
 (validate_integer, 'a', ValidationError),
 (validate_integer, '\n42', ValidationError),
 (validate_integer, '42\n', ValidationError),
 (validate_email, '*****@*****.**', None),
 (validate_email, '*****@*****.**', None),
 (validate_email, 'email@[127.0.0.1]', None),
 (validate_email, 'email@[2001:dB8::1]', None),
 (validate_email, 'email@[2001:dB8:0:0:0:0:0:1]', None),
 (validate_email, 'email@[::fffF:127.0.0.1]', None),
 (validate_email, '*****@*****.**', None),
 (validate_email, '*****@*****.**', None),
 (validate_email, '[email protected].उदाहरण.परीक्षा', None),
 (validate_email, 'email@localhost', None),
 (EmailValidator(whitelist=['localdomain']), 'email@localdomain', None),
 (validate_email, '"test@test"@example.com', None),
 (validate_email, 'example@atm.%s' % ('a' * 63), None),
 (validate_email, 'example@%s.atm' % ('a' * 63), None),
 (validate_email, 'example@%s.%s.atm' % ('a' * 63, 'b' * 10), None),
 (validate_email, 'example@atm.%s' % ('a' * 64), ValidationError),
 (validate_email, 'example@%s.atm.%s' % ('b' * 64, 'a' * 63),
  ValidationError),
 (validate_email, None, ValidationError),
 (validate_email, '', ValidationError),
 (validate_email, 'abc', ValidationError),
 (validate_email, 'abc@', ValidationError),
 (validate_email, 'abc@bar', ValidationError),
 (validate_email, 'a @x.cz', ValidationError),
 (validate_email, '[email protected]', ValidationError),
 (validate_email, 'something@@somewhere.com', ValidationError),
Esempio n. 8
0
class ModelWithCharField(models.Model):
    char_field_with_max = CharField(max_length=10, default='', blank=True)
    char_field_without_max = CharField(default='', blank=True)
    char_field_as_email = CharField(validators=[EmailValidator(message='failed')], blank=True)
Esempio n. 9
0
class School(models.Model):
    name = models.CharField(max_length=255, null=False)
    email = models.EmailField(max_length=40, validators=[EmailValidator()])
Esempio n. 10
0
class ContactForm(forms.Form):
    contact_name = forms.CharField(label=_("Your Name"), required=True, max_length = 51)
    contact_email = forms.EmailField(label=_("Your Email Address"), required=True, max_length = 201, validators = [EmailValidator()])
    contact_id = forms.CharField(label=_("Your Test URL"), required=True, max_length = 101)
    content = forms.CharField(label=_("What would you like to tell us?"),
        required=True,
        widget=forms.Textarea(attrs={'cols': 80, 'rows': 6}),
        max_length = 1001
    )

    def __init__(self, *args, **kwargs):
        self.redirect_url = kwargs.pop('redirect_url', '')
        super(ContactForm, self).__init__(*args, **kwargs)
        self.fields['contact_id'].initial=self.redirect_url
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-3'
        self.helper.field_class = 'col-lg-9'
        self.helper.layout = Layout(
            Field('contact_name'), 
            Field('contact_email'), 
            Field('contact_id', css_class = "form-control-plaintext"), 
            Field('content'), 
            Div(Submit('submit',_('Submit')), css_class="col-lg-offset-3 col-lg-9 text-center"))
Esempio n. 11
0
    def is_completed(self, request, warn=False):
        self.request = request
        try:
            emailval = EmailValidator()
            if not self.cart_session.get('email') and not self.all_optional:
                if warn:
                    messages.warning(request,
                                     _('Please enter a valid email address.'))
                return False
            if self.cart_session.get('email'):
                emailval(self.cart_session.get('email'))
        except ValidationError:
            if warn:
                messages.warning(request,
                                 _('Please enter a valid email address.'))
            return False

        if not self.all_optional:

            if self.address_asked:
                if request.event.settings.invoice_address_required and (
                        not self.invoice_address
                        or not self.invoice_address.street):
                    messages.warning(request,
                                     _('Please enter your invoicing address.'))
                    return False

            if request.event.settings.invoice_name_required and (
                    not self.invoice_address or not self.invoice_address.name):
                messages.warning(request, _('Please enter your name.'))
                return False

        for cp in self._positions_for_questions:
            answ = {aw.question_id: aw for aw in cp.answerlist}
            question_cache = {q.pk: q for q in cp.item.questions_to_ask}

            def question_is_visible(parentid, qvals):
                if parentid not in question_cache:
                    return False
                parentq = question_cache[parentid]
                if parentq.dependency_question_id and not question_is_visible(
                        parentq.dependency_question_id,
                        parentq.dependency_values):
                    return False
                if parentid not in answ:
                    return False
                return (
                    ('True' in qvals and answ[parentid].answer == 'True')
                    or ('False' in qvals and answ[parentid].answer == 'False')
                    or
                    (any(qval in
                         [o.identifier for o in answ[parentid].options.all()]
                         for qval in qvals)))

            def question_is_required(q):
                return (q.required and
                        (not q.dependency_question_id or question_is_visible(
                            q.dependency_question_id, q.dependency_values)))

            for q in cp.item.questions_to_ask:
                if question_is_required(q) and q.id not in answ:
                    if warn:
                        messages.warning(
                            request,
                            _('Please fill in answers to all required questions.'
                              ))
                    return False
            if cp.item.admission and self.request.event.settings.get('attendee_names_required', as_type=bool) \
                    and not cp.attendee_name_parts:
                if warn:
                    messages.warning(
                        request,
                        _('Please fill in answers to all required questions.'))
                return False
            if cp.item.admission and self.request.event.settings.get('attendee_emails_required', as_type=bool) \
                    and cp.attendee_email is None:
                if warn:
                    messages.warning(
                        request,
                        _('Please fill in answers to all required questions.'))
                return False
            if cp.item.admission and self.request.event.settings.get('attendee_company_required', as_type=bool) \
                    and cp.company is None:
                if warn:
                    messages.warning(
                        request,
                        _('Please fill in answers to all required questions.'))
                return False
            if cp.item.admission and self.request.event.settings.get('attendee_attendees_required', as_type=bool) \
                    and (cp.street is None or cp.city is None or cp.country is None):
                if warn:
                    messages.warning(
                        request,
                        _('Please fill in answers to all required questions.'))
                return False

            responses = question_form_fields.send(sender=self.request.event,
                                                  position=cp)
            form_data = cp.meta_info_data.get('question_form_data', {})
            for r, response in sorted(responses, key=lambda r: str(r[0])):
                for key, value in response.items():
                    if value.required and not form_data.get(key):
                        return False
        return True
Esempio n. 12
0
        except KeyError:
            pass
        else:
            validate_username('*****@*****.**' % username)
            domain = self.cleaned_data['domain']
            username = format_username(username, domain)
            num_couch_users = len(CouchUser.view("users/by_username",
                                                 key=username))
            if num_couch_users > 0:
                raise forms.ValidationError("CommCare user already exists")

            # set the cleaned username to [email protected]
            self.cleaned_data['username'] = username
        return self.cleaned_data

validate_username = EmailValidator(email_re, _(u'Username contains invalid characters.'), 'invalid')

class SupplyPointSelectWidget(forms.Widget):
    def __init__(self, attrs=None, domain=None):
        super(SupplyPointSelectWidget, self).__init__(attrs)
        self.domain = domain

    def render(self, name, value, attrs=None):
        return get_template('locations/manage/partials/autocomplete_select_widget.html').render(Context({
                    'name': name,
                    'value': value,
                    'query_url': reverse('corehq.apps.commtrack.views.api_query_supply_point', args=[self.domain]),
                }))

class CommtrackUserForm(forms.Form):
    supply_point = forms.CharField(label='Supply Point:', required=False)
class PasswordResetsSerializer(serializers.Serializer):
    """Serializer for Forgot passwords view.
    """

    email = serializers.CharField(max_length=150,
                                  validators=[EmailValidator()])

    def create(self, validated_data):
        """Creates the Passwords Reset token and email the corresponding user.

        :param validated_data: The validated data.
        """
        self.reset_password(
            email=validated_data["email"],
            request=self.context["request"],
            email_template_name="passwords/password_reset_email_custom.html")
        self._data = {
            "success":
            True,
            "message":
            "If the user exists in our system, then the email has been sent."
        }
        return object

    def reset_password(
            self,
            email,
            domain_override=None,
            subject_template_name="registration/password_reset_subject.txt",
            email_template_name="registration/password_reset_email.html",
            token_generator=default_token_generator,
            from_email=None,
            request=None,
            html_email_template_name=None,
            extra_email_context=None):
        """
        Generate a one-use only link for resetting password and send it to the
        user.
        """
        email_field_name = User.get_email_field_name()
        for user in self.get_users(email):
            if not domain_override:
                current_site = get_current_site(request)
                site_name = current_site.name
                domain = current_site.domain
            else:
                site_name = domain = domain_override
            user_email = getattr(user, email_field_name)
            context = {
                'email': user_email,
                'domain': domain,
                'site_name': site_name,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'user': user,
                'token': token_generator.make_token(user),
                'protocol':
                'https' if settings.USE_HTTPS_IN_RESET_PASSWORD else 'http',
                'app_name': 'Key2Bliss',
                **(extra_email_context or {}),
            }
            self.send_mail(
                subject_template_name,
                email_template_name,
                context,
                from_email,
                user_email,
                html_email_template_name=html_email_template_name,
            )

    def send_mail(self,
                  subject_template_name,
                  email_template_name,
                  context,
                  from_email,
                  to_email,
                  html_email_template_name=None):
        """
        Send a django.core.mail.EmailMultiAlternatives to `to_email`.
        """
        subject = loader.render_to_string(subject_template_name, context)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        body = loader.render_to_string(email_template_name, context)

        email_message = EmailMultiAlternatives(subject, body, from_email,
                                               [to_email])
        if html_email_template_name is not None:
            html_email = loader.render_to_string(html_email_template_name,
                                                 context)
            email_message.attach_alternative(html_email, 'text/html')

        email_message.send()

    def get_users(self, email):
        """Given an email, return matching user(s) who should receive a reset.

        This allows subclasses to more easily customize the default policies
        that prevent inactive users and users with unusable passwords from
        resetting their password.
        """
        email_field_name = User.get_email_field_name()
        active_users = User._default_manager.filter(
            **{
                '%s__iexact' % email_field_name: email,
                'is_active': True,
            })
        return (u for u in active_users if u.has_usable_password()
                and _unicode_ci_compare(email, getattr(u, email_field_name)))
Esempio n. 14
0
class Sede(InfoSistema, Ubicacion):
    BOOL_ACTIVO = ((True, 'Si'), (False, 'No'))
    entidad = models.ForeignKey(Entidad)
    nombre = models.CharField(max_length=255,
                              validators=[
                                  MinLengthValidator(1),
                                  MaxLengthValidator(255),
                              ],
                              unique=True,
                              db_index=True,
                              help_text='Escribir el nombre de la sede.')
    sitio_web = models.OneToOneField(
        SitioWeb,
        unique=True,
    )
    telefono = models.CharField(verbose_name="Télefono",
                                max_length=20,
                                blank=True,
                                null=True,
                                help_text='(Opcional).')

    fax = models.CharField(max_length=20,
                           blank=True,
                           null=True,
                           help_text='(Opcional).')

    email = models.EmailField(verbose_name='Correo electrónico (Sede)',
                              max_length=100,
                              unique=True,
                              db_index=True,
                              validators=[
                                  EmailValidator(),
                              ])
    fecha_creacion = models.DateField(verbose_name='Fecha creación',
                                      blank=True,
                                      null=True)
    fecha_cese = models.DateField(blank=True, null=True)
    descripcion_sede = models.TextField('Descripción (Sede)',
                                        blank=True,
                                        null=True,
                                        help_text='(Opcional).')
    observacion_sede = models.TextField('Observación (Sede)',
                                        blank=True,
                                        null=True,
                                        help_text='(Opcional).')
    activo = models.BooleanField(choices=BOOL_ACTIVO, default=True)

    #Métodos
    #Python 3.X
    def __str__(self):
        return self.get_nombre_full()

    #Python 2.X
    #def __unicode__(self):
    #	return self.nombre
    def get_nombre(self):
        return self.nombre

    def get_nombre_full(self):
        return ' %s | %s ' % (self.entidad.get_nombre(), self.get_nombre())

    def save(self, *args, **kwargs):
        if not self.pk:
            self.slug = slugify(self.get_nombre())
        else:
            slug = slugify(self.get_nombre())
            if self.slug != slug:
                self.slug = slug
        super(Sede, self).save(*args, **kwargs)

    #Opciones
    class Meta:
        #Nombre para la tabla del gestor de base de datos
        db_table = 'Sedes'
        #Ordenar los registros por un campo especifico
        ordering = ('nombre', )
        #Nombre para el Conjunto de Objetos en el Panel de Administración
        verbose_name = 'Sede'
        #Nombre en Plural en la lista de módulos en el Panel de Administración
        verbose_name_plural = 'Sedes'
Esempio n. 15
0
    def test_serialize_class_based_validators(self):
        """
        Ticket #22943: Test serialization of class-based validators, including
        compiled regexes.
        """
        validator = RegexValidator(message="hello")
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(
            string, "django.core.validators.RegexValidator(message='hello')")
        self.serialize_round_trip(validator)

        # Test with a compiled regex.
        validator = RegexValidator(regex=re.compile(r'^\w+$', re.U))
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(
            string,
            "django.core.validators.RegexValidator(regex=re.compile('^\\\\w+$', 32))"
        )
        self.serialize_round_trip(validator)

        # Test a string regex with flag
        validator = RegexValidator(r'^[0-9]+$', flags=re.U)
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(
            string,
            "django.core.validators.RegexValidator('^[0-9]+$', flags=32)")
        self.serialize_round_trip(validator)

        # Test message and code
        validator = RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', 'invalid')
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(
            string,
            "django.core.validators.RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', 'invalid')"
        )
        self.serialize_round_trip(validator)

        # Test with a subclass.
        validator = EmailValidator(message="hello")
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(
            string, "django.core.validators.EmailValidator(message='hello')")
        self.serialize_round_trip(validator)

        validator = deconstructible(
            path="migrations.test_writer.EmailValidator")(EmailValidator)(
                message="hello")
        string = MigrationWriter.serialize(validator)[0]
        self.assertEqual(
            string, "migrations.test_writer.EmailValidator(message='hello')")

        validator = deconstructible(
            path="custom.EmailValidator")(EmailValidator)(message="hello")
        with six.assertRaisesRegex(self, ImportError,
                                   "No module named '?custom'?"):
            MigrationWriter.serialize(validator)

        validator = deconstructible(
            path="django.core.validators.EmailValidator2")(EmailValidator)(
                message="hello")
        with self.assertRaisesMessage(
                ValueError,
                "Could not find object EmailValidator2 in django.core.validators."
        ):
            MigrationWriter.serialize(validator)
Esempio n. 16
0
from friends.importer import import_vcards
# from friends.forms import JoinRequestForm

# @@@ move to django-friends when ready


class ImportVCardForm(forms.Form):
    vcard_file = forms.FileField(label="vCard File")

    def save(self, user):
        imported, total = import_vcards(
            self.cleaned_data["vcard_file"].content, user)
        return imported, total


validate_email = EmailValidator('Enter a valid email addresses.', 'invalid')


class JoinInviteRequestForm(forms.Form):
    emails = forms.CharField(
        label="Enter email addresses of the people you would like to invite",
        required=True,
        widget=forms.Textarea(attrs={
            'cols': '30',
            'rows': '5'
        }),
        help_text="One email per line, or separated by a comma or semicolon.")
    message = forms.CharField(label="Message",
                              required=False,
                              widget=forms.Textarea(attrs={
                                  'cols': '30',
Esempio n. 17
0
 def clean(self, value, previous_values):
     if value:
         EmailValidator()(value)
     return value
Esempio n. 18
0
def check_email(email):
    try:
        EmailValidator('Некорректный email')(email)
    except ValidationError as ex:
        return ex.message
    return None
Esempio n. 19
0
            return "The Profile URL you have requested is already in use."
        # URL Fields: website, facebook, linkedin
        url_val = URLValidator()
        try:
            if self.facebook: url_val(self.facebook)
        except ValidationError, e:
            return "The Facebook URL you entered is not valid."
        try:
            if self.linkedin: url_val(self.linkedin)
        except ValidationError, e:
            return "The LinkedIn URL you entered is not valid."
        try:
            if self.website: url_val(self.website)
        except ValidationError, e:
            return "The Website URL you entered is not valid."
        email_val = EmailValidator()
        try:
            if self.email: email_val(self.email)
        except ValidationError, e:
            return "The email address you entered is not valid."

        return None

    def exists(self):
        """
		Returns True if this is a real existing user, not simply a mock profile.
		"""
        return bool(self.date_joined)

    def assign_slug(self):
        """
Esempio n. 20
0
from django.db import models
from django.utils.translation import gettext as _
from django.core.validators import EmailValidator

email_address = EmailValidator(
    message=_('Invalid entry. Enter a valid email address.'))


class Contacts(models.Model):
    '''
    Information of people that have used the contact form.
    '''

    #name
    name = models.CharField(verbose_name=_('Contact Name'),
                            max_length=50,
                            blank=False)

    #email
    email = models.CharField(verbose_name=_('Email'),
                             max_length=100,
                             blank=False,
                             validators=[email_address])

    #phone
    phone = models.CharField(verbose_name=_('Phone'),
                             max_length=14,
                             blank=False)

    #message
    message = models.TextField(verbose_name=_('Message'),
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError
from django.core.validators import EmailValidator
import re

email_format_validator = EmailValidator(message="Erro! Email inválido.")


def check_email_format(email):
    from django.core.validators import validate_email
    from django.core.exceptions import ValidationError
    try:
        validate_email(email) and email_dangerous_symbols_validator(email)
        return True
    except ValidationError:
        return False


def email_dangerous_symbols_validator(value):
    if '+' in value:
        raise ValidationError(_("Email can not contain the '+' character"),
                              code='security')


def password_format_validator(value):
    if is_empty(value) or not contain_minimal_size(
            value,
            8) or not contain_alpha(value) or not contain_numbers(value):
        raise ValidationError(_(
            'Password must be 8 characters or more with numbers and letters'),
                              code='invalid')
Esempio n. 22
0
File: views.py Progetto: boxed/curia
def create_community(request):
    community_types = [
        ('Friends', _("Friends")),
        ('Organization', _("Organization")),
        ('Happening', _("Happening")),
        ('Project group', _("Project group")),
        ('Online group', _("Online group")),
        ('Other group', _("Other group"))
    ]
    
    class CreateForm(django.forms.Form):
        name = django.forms.CharField(min_length=4, label=_('Name of community'))
        domain = django.forms.CharField(min_length=4, label=_('Domain'), initial='', help_text='.eldmyra.se')
        email = django.forms.CharField(max_length=150,required=True, label=_('Your e-mail address'))
        confirm_email = django.forms.CharField(max_length=150,required=True, label=_('Confirm your e-mail address'))
        community_type = django.forms.ChoiceField(choices=community_types, label=_('Describe yourself'), widget = django.forms.RadioSelect)
        user_contract = django.forms.BooleanField(required=False, widget=CheckboxInput(attrs={'label':_('I have read and accepted the <a href="/registration/administrator_agreement/" target="blank">administrator agreement</a>')}), label='')

    if request.POST:
        form = CreateForm(request.POST)
        
        email = form.data["email"]
        if email != '':
            if not EmailValidator(email):
                form.errors['email'] = (_('%s is not a valid email address') % email,)
                        
        try: 
            form.data["user_contract"]
        except:
            form.errors['user_contract'] = (_("You must accept the user agreement."),)
        
        if form.data["email"] != form.data["confirm_email"]:
            form.errors['confirm_email'] = (_("Emails did not match."),)
        
        try:
            Group.objects.get(name=form.data["name"])
            form.errors['name'] = (_("That name is already taken."),)
        except Group.DoesNotExist:
            pass
        
        forbidden_names = ['support','login','administrator','administration','admin','administrate','administrering','administrera','eldmyra']
        for forbidden_name in forbidden_names:
            if form.data['name'].lower() == forbidden_name:
                form.errors['name'] = (_("You may not call your community %s.") % forbidden_name,)
                
        forbidden_domains = ['blogg','blog','start','community','eldmyra','admin','fest','rollspel','ninja','dota','administrering','administrera','student','hantverk','demo','test','support','login','administrator','administration']
        for forbidden_domain in forbidden_domains:
            if form.data['domain'].lower() == forbidden_domain:
                form.errors['domain'] = (_("You may not use the domain name %s.eldmyra.se") % forbidden_domain, )      

        try:
            user = User.objects.get(email=request.REQUEST['email'])
        except User.DoesNotExist:
            user = None
            
        try:
            MetaGroup.objects.get(domain=form.data['domain']+'.eldmyra.se')
            form.errors['domain'] = (_('Domain name is taken, please choose another'),)
        except MetaGroup.DoesNotExist:
            pass

        if form.is_valid():
            password = None
            new_user = False
            if not user:                
                # Create new user
                password = User.objects.make_random_password(6)
                user = User.objects.create(email=form.cleaned_data['email'], username=User.objects.make_random_password(30), is_active=False)     
                user.set_password(password)
                user.save()
                new_user = True

            community = Group.objects.create(name=form.cleaned_data['name'])
            meta_group = MetaGroup.objects.create(group=community, created_by=user, domain=form.cleaned_data['domain']+'.eldmyra.se')
            presentation = Document.objects.create(owner_group=community, is_presentation=True)
            new_version = Version(document=presentation,title='Presentation', contents='', owner=user)
            new_version.save()
            community.user_set.add(user)

            if new_user:
                Invite.objects.create(user=user, group=community, inviter=user, message='')

            from django.template import loader, Context

            t = loader.get_template('registration/community_email.html')
            c = {
                'password': password,
                'email': form.cleaned_data['email'],
                'domain': meta_group.domain,
                'inviter': None,
                'message': '',
                'community': community,
                } 
            subject =  _('Your community %s has been registered at Eldmyra.se!') % (community)
            html_message = t.render(Context(c))
            
            from curia.html2text import html2text
            from curia.mail import send_html_mail_with_attachments
            text_message = html2text(html_message)
            from django.contrib.sites.models import Site
            send_html_mail_with_attachments(subject=subject, message=text_message, html_message=html_message, from_email='invite@'+Site.objects.get_current().domain, recipient_list=[form.cleaned_data['email']])
            
            # Homepage / Do not create a homepage, the no external page view is default for new communitites
            #document = Document.objects.create(owner_group=community, owner_user=user, is_presentation=False)
            #new_version = Version(document=document,title='Hem', contents='', owner=user)
            #new_version.save()
            
            # set up access rights
            #from curia.authentication import grant_access, get_public_user
            #grant_access(command='view', user=get_public_user(), obj=document)
            
            # create menu item
            #from curia.homepage.models import MenuItem
            #MenuItem.objects.create(group=community, content_type=get_content_type(document), object_id=document.id, title='Hem', url=document.get_absolute_url(), order=0, parent=None)

            from curia.labels.models import SuggestedLabel
            from curia.forums.models import Thread
            SuggestedLabel.objects.create(title=_('Events'), label=_('Events'), group=community, created_by=user, content_type=get_content_type(Thread))
            SuggestedLabel.objects.create(title=_('Links'), label=_('Links'), group=community, created_by=user, content_type=get_content_type(Thread))

            Label.objects.create(object_id=community.id, deleted=False, name=form.cleaned_data['community_type'], content_type=get_content_type(community), created_by = user, owner_user=user, owner_group=community)
            
            if new_user:
                return render_to_response(request, 'registration/create_community_done.html', {'community':community, 'disable_login_box':True})
            else:
                return HttpResponseRedirect(community.get_external_absolute_url())
    else:
        form = CreateForm()

    return render_to_response(request, 'registration/create_community.html', {'form':form, 'disable_login_box':True})    
Esempio n. 23
0
def register(request):

    if request.method == 'GET':
        if request.user.is_authenticated():
            user = request.user
        else:
            user = None

        return render(request, 'register.html', {'user': user})

    elif request.method == 'POST':

        errors = []

        username = request.POST['username']
        email = request.POST['email']
        first_name = request.POST['first-name']
        last_name = request.POST['last-name']
        affiliation = request.POST['affiliation']
        pass1 = request.POST['password1']
        pass2 = request.POST['password2']

        other_users = User.objects.filter(username=username)

        if other_users.exists():
            errors.append('A user with that username already exists.')

        if pass1 == '' or pass2 == '':
            errors.append('Password cannot be empty.')
        elif pass1 != pass2:
            errors.append('The two passwords you entered do not match.')

        if username is None or username.strip() == '':
            errors.append('Must enter a username.')

        emv = EmailValidator()
        try:
            res = emv(email)
        except ValidationError as ex:
            errors.append(ex.message)

        if first_name is None or first_name.strip() == '':
            errors.append('Enter a first name.')
        if last_name is None or last_name.strip() == '':
            errors.append('Enter a last name.')

        if errors:
            user_data = {
                'username': username,
                'email': email,
                'first_name': first_name,
                'last_name': last_name,
                'affiliation': affiliation
            }

            return render(request, 'register.html', {
                'errors': errors,
                'user_data': user_data
            })

        else:
            user = User.objects.create_user(username, email, pass1)
            user.last_name = last_name
            user.first_name = first_name
            user.save()

            qbdb_user = QBDBUser()
            qbdb_user.user = user
            qbdb_user.affiliation = affiliation
            qbdb_user.save()

            user = authenticate(username=username, password=pass1)
            login(request, user)

            return HttpResponseRedirect('/')
Esempio n. 24
0
def validate_email(email):
    validator = EmailValidator(message='The email is in wrong format')
    validator(email)
    if not re.fullmatch("^[^@]+@berkeley\\.edu", email):
        raise ValidationError(message="The domain needs to be @berkeley.edu.")
Esempio n. 25
0
class Contact(models.Model):
    """

    Stores a list of PMEL workers, related to :model:`raptr.Project`, :model:`proposal.Proposal`, :model:`crada.Crada`.

    """
    full_time_equivalent = models.FloatField(
        blank=True,
        default=1.0,
        validators=[
            MinValueValidator(0.0, message='FTEs must be between 0 and 1.'),
            MaxValueValidator(1.0, message='FTEs must be between 0 and 1.')
        ])
    position_billet = models.CharField(
        max_length=10,
        blank=True,
    )
    position_id = models.CharField(max_length=12, blank=True)
    last_name = models.CharField(max_length=50)
    first_name = models.CharField(max_length=50)
    email_address = models.EmailField(validators=[
        EmailValidator(),
    ],
                                      blank=True,
                                      null=True)
    phone_number = PhoneField(blank=True)
    room_number = models.CharField(max_length=15, blank=True)
    job_title = models.CharField(max_length=50, blank=True)
    division = models.CharField(
        choices=DIVISION_CHOICES,
        max_length=4,
        blank=True,
    )
    opt_sub_group = models.ForeignKey(Optsub,
                                      on_delete=models.DO_NOTHING,
                                      verbose_name='OPT Sub Group',
                                      blank=True,
                                      null=True)
    research_program = models.ForeignKey(Program,
                                         on_delete=models.DO_NOTHING,
                                         blank=True,
                                         null=True)
    pay_plan = models.CharField(choices=GRADE_CHOICES,
                                max_length=4,
                                blank=True)
    job_series = models.CharField(max_length=4, blank=True)
    employee_band = models.CharField(choices=PAY_BAND_CHOICES,
                                     verbose_name='band',
                                     max_length=4,
                                     blank=True)
    employee_interval = models.CharField(choices=PAY_INTERVAL_CHOICES,
                                         verbose_name='interval',
                                         max_length=4,
                                         blank=True)
    service_computation_date = models.DateField(
        blank=True,
        null=True,
        help_text='Employee\'s retirement service computation date.')
    flsa_status = models.CharField(
        verbose_name='FLSA Status',
        choices=FLSA_CHOICES,
        max_length=4,
        blank=True,
        help_text=
        'Is the person Fair Labor Standards Act (E)xempt or (N)on Exempt?')
    supervisor = models.ForeignKey(Supervisor,
                                   on_delete=models.DO_NOTHING,
                                   blank=True,
                                   null=True)
    pmel_base = models.BooleanField(
        default=False,
        verbose_name='PMEL Base',
        help_text='Is the position funded by PMEL Base Funds?')
    employee_type = models.ForeignKey(Employeetype,
                                      on_delete=models.DO_NOTHING,
                                      blank=True,
                                      null=True)
    affiliation = models.ForeignKey(Affiliation,
                                    on_delete=models.DO_NOTHING,
                                    blank=True,
                                    null=True)
    employee_category = models.CharField(choices=EMPLOYEE_CATEGORY,
                                         max_length=20,
                                         blank=True)
    is_pi = models.BooleanField(
        default=False,
        verbose_name='PI?',
        help_text='Is this person a PMEL Principal Investigator?')
    location = models.CharField(choices=LOCATIONS, max_length=15, blank=True)
    entry_on_duty = models.DateField(
        verbose_name='EOD',
        blank=True,
        null=True,
        help_text='Date person entered duty at PMEL.')
    departure_date = models.DateField(blank=True,
                                      null=True,
                                      help_text='Date person left PMEL')
    active = models.BooleanField(
        default=True,
        help_text=
        'Is the person still at PMEL? Uncheck when departure date is entered.')
    issupervisor = models.BooleanField(
        default=False, help_text='Is this person a supervisor of others?')
    photo = models.ImageField(verbose_name='Upload Photo',
                              upload_to='photos',
                              default='photos/no_photo.png',
                              blank=True,
                              null=True)
    slug = models.SlugField(
        help_text=
        "A short label, used in the URLs to camouflage the primary key "
        "- autogenerated == last_name - first_name.",
        unique=True,
        max_length=100,
    )

    class Meta:
        ordering = ['last_name']

    def __str__(self):
        return str(self.last_name) + ', ' + str(self.first_name)

    def get_absolute_url(self):
        return reverse('shared:contact_detail', kwargs={'slug': self.slug})

    def image_tag(self):
        return mark_safe('<img src="/media/%s" width="150" height="150" />' %
                         (self.photo))

    image_tag.short_description = 'Photo of Contact'
Esempio n. 26
0
class Area(InfoSistema, UbicacionInterna):
    BOOL_ACTIVO = ((True, 'Si'), (False, 'No'))
    sede = models.ForeignKey(Sede)
    area_dependiente = models.ForeignKey(
        'self',
        related_name='areas_areas_dependientes_related',
        null=True,
        blank=True,
        default=None)
    tipo_area_funcional = models.ForeignKey(TipoAreaFuncional)
    tipo_area = models.ForeignKey(TipoArea)
    nombre = models.CharField(max_length=255,
                              validators=[
                                  MinLengthValidator(1),
                                  MaxLengthValidator(255),
                              ],
                              unique=True,
                              db_index=True,
                              help_text='Escribir el nombre del área.')
    siglas = models.CharField(
        max_length=10,
        validators=[
            MinLengthValidator(1),
            MaxLengthValidator(10),
        ],
        db_index=True,
    )
    email = models.EmailField(
        verbose_name='Correo electrónico (Institucional)',
        max_length=100,
        unique=True,
        db_index=True,
        validators=[
            EmailValidator(),
        ])
    fax_interno = models.CharField(verbose_name='Fax (Interno)',
                                   max_length=20,
                                   blank=True,
                                   null=True,
                                   help_text='(Opcional).')
    anexo_interno = models.CharField(verbose_name='Anexo (Interno)',
                                     max_length=20,
                                     blank=True,
                                     null=True,
                                     help_text='(Opcional).')
    mision = models.TextField(verbose_name='Misión',
                              blank=True,
                              null=True,
                              help_text='(Opcional)')
    vision = models.TextField(verbose_name='Visión',
                              blank=True,
                              null=True,
                              help_text='(Opcional)')

    logotipo = models.ImageField(
        blank=True,
        null=True,
        upload_to='logotipos_areas',
    )
    fecha_creacion = models.DateField(verbose_name='Fecha creación',
                                      blank=True,
                                      null=True)
    fecha_cese = models.DateField(blank=True, null=True)
    descripcion = models.TextField(verbose_name='Descripción',
                                   blank=True,
                                   null=True,
                                   help_text='(Opcional)')
    observacion = models.TextField(verbose_name='Observación',
                                   blank=True,
                                   null=True,
                                   help_text='(Opcional)')
    activo = models.BooleanField(choices=BOOL_ACTIVO, default=True)

    #Métodos
    #Python 3.X
    def __str__(self):
        return self.get_siglas_nombre()

    #Python 2.X
    #def __unicode__(self):
    #	return self.nombre
    def get_tipo_area(self):
        return self.tipo_area

    def get_siglas_nombre(self):
        return '%s - %s' % (self.get_tipo_area(), self.get_nombre())

    def get_nombre(self):
        return self.nombre

    def save(self, *args, **kwargs):
        if not self.pk:
            self.slug = slugify(self.get_nombre())
        else:
            slug = slugify(self.get_nombre())
            if self.slug != slug:
                self.slug = slug
        super(Area, self).save(*args, **kwargs)

    #Opciones
    class Meta:
        #Nombre para la tabla del gestor de base de datos
        db_table = 'Areas'
        #Ordenar los registros por un campo especifico
        ordering = (
            'tipo_area',
            'nombre',
        )
        #Nombre para el Conjunto de Objetos en el Panel de Administración
        verbose_name = 'Area'
        #Nombre en Plural en la lista de módulos en el Panel de Administración
        verbose_name_plural = 'Areas'  #Métodos
Esempio n. 27
0
class User(AbstractBaseUser, PermissionsMixin):
    """
    AbstractUserをコピペして編集する
    """
    username_validator = UnicodeUsernameValidator()
    email_validator = EmailValidator()
    account_name_validator = UnicodeAccountnameValidator()

    username = models.CharField(
        _('username'),
        max_length=15,
        unique=True,
        help_text=_(
            'Required. 4 ~ 15 characters. Letters, digits and _ only.'),
        validators=[username_validator],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    account_name = models.CharField(
        _('アカウント名'),
        validators=[account_name_validator],
        max_length=10,
        help_text=_('Required. 1 ~ 10 characters.'),
    )
    email = models.EmailField(_('email address'),
                              validators=[email_validator],
                              blank=True)
    departments = models.ManyToManyField(
        Department,
        verbose_name=_('クラス'),
        blank=True,
        help_text=_('Specific Departments for this user.'),
        related_name="user_set",
        related_query_name="user",
    )
    rate = models.IntegerField(default=1500)
    short_match = models.IntegerField(default=0)
    long_match = models.IntegerField(default=0)
    short_win = models.IntegerField(default=0)
    long_win = models.IntegerField(default=0)
    '''
    favorite_answers = models.ManyToManyField(
        Answer,
        verbose_name=_('お気に入り'),
        blank=True,
        help_text=_('お気に入りの回答'),
        related_name="favorite_user_set",
        related_query_name="favorite_user",
    )
    '''
    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_(
            'Designates whether the user can log into this admin site.'),
    )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'),
    )
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = UserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['account_name', 'email']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def clean(self):
        super().clean()
        self.email = self.__class__.objects.normalize_email(self.email)

    def get_full_name(self):
        return self.account_name

    def get_short_name(self):
        return self.account_name

    def email_user(self, subject, message, from_email=None, **kwargs):
        """Send an email to this user."""
        send_mail(subject, message, from_email, [self.email], **kwargs)
Esempio n. 28
0
 def __init__(self):
     self.email_validator = EmailValidator()
Esempio n. 29
0
class AbstractBaseUser(AbstractUUIDBaseClass):
    username_validator = ASCIIUsernameValidator()
    email_validator = EmailValidator()
    username = models.CharField(
        _('username'),
        max_length=150,
        unique=True,
        help_text=_(
            'Required. 150 words or fewer. Letter, digits, and @/./+/-/_ only'
        ),
        validators=[username_validator],
        error_messages={
            'unique': _("A user with that username already exists")
        },
    )
    password = models.CharField(_('password'), max_length=128)
    first_name = models.CharField(_('first name'), max_length=50, blank=False)
    middle_name = models.CharField(_('middle name'), max_length=50, blank=True)
    last_name = models.CharField(_('last name'), max_length=50, blank=True)
    email = models.CharField(
        _('email address'),
        blank=False,
        max_length=255,
        unique=True,
        validators=[email_validator],
        error_messages={'unique': _("Provided email-id already exists.")},
    )
    is_active = models.BooleanField(_('active'), default=False)

    REQUIRED_FIELDS = ['username', 'email', 'first_name']

    class Meta:
        abstract = True
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def __init__(self, *args, **kwargs):
        super(AbstractBaseUser, self).__init__(*args, **kwargs)
        # Stores the raw password if set_password() is called so that it can
        # be passed to password_changed() after the model is saved.
        self._password = None

    def get_full_name(self):
        '''
		Return first_name plus middle_name plus last_name with space in between
		'''
        full_name = '%s %s %s' % (self.first_name, self.middle_name,
                                  self.last_name)
        return full_name.strip()

    def get_short_name(self):
        '''
		Return only first_name
		'''
        return self.first_name.strip()

    def set_password(self, raw_password):
        self.password = make_password(raw_password)
        self._password = raw_password

    def set_reset_code(self):
        self.reset_code = str(uuid.uuid4())

    def check_password(self, raw_password):
        """
		Return a boolean of whether the raw_password was correct. Handles
		hashing formats behind the scenes.
		"""
        def setter(raw_password):
            self.set_password(raw_password)
            # Password hash upgrades shouldn't be considered password changes.
            self._password = None
            self.save(update_fields=["password"])

        return check_password(raw_password, self.password, setter)