Beispiel #1
0
def create_user(strategy, details, backend, user=None, *args, **kwargs):
    """Aggressively attempt to register and sign in new user"""
    if user:
        return None

    request = strategy.request
    email = details.get('email')
    username = kwargs.get('clean_username')

    if not email or not username:
        return None

    try:
        validate_email(email)
        validate_new_registration(request, {
            'email': email,
            'username': username,
        })
    except ValidationError:
        return None

    activation_kwargs = {}
    if settings.account_activation == 'admin':
        activation_kwargs = {'requires_activation': UserModel.ACTIVATION_ADMIN}

    new_user = UserModel.objects.create_user(username,
                                             email,
                                             create_audit_trail=True,
                                             joined_from_ip=request.user_ip,
                                             set_default_avatar=True,
                                             **activation_kwargs)

    send_welcome_email(request, new_user)

    return {'user': new_user, 'is_new': True}
Beispiel #2
0
    def clean(self):
        data = super(ChangeEmailPasswordForm, self).clean()

        current_password = data.get('current_password')
        new_email = data.get('new_email')
        new_password = data.get('new_password')

        if not data.get('current_password'):
            message = _("You have to enter your current password.")
            raise forms.ValidationError(message)

        if not self.user.check_password(current_password):
            raise forms.ValidationError(_("Entered password is invalid."))

        if not (new_email or new_password):
            message = _("You have to enter new e-mail or password.")
            raise forms.ValidationError(message)

        if new_email:
            if new_email.lower() == self.user.email.lower():
                message = _("New e-mail is same as current one.")
                raise forms.ValidationError(message)
            validate_email(new_email)

        if new_password:
            validate_password(new_password)

        return data
Beispiel #3
0
def validate_email(request, user=None):
    try:
        validators.validate_email(request.POST['email'],
                                  exclude=user)
        return _("Entered e-mail is valid.")
    except KeyError:
        raise ValidationError(_('Enter e-mail address.'))
Beispiel #4
0
    def clean(self):
        data = super(ChangeEmailPasswordForm, self).clean()

        current_password = data.get('current_password')
        new_email = data.get('new_email')
        new_password = data.get('new_password')

        if not data.get('current_password'):
            message = _("You have to enter your current password.")
            raise forms.ValidationError(message)

        if not self.user.check_password(current_password):
            raise forms.ValidationError(_("Entered password is invalid."))

        if not (new_email or new_password):
            message = _("You have to enter new e-mail or password.")
            raise forms.ValidationError(message)

        if new_email:
            if new_email.lower() == self.user.email.lower():
                message = _("New e-mail is same as current one.")
                raise forms.ValidationError(message)
            validate_email(new_email)

        if new_password:
            validate_password(new_password)

        return data
Beispiel #5
0
    def create_user(self, username, email, password=None,
                    set_default_avatar=False, **extra_fields):
        from misago.users.validators import (validate_email, validate_password,
                                             validate_username)

        with transaction.atomic():
            if not email:
                raise ValueError(_("User must have an email address."))
            if not password:
                raise ValueError(_("User must have a password."))

            validate_username(username)
            validate_email(email)
            validate_password(password)

            if not 'joined_from_ip' in extra_fields:
                extra_fields['joined_from_ip'] = '127.0.0.1'

            if not 'timezone' in extra_fields:
                extra_fields['timezone'] = settings.default_timezone

            WATCH_DICT = {
                'no': AUTO_SUBSCRIBE_NONE,
                'watch': AUTO_SUBSCRIBE_WATCH,
                'watch_email': AUTO_SUBSCRIBE_WATCH_AND_EMAIL,
            }

            if not 'subscribe_to_started_threads' in extra_fields:
                new_value = WATCH_DICT[settings.subscribe_start]
                extra_fields['subscribe_to_started_threads'] = new_value

            if not 'subscribe_to_replied_threads' in extra_fields:
                new_value = WATCH_DICT[settings.subscribe_reply]
                extra_fields['subscribe_to_replied_threads'] = new_value

            now = timezone.now()
            user = self.model(is_staff=False, is_superuser=False,
                              last_login=now, joined_on=now, **extra_fields)

            user.set_username(username)
            user.set_email(email)
            user.set_password(password)

            if not 'rank' in extra_fields:
                user.rank = Rank.objects.get_default()

            user.save(using=self._db)

            if set_default_avatar:
                avatars.set_default_avatar(user)

            authenticated_role = Role.objects.get(special_role='authenticated')
            if authenticated_role not in user.roles.all():
                user.roles.add(authenticated_role)

            user.update_acl_key()
            user.save(update_fields=['acl_key'])

            return user
