def user_access_check(request, callee, action, **kwargs): """Checks that the user can access the functions they're trying to, and if they can calls callee""" """Check that the user is allowed access, and if they are call the given Callable. @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 user_id The ID of the user in question; not used for action = "add" @exception ValueError If an action is unrecognised @exception KeyError If an option is missing""" def denied(): """Generate an error message and redirect if we try do something to a template we're not allowed to""" messages.error(request, "Either this user doesn't exist or you don't " "have permission to %s it." % action) return HttpResponseRedirect('/') def denied_add(): """Generate an error message and redirect if we try to create a template and are not allowed to""" messages.error(request, "You don't have permission to create users.") return HttpResponseRedirect('/') # If we're trying to add a template, don't need to get the template itself if action == "add": if permissions.allowed_user_access_create(request.user): return callee(request) else: return denied_add() else: # Try getting the template - if it doesn't exist, show the same message # as for permission denied user_name = kwargs["un"] try : user = User.objects.get(username=user_name) except User.DoesNotExist: return denied() if action == "use": if permissions.allowed_user_access_use(request.user, user): return callee(request, user.get_profile()) else: return denied() elif action == "change": if permissions.allowed_user_access_change(request.user, user): return callee(request, user.get_profile()) else: return denied() elif action == "delete": if permissions.allowed_user_access_delete(request.user, user): return callee(request, user.get_profile()) else: return denied() else: raise ValueError("Unknown action: %s" % options["action"])
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()
def user_create(request): tn = 'vns/user_create.html' RegistrationForm = make_registration_form(request.user) if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): try: # Get the form data username = form.cleaned_data['username'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] email = form.cleaned_data['email'] pw = form.cleaned_data['pw'] pw_method = form.cleaned_data['pw_method'] pos = form.cleaned_data['pos'] pos = int(pos) # If we've been given an organization, use that org; otherwise # use the org of the user who's creating the new user try: org_name = form.cleaned_data['org'] org = db.Organization.objects.get(name=org_name) except KeyError: org = request.user.get_profile().org # Check that we're allowed to create a user with this position/organization if not permissions.allowed_user_access_create(request.user, pos, org): messages.error(request, "You cannot create this user") return HttpResponseRedirect('/user/create') # Work out what password to set if pw_method == "email": pw = User.objects.make_random_password() elif pw_method == "raven": pw = None # Try to create the user try: user = User.objects.create_user(username, email, pw) except IntegrityError: messages.error(request, "Unable to create the user: the requested username '%s' is already taken" % username) return direct_to_template(request, tn, { 'form': form }) user.last_name = last_name user.first_name = first_name user.groups.add(Group.objects.get(name=db.UserProfile.GROUPS[pos])) # Create the user profile up = db.UserProfile() up.user = user up.pos = pos up.org = org up.generate_and_set_new_sim_auth_key() # See if we need to create a superuser if (up.pos == 0): user.is_staff = True user.is_superuser = True # Save everything user.save() up.save() # Email the user their password, if necessary if pw_method == "email": user.email_user("VNS Account", "The password for your " "new VNS account is %s\n\nPlease log " "in and change this ASAP." % pw) messages.success(request, "Successfully created new user: %s" % username) return HttpResponseRedirect('/user/%s/' % username) except: # Unknown exception, probably the database isn't set up correctly try: user.delete() except: # Give up trying to do anything pass # Re-raise the error, so we can see what's going on in debug mode raise else: messages.error(request, "Invalid form") return direct_to_template(request, tn, {'form':form}) else: form = RegistrationForm() return direct_to_template(request, tn, { 'form': form })
def can_create_user(self): return permissions.allowed_user_access_create(self.user)