Example #1
0
def insert_users(user, users, group_name, pos, org, create_and_email_pw=False):
    """Inserts user into the database.  If an exception is raised, no changes
    are made to the DB.
    @param users  A string listing users, one per line, whitespace-
    separated, of the form <username> <email> <firstname> <lastname>.
    Any lines starting with # are ignored, as are blank lines.
    @param user  The user who is creating the other users
    @param group_name  The name of the group to add the users to - empty or None
    implies no group
    @param pos  An int giving the position of the new users
    @param org  An Organization to which the group and users will belong
    @exception UserSyntaxError if there is a syntax error in users
    @exception UserGroupError if a group by that name already exists
    @exception UserUserError if a user by that name already exists or there
    is an invalid username
    @exception UserPermissionError if the user creating the users doesn't have
    the right permission"""

    include_group = group_name != "" and group_name != None

    userlist = []

    # Parse the lines and add the user details to userlist; check that all the
    # usernames are valid
    lines = users.splitlines()
    for i,l in enumerate(lines):
        l = l.strip()
        if l == "" or l.startswith("#"):
            continue
        
        toks = l.split(',')
        if len(toks) != 4:
            raise UserSyntaxError("Syntax error on line %d: expected a line of "
                                  "the form <username>, <email>, <firstname>, <lastname>")
        username = toks[0].strip()
        email = toks[1].strip()
        firstname = toks[2].strip()
        lastname = toks[3].strip()
        userlist.append( (username, email, firstname, lastname) )

        # Check for valid username
        if re.match(r'^\w+$', username) is None:
            raise UserUserError("The username %s is invalid." % username)

    # Check that the group doesn't exist
    if include_group:
        try:
            _ = db.Group.objects.get(name=group_name, org=org)
        except db.Group.DoesNotExist:
            pass
        else:
            raise UserGroupError("Error: That group already exists")

    # Check that the users don't exist; put any that do in a list
    existing_users = []
    for (username, _, _, _) in userlist:
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            pass
        else:
            existing_users.append(username)
    
    # If users do already exist, format the list in a nice way and raise an error
    if len(existing_users) != 0:
        display_list = ', '.join(existing_users[0:5])
        if len(existing_users) > 5:
            display_list += ", ..."
        raise UserUserError("Error: %d user(s) already exist: %s" % (len(existing_users), display_list))

    # Check we can create users at this position and organization
    if not permissions.allowed_user_access_create(user, pos, org):
        raise UserPermissionError("Error: You do not have permission to create "
                                  " that type of user at that organization.")

    # Check that we can create groups at this organization
    if not permissions.allowed_group_access_create(user, org):
        raise UserPermissionError("Error: You do not have permission to create "
                                  " groups at that organization.")

    # Add the group to the DB
    if include_group:
        try:
            group = db.Group()
            group.name = group_name
            group.org = org
            group.save()
        except IntegrityError:
            raise UserGroupError("Error: That group already exists")

    # Add the new users to the DB, since we haven't had any errors
    for (username, email, firstname, lastname) in userlist:
        
        # Create the django user
        new_user = User.objects.create_user(username, email, None)
        print("%s %s" % (firstname, lastname))
        new_user.first_name = firstname
        new_user.last_name = lastname
        pos_group = Group.objects.get(name=db.UserProfile.GROUPS[pos])
        new_user.groups.add(pos_group)
        if include_group:
            new_user.vns_groups.add(group)

        # Make the user a superuser if necessary
        if pos == 0:
            new_user.is_staff = True
            new_user.is_superuser = True
        
        # Create the user profile
        up = db.UserProfile()
        up.user = new_user
        up.pos = pos
        up.org = org
        up.generate_and_set_new_sim_auth_key()

        new_user.save()
        up.save()

        # If they need to have an initial password, set it and email it to them
        if create_and_email_pw:
            pw = User.objects.make_random_password()
            new_user.set_password(pw)
            print("Emailing %s with password" % new_user)
            new_user.email_user("VNS Account", "The password for your new VNS "
                                "account is %s\n\nPlease log in and change "
                                "this ASAP." % pw)
            new_user.save()
Example #2
0
def group_access_check(request, callee, action, **kwargs):
    """Checks that the user can access the functions they're trying to, and
    if they can calls callee.
    @param request  An HTTP request
    @param callee  Gives the Callable to call
    @param action  One of "add", "change", "use", "delete", describing the
    permissions needed
    @param gid  The ID of the group in question; not used for
    action = "add"
    @exception ValueError  If an action is unrecognised
    @exception KeyError  If an option is missing
    @return HttpResponse"""

    def denied():
        """Generate an error message and redirect if we try do something to a
        group we're not allowed to"""
        messages.error(request, "Either this group doesn't exist or you don't "
                                "have permission to %s it." % action)
        return HttpResponseRedirect('/login/')

    def denied_add():
        """Generate an error message and redirect if we try to create a group
        and are not allowed to"""
        messages.error(request, "You don't have permission to create groups.")
        return HttpResponseRedirect('/login/')

    
    # If we're trying to add a group, don't need to get the group itself
    if action == "add":
        if permissions.allowed_group_access_create(request.user):
            return callee(request)
        else:
            return denied_add()

    else:

        # Try getting the group - if it doesn't exist, show the same message
        # as for permission denied.  If we don't have org / group name
        # arguments, django will show an internal error, which is what we want.
        gn = kwargs['gn']
        on = kwargs['on']
        try :
            group = db.Group.objects.get(org__name=on, name=gn)
        except db.Group.DoesNotExist:
            return denied()

        if action == "use":
            if permissions.allowed_group_access_use(request.user, group):
                 return callee(request, group=group, **kwargs)
            else:
                return denied()
        elif action == "change":
            if permissions.allowed_group_access_change(request.user, group):
                return callee(request, group=group, **kwargs)
            else:
                return denied()
        elif action == "delete":
            if permissions.allowed_group_access_delete(request.user, group):
                return callee(request, group=group, **kwargs)
            else:
                return denied()
        else:
            raise ValueError("Unknown action: %s" % options["action"])
Example #3
0
File: models.py Project: smbz/vns
 def can_create_group(self):
     return permissions.allowed_group_access_create(self.user)