def save_users(users, args, parser):
    properties = defaultdict(dict)
    if users:
        print('Users:')
    for username, data in six.iteritems(users):
        username = username.lower()

        try:
            user = user_backend.create(username=username,
                                       property_backend=property_backend)
            created = True
        except UserExists:
            user = user_backend.get(username=username)
            created = False

        if not created and args.skip_existing_users:
            continue

        # handle password:
        if 'password' in data and (created or args.overwrite_passwords):
            pwd = data['password']
            if isinstance(pwd, six.string_types):
                user_backend.set_password(username=username, password=pwd)
                print('* %s: Set password from input data.' % username)
            elif isinstance(pwd, dict):
                try:
                    user_backend.set_password_hash(username=username, **pwd)
                    print('* %s: Set hash from input data.' % username)
                except ValueError:
                    print(
                        '* %s: Hash of type "%s" is not supported, skipping.' %
                        (username, pwd['algorithm']))
            else:
                raise TypeError("password is of type %s" % type(pwd).__name__)
        elif created and args.gen_passwords:
            raw_passwd = Service.objects.make_random_password(length=16)
            user_backend.set_password(username=username, password=raw_passwd)
            print('* %s: Generated password: %s' % (username, raw_passwd))

        # handle all other preferences
        for key, value in six.iteritems(data.get('properties', {})):
            if key in TIMESTAMP_PROPS:
                if isinstance(value, (int, float)):
                    value = datetime.fromtimestamp(value)
                else:  # parse time, to ensure correct format
                    value = datetime.strptime(value, TIMESTAMP_FORMAT)
                value = datetime.strftime(value, TIMESTAMP_FORMAT)

                # if the user was created, remove the 'date joined' prop, if we
                # find it in the passed properties
                if key == 'date joined' and created:
                    property_backend.remove(user, key)

            properties[user][key] = value
    return properties
Beispiel #2
0
    def __call__(self, parser, namespace, value, option_string):
        username = value.lower()
        if not six.PY3:  # pragma: no branch, pragma: py2
            username = username.decode('utf-8')

        if namespace.create_user:
            if not resource_validator(username):
                raise ArgumentError(self, "Username contains invalid characters")

            try:
                validate_username(username)
                user = user_backend.create(username=username, property_backend=property_backend)
            except UserExists:
                raise ArgumentError(self, 'User already exists.')
            except PreconditionFailed as e:
                raise ArgumentError(self, e)
        else:
            try:
                user = user_backend.get(username=username)
            except UserNotFound:
                raise ArgumentError(self, 'User does not exist.')
        setattr(namespace, self.dest, user)
Beispiel #3
0
    def post(self, request, largs, dry=False):
        """Create a new user."""

        if not request.user.has_perm('Users.user_create'):
            return HttpResponseForbidden()

        name, password, properties = self._parse_post(request)
        name = name.lower()

        # check username:
        if not resource_validator(name):
            raise PreconditionFailed("Username contains invalid characters")
        # If UsernameInvalid: 412 Precondition Failed
        validate_username(name)

        # check password:
        if password is not None and password != '':
            if len(password) < settings.MIN_PASSWORD_LENGTH:
                raise PasswordInvalid("Password too short")

        # check properties:
        if properties is not None:
            for key in six.iterkeys(properties):
                if not resource_validator(key):
                    raise PreconditionFailed(
                        "Property contains invalid characters")

        # If ResourceExists: 409 Conflict
        # If PasswordInvalid: 412 Precondition Failed
        user = user_backend.create(username=name,
                                   password=password,
                                   properties=properties,
                                   property_backend=property_backend,
                                   dry=dry)

        self.log.info('%s: Created user', user.username, extra=largs)
        return HttpResponseCreated(request, 'users.user', name=user.username)
Beispiel #4
0
 def create_user(self, username, password=None):
     return user_backend.create(username=username,
                                password=password,
                                property_backend=property_backend)