Ejemplo n.º 1
0
class AddLdapUserForm(forms.Form):
  username = forms.RegexField(
      label=_("Username"),
      max_length=64,
      regex='^%s$' % (get_username_re_rule(),),
      help_text=_("Required. 30 characters or fewer. No whitespaces or colons."),
      error_messages={'invalid': _("Whitespaces and ':' not allowed")})
  dn = forms.BooleanField(label=_("Distinguished name"),
                          help_text=_("Whether or not the user should be imported by "
                                    "distinguished name."),
                          initial=False,
                          required=False)
  ensure_home_directory = forms.BooleanField(label=_("Create home directory"),
                                            help_text=_("Create home directory for user if one doesn't already exist."),
                                            initial=True,
                                            required=False)

  def clean(self):
    cleaned_data = super(AddLdapUserForm, self).clean()
    username = cleaned_data.get("username")
    dn = cleaned_data.get("dn")

    if not dn:
      if username is not None and len(username) > 30:
        msg = _('Too long: 30 characters or fewer and not %(username)s') % dict(username=len(username),)
        errors = self._errors.setdefault('username', ErrorList())
        errors.append(msg)
        raise forms.ValidationError(msg)

    return cleaned_data
Ejemplo n.º 2
0
def validate_username(username_pattern):
    validator = re.compile(r"^%s$" % get_username_re_rule())

    assert username_pattern is not None, _('Username is required.')
    assert len(username_pattern) <= 30, _(
        'Username must be fewer than 30 characters.')
    assert validator.match(username_pattern), _(
        "Username must not contain whitespaces and ':'")
Ejemplo n.º 3
0
def validate_username(username_pattern):
  validator = re.compile(r"^%s$" % get_username_re_rule())

  if not username_pattern:
    raise ValidationError(_('Username is required.'))
  if len(username_pattern) > 30:
    raise ValidationError(_('Username must be fewer than 30 characters.'))
  if not validator.match(username_pattern):
    raise ValidationError(_("Username must not contain whitespaces and ':'"))
Ejemplo n.º 4
0
Archivo: forms.py Proyecto: ztwu/hue
def validate_username(username_pattern):
  validator = re.compile(r"^%s$" % get_username_re_rule())

  if not username_pattern:
    raise ValidationError(_('Username is required.'))
  if len(username_pattern) > 30:
    raise ValidationError(_('Username must be fewer than 30 characters.'))
  if not validator.match(username_pattern):
    raise ValidationError(_("Username must not contain whitespaces and ':'"))
Ejemplo n.º 5
0
Archivo: forms.py Proyecto: ozzie00/hue
class UserChangeForm(django.contrib.auth.forms.UserChangeForm):
    """
  This is similar, but not quite the same as djagno.contrib.auth.forms.UserChangeForm
  and UserCreationForm.
  """
    username = forms.RegexField(
        label=_t("Username"),
        max_length=30,
        regex='^%s$' % (get_username_re_rule(), ),
        help_text=_t(
            "Required. 30 characters or fewer. No whitespaces or colons."),
        error_messages={'invalid': _t("Whitespaces and ':' not allowed")})
    password1 = forms.CharField(label=_t("Password"),
                                widget=forms.PasswordInput,
                                required=False)
    password2 = forms.CharField(label=_t("Password confirmation"),
                                widget=forms.PasswordInput,
                                required=False)
    ensure_home_directory = forms.BooleanField(
        label=_t("Create home directory"),
        help_text=_t("Create home directory if one doesn't already exist."),
        initial=True,
        required=False)

    class Meta(django.contrib.auth.forms.UserChangeForm.Meta):
        fields = [
            "username", "first_name", "last_name", "email",
            "ensure_home_directory"
        ]

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1", "")
        password2 = self.cleaned_data["password2"]
        if password1 != password2:
            raise forms.ValidationError(_t("Passwords do not match."))
        return password2

    def clean_password1(self):
        password = self.cleaned_data.get("password1", "")
        if self.instance.id is None and password == "":
            raise forms.ValidationError(
                _("You must specify a password when creating a new user."))
        return self.cleaned_data.get("password1", "")

    def save(self, commit=True):
        """
    Update password if it's set.
    """
        user = super(UserChangeForm, self).save(commit=False)
        if self.cleaned_data["password1"]:
            user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
            # groups must be saved after the user
            self.save_m2m()
        return user
