Beispiel #1
0
    def test_existing_properties(self):
        backend.create_user(username2)
        backend.create_property(user=username2, key=propkey1, value=propval3)  # propval1 -> json
        backend.create_property(user=username2, key="date joined", value=propval3)

        path = os.path.join(self.base, 'users1.json')
        with capture() as (stdout, stderr):
            restauth_import([path])
            self.assertCountEqual(backend.list_users(), [username1, username2, username3])

            pattern = r'^%s: Property "%s" already exists\.$' % (username2, propkey1)
            self.assertHasLine(stdout, pattern)
            self.assertHasLine(stdout, r'^%s: Property "date joined" already exists\.$' % username2)

            expected_props = {
                propkey1: propval3,  # propva1 is in json-file - we don't overwrite!
                propkey2: propval2,
                u'last login': u'2013-12-01 19:27:44',  # date from json file
            }

            props = backend.get_properties(user=username2)
            # delete 'date joined' prop because it was created by the backend and
            # restauth-import doesn't overwrite in this invocation:
            del props['date joined']

            self.assertEqual(props, expected_props)
Beispiel #2
0
    def test_skip_existing_users(self):
        backend.create_user(username2)
        backend.set_property(user=username2, key=propkey1, value=propval3)
        backend.set_property(user=username2, key="date joined", value=propval3)

        path = os.path.join(self.base, 'users1.json')
        with capture() as (stdout, stderr):
            restauth_import(['--skip-existing-users', path])
        self.assertProperties(username2, {propkey1: propval3, })
Beispiel #3
0
    def test_skip_existing_groups(self):
        # same test-setup as above, only we skip existing groups
        backend.create_user(username1)
        backend.create_user(username2)
        backend.create_user(username3)
        backend.create_user(username4)  # new user

        # this group already exists and has some memberships
        backend.create_group(group=groupname2, service=self.service)
        backend.add_member(group=groupname2, service=self.service, user=username1)
        backend.add_member(group=groupname2, service=self.service, user=username4)

        path = os.path.join(self.base, 'groups1.json')
        with capture() as (stdout, stderr):
            try:
                restauth_import(['--skip-existing-groups', path])
            except SystemExit:
                self.fail(stderr.getvalue())
            self.assertHasLine(stdout, r'^Groups:$')
            self.assertHasLine(stdout, r'^\* %s: created\.$' % groupname1)
            self.assertHasLine(stdout, r'^\* %s: Already exists, skipping\.$' % groupname2)
            self.assertHasLine(stdout, r'^\* %s: created\.$' % groupname3)
            self.assertHasLine(stdout, r'^\* %s: created\.$' % groupname4)

        # test memberships
        self.assertCountEqual(backend.members(group=groupname1, service=None), [])
        self.assertCountEqual(backend.members(group=groupname2, service=self.service), [username1, username4])

        # group3 now is not a subgroup, because group2 already existed and we skipped its data
        self.assertEqual(backend.members(group=groupname3, service=self.service), [username3])
        self.assertEqual(backend.members(group=groupname4, service=None), [])
Beispiel #4
0
    def test_existing_groups(self):
        backend.create_user(username1)
        backend.create_user(username2)
        backend.create_user(username3)
        backend.create_user(username4)  # new user

        # this group already exists and has some memberships
        backend.create_group(group=groupname2, service=self.service)
        backend.add_member(group=groupname2, service=self.service, user=username1)
        backend.add_member(group=groupname2, service=self.service, user=username4)

        path = os.path.join(self.base, 'groups1.json')
        with capture() as (stdout, stderr):
            restauth_import([path])
            self.assertEqual(stderr.getvalue(), '')
            self.assertHasLine(stdout, r'^Groups:$')
            self.assertHasLine(stdout, r'^\* %s: created\.$' % groupname1)
            self.assertHasLine(stdout, r'^\* %s: Already exists, adding memberships\.$' % groupname2)
            self.assertHasLine(stdout, r'^\* %s: created\.$' % groupname3)
            self.assertHasLine(stdout, r'^\* %s: created\.$' % groupname4)

        # test memberships
        self.assertCountEqual(backend.members(group=groupname1, service=None), [])
        self.assertCountEqual(backend.members(group=groupname2, service=self.service),
                              [username1, username2, username4])
        if backend.SUPPORTS_SUBGROUPS is True:
            self.assertCountEqual(backend.members(group=groupname3, service=self.service),
                                  [username1, username2, username3, username4])
            self.assertCountEqual(backend.members(group=groupname4, service=None),
                                  [username1, username2, username4])
        else:
            self.assertCountEqual(backend.members(group=groupname3, service=self.service),
                                  [username3])
            self.assertCountEqual(backend.members(group=groupname4, service=None), [])