Beispiel #6
0
    def create_user(self, username, email, password=None, set_default_avatar=False, **extra_fields):
        from misago.users.validators import validate_email, validate_password, validate_username

        with transaction.atomic():
            if not email:
                raise ValueError(_("User must have an email address."))
            if not password:
                raise ValueError(_("User must have a password."))

            validate_username(username)
            validate_email(email)
            validate_password(password)

            if not "joined_from_ip" in extra_fields:
                extra_fields["joined_from_ip"] = "127.0.0.1"

            WATCH_DICT = {
                "no": AUTO_SUBSCRIBE_NONE,
                "watch": AUTO_SUBSCRIBE_WATCH,
                "watch_email": AUTO_SUBSCRIBE_WATCH_AND_EMAIL,
            }

            if not "subscribe_to_started_threads" in extra_fields:
                new_value = WATCH_DICT[settings.subscribe_start]
                extra_fields["subscribe_to_started_threads"] = new_value

            if not "subscribe_to_replied_threads" in extra_fields:
                new_value = WATCH_DICT[settings.subscribe_reply]
                extra_fields["subscribe_to_replied_threads"] = new_value

            now = timezone.now()
            user = self.model(is_staff=False, is_superuser=False, last_login=now, joined_on=now, **extra_fields)

            user.set_username(username)
            user.set_email(email)
            user.set_password(password)

            if not "rank" in extra_fields:
                user.rank = Rank.objects.get_default()

            user.save(using=self._db)

            if set_default_avatar:
                avatars.set_default_avatar(user)
                user.avatar_hash = avatars.get_avatar_hash(user)
            else:
                user.avatar_hash = "abcdef01"

            authenticated_role = Role.objects.get(special_role="authenticated")
            if authenticated_role not in user.roles.all():
                user.roles.add(authenticated_role)
            user.update_acl_key()

            user.save(update_fields=["avatar_hash", "acl_key"])

            return user
Beispiel #7
0
    def validate_new_email(self, value):
        if not value:
            raise serializers.ValidationError(_("You have to enter new e-mail address."))

        if value.lower() == self.context['user'].email.lower():
            raise serializers.ValidationError(_("New e-mail is same as current one."))

        validate_email(value)

        return value
Beispiel #8
0
    def clean_new_email(self):
        data = self.cleaned_data['new_email']

        if not data:
            message = _("You have to enter new e-mail address.")
            raise forms.ValidationError(message)

        if data.lower() == self.user.email.lower():
            message = _("New e-mail is same as current one.")
            raise forms.ValidationError(message)

        validate_email(data)

        return data
Beispiel #9
0
    def clean_new_email(self):
        data = self.cleaned_data['new_email']

        if not data:
            message = _("You have to enter new e-mail address.")
            raise forms.ValidationError(message)

        if data.lower() == self.user.email.lower():
            message = _("New e-mail is same as current one.")
            raise forms.ValidationError(message)

        validate_email(data)

        return data