Ejemplo n.º 6
0
Archivo: forms.py Proyecto: ycaihua/hue
class AddLdapUsersForm(forms.Form):
    username_pattern = forms.RegexField(
        label=_t("Username"),
        regex='^%s$' % (get_username_re_rule(), ),
        help_text=_t(
            "Required. 30 characters or fewer with username. 64 characters or fewer with DN. No whitespaces or colons."
        ),
        error_messages={'invalid': _t("Whitespaces and ':' not allowed")})
    dn = forms.BooleanField(
        label=_t("Distinguished name"),
        help_text=_t("Whether or not the user should be imported by "
                     "distinguished name."),
        initial=False,
        required=False)
    ensure_home_directory = forms.BooleanField(
        label=_t("Create home directory"),
        help_text=_t(
            "Create home directory for user if one doesn't already exist."),
        initial=True,
        required=False)

    def __init__(self, *args, **kwargs):
        super(AddLdapUsersForm, self).__init__(*args, **kwargs)
        self.fields['server'] = forms.ChoiceField(choices=get_server_choices(),
                                                  required=False)

    def clean(self):
        cleaned_data = super(AddLdapUsersForm, self).clean()
        username_pattern = cleaned_data.get("username_pattern")
        dn = cleaned_data.get("dn")

        if dn:
            if username_pattern is not None and len(username_pattern) > 64:
                msg = _('Too long: 64 characters or fewer and not %s.'
                        ) % username_pattern
                errors = self._errors.setdefault('username_pattern',
                                                 ErrorList())
                errors.append(msg)
                raise forms.ValidationError(msg)
        else:
            if username_pattern is not None and len(username_pattern) > 30:
                msg = _('Too long: 30 characters or fewer and not %s.'
                        ) % username_pattern
                errors = self._errors.setdefault('username_pattern',
                                                 ErrorList())
                errors.append(msg)
                raise forms.ValidationError(msg)

        return cleaned_data
Ejemplo n.º 7
0
def monkey_patch_username_validator():
    """
  In 1.6, the `User.username` field gained some validation rules to check that
  it conformed to a particular regex. Unfortunately we use to support a more
  liberal username scheme. The proper solution would be to use our own custom
  user model, but that touches a lot of code. It's easier if we just modify the
  regular expression inside the username validator.
  """

    username = User._meta.get_field("username")

    regex = re.compile("^%s$" % get_username_re_rule())

    for validator in username.validators:
        if isinstance(validator, RegexValidator):
            validator.regex = regex
Ejemplo n.º 8
0
def monkey_patch_username_validator():
    """
  In 1.6, the `User.username` field gained some validation rules to check that
  it conformed to a particular regex. Unfortunately we use to support a more
  liberal username scheme. The proper solution would be to use our own custom
  user model, but that touches a lot of code. It's easier if we just modify the
  regular expression inside the username validator.
  """

    username = User._meta.get_field("username")

    regex = re.compile('^%s$' % get_username_re_rule())

    for validator in username.validators:
        if isinstance(validator, RegexValidator):
            validator.regex = regex