def save_users(users, args, parser):
    properties = defaultdict(dict)
    if users:
        print('Users:')
    for username, data in six.iteritems(users):
        username = username.lower()

        try:
            backend.create_user(user=username)
            created = True
        except UserExists:
            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):
                backend.set_password(user=username, password=pwd)
                print('* %s: Set password from input data.' % username)
            elif isinstance(pwd, dict):
                try:
                    backend.set_password_hash(user=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)
            backend.set_password(user=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)

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

        if namespace.create_user:
            try:
                user = stringcheck(user)
            except PreconditionFailed:
                raise ArgumentError(self, "Username contains invalid characters")

            try:
                validate_username(user)
                backend.create_user(user=user)
            except UserExists:
                raise ArgumentError(self, 'User already exists.')
            except PreconditionFailed as e:
                raise ArgumentError(self, e)

        setattr(namespace, self.dest, user)
Beispiel #7
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, groups = self._parse_post(request)
        name = stringcheck(name)

        # If UsernameInvalid: 412 Precondition Failed
        validate_username(name)

        # check password:
        if password:
            if len(password) < settings.MIN_PASSWORD_LENGTH:
                # If PasswordInvalid: 412 Precondition Failed
                raise PasswordInvalid("Password too short")
        else:
            password = None

        # normalize properties, add date-joined if not present
        if properties is None:
            properties = {
                'date joined': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            }
        else:
            properties = {stringcheck(k): v for k, v in six.iteritems(properties)}
            if 'date joined' not in properties:
                properties['date joined'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # normalize groups
        if groups:
            groups = [(stringcheck(g), request.user) for g in groups]

        # If UserExists: 409 Conflict
        backend.create_user(user=name, password=password, properties=properties, groups=groups,
                            dry=dry)
        self.log.info('%s: Created user', name, extra=largs)

        return HttpResponseCreated()
Beispiel #8
0
    def test_groups(self):
        backend.create_user(username1)
        backend.create_user(username2)
        backend.create_user(username3)

        path = os.path.join(self.base, 'groups1.json')
        with capture() as (stdout, stderr):
            restauth_import([path])
            self.assertHasLine(stdout, '^Groups:$')
            self.assertHasLine(stdout, '^\* %s: created\.$' % groupname1)
            self.assertHasLine(stdout, '^\* %s: created\.$' % groupname2)
            self.assertHasLine(stdout, '^\* %s: created\.$' % groupname3)
            self.assertHasLine(stdout, '^\* %s: created\.$' % groupname4)

        # test memberships
        self.assertCountEqual(backend.members(group=groupname1,  service=None), [])
        self.assertCountEqual(backend.members(group=groupname2,  service=self.service),
                              [username1, username2])
        if backend.SUPPORTS_SUBGROUPS is True:
            self.assertCountEqual(backend.members(group=groupname3,  service=self.service),
                                  [username1, username2, username3])
            self.assertCountEqual(backend.members(group=groupname4,  service=None),
                                  [username1, username2])
        else:
            self.assertCountEqual(backend.members(group=groupname3,  service=self.service),
                                  [username3])
            self.assertCountEqual(backend.members(group=groupname4,  service=None), [])
Beispiel #9
0
 def create_user(self, username, password=None):
     backend.create_user(user=username, password=password, properties={
         'date joined': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
     })