def post(self, request, largs, name, dry=False): """ Create a new property. """ if not request.user.has_perm('Users.prop_create'): return HttpResponseForbidden() # If AssertionError: 400 Bad Request key, value = self._parse_post(request) if not resource_validator(key): raise PreconditionFailed("Property contains invalid characters") # If UserNotFound: 404 Not Found user = user_backend.get(username=name) # If PropertyExists: 409 Conflict key, value = property_backend.create(user=user, key=key, value=value, dry=dry) self.log.info('Created property "%s" as "%s"', key, value, extra=largs) return HttpResponseCreated(request, 'users.user.props.prop', name=name, subname=key)
def put(self, request, largs, name, subname): """ Set value of a single property. """ if not request.user.has_perm('Users.prop_set'): return HttpResponseForbidden() # If BadRequest: 400 Bad Request value = self._parse_put(request) # If UserNotFound: 404 Not Found user = user_backend.get(username=name) key, old_value = property_backend.set(user=user, key=subname, value=value) if old_value is None: # new property self.log.info('Set to "%s"', value, extra=largs) return HttpResponseCreated(request, 'users.user.props.prop', name=name, subname=key) else: # existing property self.log.info('Changed from "%s" to "%s"', old_value, value, extra=largs) return HttpRestAuthResponse(request, old_value)
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
def delete(self, request, largs, name, subname): """ Delete a property. """ if not request.user.has_perm('Users.prop_delete'): return HttpResponseForbidden() # If UserNotFound: 404 Not Found user = user_backend.get(username=name) property_backend.remove(user=user, key=subname) return HttpResponseNoContent()
def get(self, request, largs, name): """ Get all properties of a user. """ if not request.user.has_perm('Users.props_list'): return HttpResponseForbidden() # If UserNotFound: 404 Not Found user = user_backend.get(username=name) props = property_backend.list(user=user) return HttpRestAuthResponse(request, props)
def get(self, request, largs, name, subname): """ Get value of a single property. """ if not request.user.has_perm('Users.prop_get'): return HttpResponseForbidden() # If UserNotFound: 404 Not Found user = user_backend.get(username=name) value = property_backend.get(user=user, key=subname) return HttpRestAuthResponse(request, value)
def delete(self, request, largs, name, subname): """ Remove a user from a group. """ if not request.user.has_perm('Groups.group_remove_user'): return HttpResponseForbidden() # If GroupNotFound: 404 Not Found group = group_backend.get(service=request.user, name=name) # If UserNotFound: 404 Not Found user = user_backend.get(username=subname) group_backend.rm_user(group=group, user=user) self.log.info('Remove user from group', extra=largs) return HttpResponseNoContent()
def put(self, request, largs, name): """ Set multiple properties. """ if not request.user.has_perm('Users.prop_create'): return HttpResponseForbidden() # If UserNotFound: 404 Not Found user = user_backend.get(username=name) properties = parse_dict(request) for key in six.iterkeys(properties): if not resource_validator(key): raise PreconditionFailed( "Property contains invalid characters") property_backend.set_multiple(user=user, props=properties) return HttpResponseNoContent()
def get(self, request, largs, name, subname): """ Verify that a user is in a group. """ if not request.user.has_perm('Groups.group_user_in_group'): return HttpResponseForbidden() # If GroupNotFound: 404 Not Found group = group_backend.get(service=request.user, name=name) # If UserNotFound: 404 Not Found user = user_backend.get(username=subname) if group_backend.is_member(group=group, user=user): return HttpResponseNoContent() else: raise UserNotFound(subname) # 404 Not Found
def get(self, request, largs): """Get a list of groups or, if called with the 'user' query parameter, a list of groups where the user is a member of.""" username = request.GET.get('user', None) if username is None or username == '': if not request.user.has_perm('Groups.groups_list'): return HttpResponseForbidden() groups = group_backend.list(service=request.user) else: if not request.user.has_perm('Groups.groups_for_user'): return HttpResponseForbidden() # Get all groups of a user user = user_backend.get(username=username.lower()) groups = group_backend.list(service=request.user, user=user) groups = [g.lower() for g in groups] return HttpRestAuthResponse(request, groups)
def post(self, request, largs, name): """ Add a user to a group. """ if not request.user.has_perm('Groups.group_add_user'): return HttpResponseForbidden() # If BadRequest: 400 Bad Request username = self._parse_post(request).lower() # If GroupNotFound: 404 Not Found group = group_backend.get(service=request.user, name=name) # If UserNotFound: 404 Not Found user = user_backend.get(username=username) group_backend.add_user(group=group, user=user) self.log.info('Add user "%s"', username, extra=largs) return HttpResponseNoContent()
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)
def save_groups(groups, args, parser): if groups: print("Groups:") subgroups = {} for name, data in six.iteritems(groups): service = data.pop('service', None) if service: service = Service.objects.get(username=service) try: group = group_backend.create(service=service, name=name) print("* %s: created." % name) except GroupExists: if args.skip_existing_groups: print("* %s: Already exists, skipping." % name) continue else: print("* %s: Already exists, adding memberships." % name) group = group_backend.get(service=service, name=name) for username in data.get('users', []): user = user_backend.get(username=username) group_backend.add_user(group=group, user=user) if 'subgroups' in data: subgroups[group] = data.pop('subgroups') # add group-memberships *after* we created all groups to make sure # groups already exist. for group, subgroups_data in six.iteritems(subgroups): for subgroup_data in subgroups_data: name = subgroup_data['name'] service = subgroup_data.get('service') if service: service = Service.objects.get(username=service) subgroup = group_backend.get(name=name, service=service) group_backend.add_subgroup(group=group, subgroup=subgroup)