Beispiel #10
0
    def handle(self, *args, **options):
        username = options.get('username')
        email = options.get('email')
        password = options.get('password')
        interactive = options.get('interactive')
        verbosity = int(options.get('verbosity', 1))

        # Validate initial inputs
        if username is not None:
            try:
                username = username.strip()
                validate_username(username)
            except ValidationError as e:
                self.stderr.write(u'\n'.join(e.messages))
                username = None

        if email is not None:
            try:
                email = email.strip()
                validate_email(email)
            except ValidationError as e:
                self.stderr.write(u'\n'.join(e.messages))
                email = None

        if password is not None:
            password = password.strip()
            if password == '':
                self.stderr.write("Error: Blank passwords aren't allowed.")

        if not interactive:
            if username and email and password:
                # Call User manager's create_superuser using our wrapper
                self.create_superuser(username, email, password, verbosity)
        else:
            try:
                if hasattr(self.stdin, 'isatty') and not self.stdin.isatty():
                    raise NotRunningInTTYException("Not running in a TTY")

                # Prompt for username/password, and any other required fields.
                # Enclose this whole thing in a try/except to trap for a
                # keyboard interrupt and exit gracefully.
                while not username:
                    try:
                        message = force_str("Enter displayed username: "******"Enter e-mail address: ").strip()
                        validate_email(raw_value)
                        email = raw_value
                    except ValidationError as e:
                        self.stderr.write(u'\n'.join(e.messages))

                while not password:
                    raw_value = getpass("Enter password: "******"Repeat password:"******"Error: Your passwords didn't match.")
                        # Don't validate passwords that don't match.
                        continue
                    if raw_value.strip() == '':
                        self.stderr.write(
                            "Error: Blank passwords aren't allowed.")
                        # Don't validate blank passwords.
                        continue
                    try:
                        validate_password(raw_value,
                                          user=UserModel(username=username,
                                                         email=email))
                    except ValidationError as e:
                        self.stderr.write(u'\n'.join(e.messages))
                        response = input(
                            'Bypass password validation and create user anyway? [y/N]: '
                        )
                        if response.lower() != 'y':
                            continue
                    password = raw_value

                # Call User manager's create_superuser using our wrapper
                self.create_superuser(username, email, password, verbosity)

            except KeyboardInterrupt:
                self.stderr.write("\nOperation cancelled.")
                sys.exit(1)
            except NotRunningInTTYException:
                self.stdout.write(
                    "Superuser creation skipped due to not running in a TTY. "
                    "You can run `manage.py createsuperuser` in your project "
                    "to create one manually.")
Beispiel #11
0
    def create_user(self,
                    username,
                    email,
                    password=None,
                    set_default_avatar=False,
                    **extra_fields):
        from misago.users.validators import (validate_email, validate_password,
                                             validate_username)

        with transaction.atomic():
            if not email:
                raise ValueError(_("User must have an email address."))
            if not password:
                raise ValueError(_("User must have a password."))

            validate_username(username)
            validate_email(email)
            validate_password(password)

            if not 'joined_from_ip' in extra_fields:
                extra_fields['joined_from_ip'] = '127.0.0.1'

            WATCH_DICT = {
                'no': AUTO_SUBSCRIBE_NONE,
                'watch': AUTO_SUBSCRIBE_WATCH,
                'watch_email': AUTO_SUBSCRIBE_WATCH_AND_EMAIL,
            }

            if not 'subscribe_to_started_threads' in extra_fields:
                new_value = WATCH_DICT[settings.subscribe_start]
                extra_fields['subscribe_to_started_threads'] = new_value

            if not 'subscribe_to_replied_threads' in extra_fields:
                new_value = WATCH_DICT[settings.subscribe_reply]
                extra_fields['subscribe_to_replied_threads'] = new_value

            now = timezone.now()
            user = self.model(is_staff=False,
                              is_superuser=False,
                              last_login=now,
                              joined_on=now,
                              **extra_fields)

            user.set_username(username)
            user.set_email(email)
            user.set_password(password)

            if not 'rank' in extra_fields:
                user.rank = Rank.objects.get_default()

            user.save(using=self._db)

            if set_default_avatar:
                avatars.set_default_avatar(user)
                user.avatar_hash = avatars.get_avatar_hash(user)
            else:
                user.avatar_hash = 'abcdef01'

            authenticated_role = Role.objects.get(special_role='authenticated')
            if authenticated_role not in user.roles.all():
                user.roles.add(authenticated_role)
            user.update_acl_key()

            user.save(update_fields=['avatar_hash', 'acl_key'])

            return user