Ejemplo n.º 9
0
class AuditLoggingMiddleware(object):

    username_re = get_username_re_rule()
    groupname_re = get_groupname_re_rule()

    operations = {
        '/accounts/login': '******',
        '/accounts/logout': 'USER_LOGOUT',
        '/useradmin/users/add_ldap_users': 'ADD_LDAP_USERS',
        '/useradmin/users/add_ldap_groups': 'ADD_LDAP_GROUPS',
        '/useradmin/users/sync_ldap_users_groups': 'SYNC_LDAP_USERS_GROUPS',
        '/useradmin/users/new': 'CREATE_USER',
        '/useradmin/groups/new': 'CREATE_GROUP',
        '/useradmin/users/delete': 'DELETE_USER',
        '/useradmin/groups/delete': 'DELETE_GROUP'
    }

    operation_patterns = {
        '/useradmin/permissions/edit/(?P<app>.*)/(?P<priv>.*)':
        'EDIT_PERMISSION',
        '/useradmin/users/edit/(?P<username>%s)' % (username_re, ):
        'EDIT_USER',
        '/useradmin/groups/edit/(?P<name>%s)' % (groupname_re, ): 'EDIT_GROUP'
    }

    process_view_operations = ('USER_LOGOUT', 'DELETE_USER')

    def __init__(self):
        from desktop.conf import AUDIT_EVENT_LOG_DIR, SERVER_USER

        self.impersonator = SERVER_USER.get()

        if not AUDIT_EVENT_LOG_DIR.get():
            LOG.info('Unloading AuditLoggingMiddleware')
            raise exceptions.MiddlewareNotUsed

    def process_view(self, request, view_func, view_args, view_kwargs):
        try:
            operation = self._get_operation(request.path)
            if operation in self.process_view_operations:
                self._log_message(operation, request)
        except Exception, e:
            LOG.error('Could not audit the request: %s' % e)

        return None
Ejemplo n.º 10
0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from django.conf.urls import url

from desktop.lib.django_util import get_username_re_rule, get_groupname_re_rule

from useradmin import views as useradmin_views
from useradmin import api as useradmin_api


username_re = get_username_re_rule()
groupname_re = get_groupname_re_rule()