Beispiel #12
0
def validate_email(request, user=None):
    try:
        validators.validate_email(request.POST['email'], exclude=user)
        return _("Entered e-mail is valid.")
    except KeyError:
        raise ValidationError(_('Enter e-mail address.'))
    def create_user(
            self, username, email, password=None, set_default_avatar=False, **extra_fields
    ):
        from misago.users.validators import validate_email, validate_username

        email = self.normalize_email(email)
        username = self.model.normalize_username(username)

        if not email:
            raise ValueError(_("User must have an email address."))
        if not password:
            raise ValueError(_("User must have a password."))

        if not 'joined_from_ip' in extra_fields:
            extra_fields['joined_from_ip'] = '127.0.0.1'

        WATCH_DICT = {
            'no': self.model.SUBSCRIBE_NONE,
            'watch': self.model.SUBSCRIBE_NOTIFY,
            'watch_email': self.model.SUBSCRIBE_ALL,
        }

        if not 'subscribe_to_started_threads' in extra_fields:
            new_value = WATCH_DICT[settings.subscribe_start]
            extra_fields['subscribe_to_started_threads'] = new_value

        if not 'subscribe_to_replied_threads' in extra_fields:
            new_value = WATCH_DICT[settings.subscribe_reply]
            extra_fields['subscribe_to_replied_threads'] = new_value

        extra_fields.update({'is_staff': False, 'is_superuser': False})

        now = timezone.now()
        user = self.model(last_login=now, joined_on=now, **extra_fields)

        user.set_username(username)
        user.set_email(email)
        user.set_password(password)

        validate_username(username)
        validate_email(email)
        validate_password(password, user=user)

        if not 'rank' in extra_fields:
            user.rank = Rank.objects.get_default()

        user.save(using=self._db)

        if set_default_avatar:
            avatars.set_default_avatar(
                user, settings.default_avatar, settings.default_gravatar_fallback
            )
        else:
            # just for test purposes
            user.avatars = [{'size': 400, 'url': '/placekitten.com/400/400'}]

        authenticated_role = Role.objects.get(special_role='authenticated')
        if authenticated_role not in user.roles.all():
            user.roles.add(authenticated_role)
        user.update_acl_key()

        user.save(update_fields=['avatars', 'acl_key'])

        # populate online tracker with default value
        Online.objects.create(
            user=user,
            current_ip=extra_fields['joined_from_ip'],
            last_click=now,
        )

        return user
Beispiel #14
0
    def handle(self, *args, **options):
        username = options.get('username')
        email = options.get('email')
        password = options.get('password')
        interactive = options.get('interactive')
        verbosity = int(options.get('verbosity', 1))

        # Validate initial inputs
        if username is not None:
            try:
                username = username.strip()
                validate_username(username)
            except ValidationError as e:
                self.stderr.write(e.messages[0])
                username = None

        if email is not None:
            try:
                email = email.strip()
                validate_email(email)
            except ValidationError as e:
                self.stderr.write(e.messages[0])
                email = None

        if password is not None:
            try:
                password = password.strip()
                validate_password(password)
            except ValidationError as e:
                self.stderr.write(e.messages[0])
                password = None

        if not interactive:
            if username and email and password:
                # Call User manager's create_superuser using our wrapper
                self.create_superuser(username, email, password, verbosity)
        else:
            try:
                if hasattr(self.stdin, 'isatty') and not self.stdin.isatty():
                    raise NotRunningInTTYException("Not running in a TTY")

                # Prompt for username/password, and any other required fields.
                # Enclose this whole thing in a try/except to trap for a
                # keyboard interrupt and exit gracefully.
                while not username:
                    try:
                        message = force_str("Enter displayed username: "******"Enter E-mail address: ").strip()
                        validate_email(raw_value)
                        email = raw_value
                    except ValidationError as e:
                        self.stderr.write(e.messages[0])

                while not password:
                    try:
                        raw_value = getpass("Enter password: "******"Repeat password: "******"Entered passwords are different.")
                        password = raw_value
                    except ValidationError as e:
                        self.stderr.write(e.messages[0])

                # Call User manager's create_superuser using our wrapper
                self.create_superuser(username, email, password, verbosity)

            except KeyboardInterrupt:
                self.stderr.write("\nOperation cancelled.")
                sys.exit(1)
            except NotRunningInTTYException:
                self.stdout.write(
                    "Superuser creation skipped due to not running in a TTY. "
                    "You can run `manage.py createsuperuser` in your project "
                    "to create one manually.")
 def test_validate_email(self):
     """validate_email has no crashes"""
     validate_email('*****@*****.**')
     with self.assertRaises(ValidationError):
         validate_email('*')