urlpatterns = [
  url(r'^$', useradmin_views.list_users, name="useradmin.views.list_users"),
  url(r'^users/?$', useradmin_views.list_users, name="useradmin.views.list_users"),
  url(r'^groups/?$', useradmin_views.list_groups, name="useradmin.views.list_groups"),
  url(r'^permissions/?$', useradmin_views.list_permissions, name="useradmin.views.list_permissions"),
  url(r'^configurations/?$', useradmin_views.list_configurations, name="useradmin.views.list_configurations"),
  url(r'^users/edit/(?P<username>%s)$' % (username_re,), useradmin_views.edit_user, name="useradmin.views.edit_user"),
  url(r'^users/add_ldap_users$', useradmin_views.add_ldap_users, name="useradmin.views.add_ldap_users"),
  url(r'^users/add_ldap_groups$', useradmin_views.add_ldap_groups, name="useradmin.views.add_ldap_groups"),
  url(r'^users/sync_ldap_users_groups$', useradmin_views.sync_ldap_users_groups, name="useradmin_views_sync_ldap_users_groups"),
  url(r'^groups/edit/(?P<name>%s)$' % (groupname_re,), useradmin_views.edit_group, name="useradmin.views.edit_group"),
  url(r'^permissions/edit/(?P<app>.+?)/(?P<priv>.+?)/?$', useradmin_views.edit_permission, name="useradmin.views.edit_permission"),
Ejemplo n.º 11
0
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from django.conf.urls.defaults import patterns, url
from desktop.lib.django_util import get_username_re_rule, get_groupname_re_rule

username_re = get_username_re_rule()
groupname_re = get_groupname_re_rule()


urlpatterns = patterns('useradmin.views',
  url(r'^$', 'list_users'),
  url(r'^users$', 'list_users'),
  url(r'^groups$', 'list_groups'),
  url(r'^permissions$', 'list_permissions'),
  url(r'^users/edit/(?P<username>%s)$' % (username_re,), 'edit_user'),
  url(r'^users/add_ldap_users$', 'add_ldap_users'),
  url(r'^users/add_ldap_groups$', 'add_ldap_groups'),
  url(r'^users/sync_ldap_users_groups$', 'sync_ldap_users_groups'),
  url(r'^groups/edit/(?P<name>%s)$' % (groupname_re,), 'edit_group'),
  url(r'^permissions/edit/(?P<app>.*)/(?P<priv>.*)$', 'edit_permission'),
  url(r'^users/new$', 'edit_user', name="useradmin.new"),
Ejemplo n.º 12
0
class UserChangeForm(django.contrib.auth.forms.UserChangeForm):
    """
  This is similar, but not quite the same as djagno.contrib.auth.forms.UserChangeForm and UserCreationForm.
  """

    GENERIC_VALIDATION_ERROR = _("Username or password is invalid.")

    username = forms.RegexField(
        label=_t("Username"),
        max_length=30,
        regex='^%s$' %
        (get_username_re_rule(), ),  # Could use UnicodeUsernameValidator()
        help_text=_t(
            "Required. 30 characters or fewer. No whitespaces or colons."),
        error_messages={'invalid': _t("Whitespaces and ':' not allowed")})

    password1 = forms.CharField(label=_t("New Password"),
                                widget=forms.PasswordInput,
                                required=False,
                                validators=hue_get_password_validators())
    password2 = forms.CharField(label=_t("Password confirmation"),
                                widget=forms.PasswordInput,
                                required=False,
                                validators=hue_get_password_validators())
    password_old = forms.CharField(label=_t("Current password"),
                                   widget=forms.PasswordInput,
                                   required=False)
    ensure_home_directory = forms.BooleanField(
        label=_t("Create home directory"),
        help_text=_t("Create home directory if one doesn't already exist."),
        initial=True,
        required=False)
    language = forms.ChoiceField(label=_t("Language Preference"),
                                 choices=LANGUAGES,
                                 required=False)
    unlock_account = forms.BooleanField(
        label=_t("Unlock Account"),
        help_text=_t("Unlock user's account for login."),
        initial=False,
        required=False)

    class Meta(django.contrib.auth.forms.UserChangeForm.Meta):
        model = User
        fields = [
            "username", "first_name", "last_name", "email",
            "ensure_home_directory"
        ]

    def __init__(self, *args, **kwargs):
        super(UserChangeForm, self).__init__(*args, **kwargs)

        if self.instance.id and 'username' in self.fields:
            self.fields['username'].widget.attrs['readonly'] = True

        if 'desktop.auth.backend.LdapBackend' in desktop_conf.AUTH.BACKEND.get(
        ):
            self.fields['password1'].widget.attrs['readonly'] = True
            self.fields['password2'].widget.attrs['readonly'] = True
            self.fields['password_old'].widget.attrs['readonly'] = True
            self.fields['first_name'].widget.attrs['readonly'] = True
            self.fields['last_name'].widget.attrs['readonly'] = True
            self.fields['email'].widget.attrs['readonly'] = True
            if 'is_active' in self.fields:
                self.fields['is_active'].widget.attrs['readonly'] = True
            if 'is_superuser' in self.fields:
                self.fields['is_superuser'].widget.attrs['readonly'] = True
            if 'unlock_account' in self.fields:
                self.fields['unlock_account'].widget.attrs['readonly'] = True
            if 'groups' in self.fields:
                self.fields['groups'].widget.attrs['readonly'] = True

        if ENABLE_ORGANIZATIONS.get():
            organization = self.instance.organization if self.instance.id else get_user_request_organization(
            )
            self.fields['groups'].choices = [
                (group.id, group.name)
                for group in organization.organizationgroup_set.all()
            ]

    def clean_username(self):
        username = self.cleaned_data["username"]
        if self.instance.username == username:
            return username
        try:
            User._default_manager.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(_("Username already exists."),
                                    code='duplicate_username')

    def clean_password(self):
        return self.cleaned_data["password"]

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1", "")
        password2 = self.cleaned_data["password2"]
        if password1 != password2:
            raise forms.ValidationError(_t("Passwords do not match."))
        return password2

    def clean_password1(self):
        password = self.cleaned_data.get("password1", "")
        if self.instance.id is None and password == "":
            raise forms.ValidationError(
                _("You must specify a password when creating a new user."))
        return self.cleaned_data.get("password1", "")

    def clean_password_old(self):
        if self.instance.id is not None:
            password1 = self.cleaned_data.get("password1", "")
            password_old = self.cleaned_data.get("password_old", "")
            if password1 != '' and not self.instance.check_password(
                    password_old):
                raise forms.ValidationError(self.GENERIC_VALIDATION_ERROR)
        return self.cleaned_data.get("password_old", "")

    def save(self, commit=True):
        """
    Update password if it's set.
    """
        user = super(UserChangeForm, self).save(commit=False)
        if self.cleaned_data["password1"]:
            user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
            # groups must be saved after the user
            self.save_m2m()
        return user
Ejemplo n.º 13
0
def validate_username(username_pattern):
  validator = re.compile(r"^%s$" % get_username_re_rule())

  assert username_pattern is not None, _('Username is required.')
  assert len(username_pattern) <= 30, _('Username must be fewer than 30 characters.')
  assert validator.match(username_pattern), _("Username must not contain whitespaces and ':'")
Ejemplo n.º 14
0
class UserChangeForm(django.contrib.auth.forms.UserChangeForm):
    """
  This is similar, but not quite the same as djagno.contrib.auth.forms.UserChangeForm
  and UserCreationForm.
  """
    username = forms.RegexField(
        label=_t("Username"),
        max_length=30,
        regex='^%s$' % (get_username_re_rule(), ),
        help_text=_t(
            "Required. 30 characters or fewer. No whitespaces or colons."),
        error_messages={'invalid': _t("Whitespaces and ':' not allowed")})

    password1 = forms.CharField(label=_t("Password"),
                                widget=forms.PasswordInput,
                                required=False,
                                validators=get_password_validators())
    password2 = forms.CharField(label=_t("Password confirmation"),
                                widget=forms.PasswordInput,
                                required=False,
                                validators=get_password_validators())
    password_old = forms.CharField(label=_t("Previous Password"),
                                   widget=forms.PasswordInput,
                                   required=False)
    ensure_home_directory = forms.BooleanField(
        label=_t("Create home directory"),
        help_text=_t("Create home directory if one doesn't already exist."),
        initial=True,
        required=False)

    class Meta(django.contrib.auth.forms.UserChangeForm.Meta):
        fields = [
            "username", "first_name", "last_name", "email",
            "ensure_home_directory"
        ]

    def __init__(self, *args, **kwargs):
        super(UserChangeForm, self).__init__(*args, **kwargs)

        if self.instance.id:
            self.fields['username'].widget.attrs['readonly'] = True

        if desktop_conf.AUTH.BACKEND.get(
        ) == 'desktop.auth.backend.LdapBackend':
            self.fields['password1'].widget.attrs['readonly'] = True
            self.fields['password2'].widget.attrs['readonly'] = True
            self.fields['password_old'].widget.attrs['readonly'] = True

    def clean_password(self):
        return self.cleaned_data["password"]

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1", "")
        password2 = self.cleaned_data["password2"]
        if password1 != password2:
            raise forms.ValidationError(_t("Passwords do not match."))
        return password2

    def clean_password1(self):
        password = self.cleaned_data.get("password1", "")
        if self.instance.id is None and password == "":
            raise forms.ValidationError(
                _("You must specify a password when creating a new user."))
        return self.cleaned_data.get("password1", "")

    def clean_password_old(self):
        if self.instance.id is not None:
            password1 = self.cleaned_data.get("password1", "")
            password_old = self.cleaned_data.get("password_old", "")
            if password1 != '' and not self.instance.check_password(
                    password_old):
                raise forms.ValidationError(
                    _("The old password does not match the current password."))
        return self.cleaned_data.get("password_old", "")

    def save(self, commit=True):
        """
    Update password if it's set.
    """
        user = super(UserChangeForm, self).save(commit=False)
        if self.cleaned_data["password1"]:
            user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
            # groups must be saved after the user
            self.save_m2m()
        return user