Beispiel #16
0
 def test_validate_email(self):
     """validate_email has no crashes"""
     validate_email('*****@*****.**')
     with self.assertRaises(ValidationError):
         validate_email('*')
    def handle(self, *args, **options):
        username = options.get('username')
        email = options.get('email')
        password = options.get('password')
        interactive = options.get('interactive')
        verbosity = int(options.get('verbosity', 1))

        # Validate initial inputs
        if username is not None:
            try:
                username = username.strip()
                validate_username(username)
            except ValidationError as e:
                self.stderr.write(e.messages[0])
                username = None

        if email is not None:
            try:
                email = email.strip()
                validate_email(email)
            except ValidationError as e:
                self.stderr.write(e.messages[0])
                email = None

        if password is not None:
            try:
                password = password.strip()
                validate_password(password)
            except ValidationError as e:
                self.stderr.write(e.messages[0])
                password = None

        if not interactive:
            if username and email and password:
                # Call User manager's create_superuser using our wrapper
                self.create_superuser(username, email, password, verbosity)
        else:
            try:
                if hasattr(self.stdin, 'isatty') and not self.stdin.isatty():
                    raise NotRunningInTTYException("Not running in a TTY")

                # Prompt for username/password, and any other required fields.
                # Enclose this whole thing in a try/except to trap for a
                # keyboard interrupt and exit gracefully.
                while not username:
                    try:
                        message = force_str("Enter displayed username: "******"Enter E-mail address: ").strip()
                        validate_email(raw_value)
                        email = raw_value
                    except ValidationError as e:
                        self.stderr.write(e.messages[0])

                while not password:
                    try:
                        raw_value = getpass("Enter password: "******"Repeat password: "******"Entered passwords are different.")
                        password = raw_value
                    except ValidationError as e:
                        self.stderr.write(e.messages[0])

                # Call User manager's create_superuser using our wrapper
                self.create_superuser(username, email, password, verbosity)

            except KeyboardInterrupt:
                self.stderr.write("\nOperation cancelled.")
                sys.exit(1)
            except NotRunningInTTYException:
                self.stdout.write(
                    "Superuser creation skipped due to not running in a TTY. "
                    "You can run `manage.py createsuperuser` in your project "
                    "to create one manually."
                )
Beispiel #18
0
 def clean_email(self):
     data = self.cleaned_data['email']
     validate_email(data, exclude=self.instance)
     return data
Beispiel #19
0
    def create_user(self,
                    username,
                    email,
                    password=None,
                    set_default_avatar=False,
                    **extra_fields):
        from misago.users.validators import validate_email, validate_username

        email = self.normalize_email(email)
        username = self.model.normalize_username(username)

        if not email:
            raise ValueError(_("User must have an email address."))
        if not password:
            raise ValueError(_("User must have a password."))

        if not 'joined_from_ip' in extra_fields:
            extra_fields['joined_from_ip'] = '127.0.0.1'

        WATCH_DICT = {
            'no': self.model.SUBSCRIBE_NONE,
            'watch': self.model.SUBSCRIBE_NOTIFY,
            'watch_email': self.model.SUBSCRIBE_ALL,
        }

        if not 'subscribe_to_started_threads' in extra_fields:
            new_value = WATCH_DICT[settings.subscribe_start]
            extra_fields['subscribe_to_started_threads'] = new_value

        if not 'subscribe_to_replied_threads' in extra_fields:
            new_value = WATCH_DICT[settings.subscribe_reply]
            extra_fields['subscribe_to_replied_threads'] = new_value

        extra_fields.update({'is_staff': False, 'is_superuser': False})

        now = timezone.now()
        user = self.model(last_login=now, joined_on=now, **extra_fields)

        user.set_username(username)
        user.set_email(email)
        user.set_password(password)

        validate_username(username)
        validate_email(email)
        validate_password(password, user=user)

        if not 'rank' in extra_fields:
            user.rank = Rank.objects.get_default()

        user.save(using=self._db)

        if set_default_avatar:
            avatars.set_default_avatar(user, settings.default_avatar,
                                       settings.default_gravatar_fallback)
        else:
            # just for test purposes
            user.avatars = [{'size': 400, 'url': '/placekitten.com/400/400'}]

        authenticated_role = Role.objects.get(special_role='authenticated')
        if authenticated_role not in user.roles.all():
            user.roles.add(authenticated_role)
        user.update_acl_key()

        user.save(update_fields=['avatars', 'acl_key'])

        # populate online tracker with default value
        Online.objects.create(
            user=user,
            current_ip=extra_fields['joined_from_ip'],
            last_click=now,
        )

        return user
Beispiel #20
0
 def clean_email(self):
     data = self.cleaned_data['email']
     validate_email(data, exclude=self.instance)
     return data