def groups(): '''sets up the groups''' groupnames=[ {'n':'Principal', 'p':None}, {'n':'Bursar', 'p':None}, {'n':'Dean(Residence)', 'p':None}, {'n':'Dean(Academic Affairs)', 'p':None}, {'n':'Chaplain', 'p':None}, {'n':'Public Information Officer', 'p':None}, {'n':'Special Assignments', 'p':None}, {'n':'Administration', 'p':None}, {'n':'Staff Advisor', 'p':None}, {'n':'Faculty', 'p':None}, {'n':'Students', 'p':None}] for i in groupnames: a=Group() a.name=i['n'] a.save()
def write_contacts(): global contacts global allgroups for group in allgroups : grp = None try: grp = Group.objects.get(name=group) except : pass if not grp : grp = Group() grp.name = group grp.save() for contact in contacts : user = None try: user = User.objects.get(username=contact['email']) except : pass if not user : user = User() user.username = contact['email'] user.email = contact['email'] user.is_active = False user.last_name = contact['family_name'] user.first_name = contact['given_name'] user.save() for grp in contact['groups']: g = Group.objects.get(name=grp) g.user_set.add(user) user.save()
def create_group(gname): if Group.objects.filter(name=gname): print " group exists for %s" % gname return g = Group(name=gname) g.save() print " created group %s" % gname
def testGetScenariosUserDoesntHavePermission(self): # If the user doesn't have the required permission, an empty # queryset is returned. scenario = ScenarioF.create(status_cache=Scenario.STATUS_APPROVED) project = ProjectF.create() scenario.set_project(project) scenarioproject = ScenarioProject.objects.get(scenario=scenario, project=project) scenarioproject.approved = True scenarioproject.save() user, _ = User.objects.get_or_create(username="******") group = Group() group.save() user.groups.add(group) group.projectgrouppermission_set.add( ProjectGroupPermission(group=group, project=project, permission=UserPermission.PERMISSION_SCENARIO_VIEW) ) pm = permission_manager.UserPermissionManager(user) self.assertFalse(pm.check_permission(UserPermission.PERMISSION_SCENARIO_VIEW)) self.assertEquals(0, len(pm.get_scenarios())) user.userpermission_set.add(UserPermission(permission=UserPermission.PERMISSION_SCENARIO_VIEW, user=user)) self.assertTrue(pm.check_permission(UserPermission.PERMISSION_SCENARIO_VIEW)) self.assertEquals(1, len(pm.get_scenarios()))
def create_profile(self, user, person, project, record_type, already_activated=False): salt = hashlib.sha1(str(random.random())).hexdigest()[:5] username = user.username if isinstance(username, unicode): username = username.encode('utf-8') if already_activated: activation_key = "ALREADY_ACTIVATED" else: activation_key = hashlib.sha1(salt+username).hexdigest() create_user = self.create(user=user,activation_key=activation_key, person = person, project=project, record_type = record_type ) if already_activated: user.is_active = True user.is_staff = True user.save() from django.contrib.auth.models import Group try: g = Group.objects.get(name=record_type.clas) except: g = Group(name=record_type.clas) g.save() g.user_set.add(user) return create_user
def setUp(self): self.accounts = [('user1', 'pwd1', 'useronefirstname', 'useronelastname'), ('user2', 'pwd2', 'usertwofirstname', 'usertwolastname'), ('user3', 'pwd3', 'userthreefirstname', 'userthreelastname')] for (uname, pwd, first, last) in self.accounts: user = User.objects.create_user(uname, '', pwd) user.first_name = first user.last_name = last user.save() profile = UserProfile(user=user, isDjangoAccount=True) profile.save() self.users = User.objects.all() self.client = Client() login = self.client.login(username=self.accounts[0][0], password=self.accounts[0][1]) self.assertTrue(login) self.groups = ['group1', 'group2', 'group3', 'group4'] for groupname in self.groups: group = Group(name=groupname) group.save()
def testGetScenariosPermissionScenarioView(self): user, _ = User.objects.get_or_create(username="******") group = Group() group.save() user.groups.add(group) user.userpermission_set.add(UserPermission(permission=UserPermission.PERMISSION_SCENARIO_VIEW, user=user)) project = ProjectF.create() # User can only see approved scenarios scenario = ScenarioF.create(status_cache=Scenario.STATUS_APPROVED) scenario.set_project(project) scenarioproject = ScenarioProject.objects.get(scenario=scenario, project=project) scenarioproject.approved = True scenarioproject.save() # So can't see this one scenario2 = ScenarioF.create(status_cache=Scenario.STATUS_WAITING) scenario2.set_project(project) group.projectgrouppermission_set.add( ProjectGroupPermission(group=group, project=project, permission=UserPermission.PERMISSION_SCENARIO_VIEW) ) pm = permission_manager.UserPermissionManager(user) self.assertTrue(pm.check_permission(UserPermission.PERMISSION_SCENARIO_VIEW)) scenarios = pm.get_scenarios() self.assertEquals(len(scenarios), 1) self.assertEquals(scenarios[0].id, scenario.id)
def user_add_group(user, group_name): group = get_object_or_none(Group, name=group_name) if not group: group = Group(name=group_name) group.save() group.user_set.add(user) return True
def add_course(stg, fcg): """ Look up the student and faculty WIND affils for a course. If they don't exist, create them. Add the default social work school faculty to the affils.""" default_faculty = User.objects.filter( username__in=settings.DEFAULT_SOCIALWORK_FACULTY_UNIS) already_existing_student_affils = Group.objects.filter(name__icontains=stg) already_existing_faculty_affils = Group.objects.filter(name__icontains=fcg) ##################### # FACULTY AFFILS: if not already_existing_faculty_affils: new_faculty_affil = Group(name=fcg) new_faculty_affil.save() else: # Faculty affil already exists. new_faculty_affil = already_existing_faculty_affils[0] ##################### # STUDENT AFFILS: if not already_existing_student_affils: new_student_affil = Group(name=stg) new_student_affil.save() else: # Student affil already exists. new_student_affil = already_existing_student_affils[0] ##################### for instructor in default_faculty: new_student_affil.user_set.add(instructor) new_student_affil.save() new_faculty_affil.user_set.add(instructor) new_faculty_affil.save() instructor.save()
class MyTardisResourceTestCase(ResourceTestCase): ''' abstract class without tests to combine common settings in one place ''' def setUp(self): super(MyTardisResourceTestCase, self).setUp() self.username = '******' self.password = '******' self.user = User.objects.create_user(username=self.username, password=self.password) test_auth_service = AuthService() test_auth_service._set_user_from_dict( self.user, user_dict={'first_name': 'Testing', 'last_name': 'MyTardis API', 'email': '*****@*****.**'}, auth_method="None") self.user_profile = UserProfile(user=self.user).save() self.testgroup = Group(name="Test Group") self.testgroup.save() self.testgroup.user_set.add(self.user) self.testfacility = Facility(name="Test Facility", manager_group=self.testgroup) self.testfacility.save() self.testinstrument = Instrument(name="Test Instrument", facility=self.testfacility) self.testinstrument.save() def get_credentials(self): return self.create_basic(username=self.username, password=self.password) def get_apikey_credentials(self): return self.create_apikey(username=self.username, api_key=self.user.api_key.key)
def create_product_group(self, sender, created, **kwargs): if created: group = Group(name='ppg@{}'.format(instance.id)) group.save() self.first_owner.groups.add(group) #???????? self.product_group = group self.save()
def newregister(request): get_authcode = lambda randcode: md5(settings.SECRET_KEY + randcode).hexdigest() get_randcode = lambda: md5(str(getrandbits(64))).hexdigest() error = "" if request.method == "POST": form = NewRegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data['saname'] password = form.cleaned_data['password1'] email = form.cleaned_data['email'] authcode = get_authcode(form.cleaned_data['randcode']) error = None randcode = form.cleaned_data['randcode'] if settings.REGISTER_SA_VERIFICATION: try: profile = SAProfile(username) except URLError: error = "Couldn't find your profile. Check you haven't made a typo and that SA isn't down." if LIVE: try: if len(UserProfile.objects.filter(sa_id=profile.get_id())) > 0: error = "You appear to have already registered with this SA account" except IDNotFoundError: error = "Your SA ID could not be found. Please contact Jonnty" if not profile.has_authcode(authcode): error = "Verification code not found on your profile." if len(User.objects.filter(username__iexact=username)): error = "This username has already been taken. Please contact Jonnty to get a different one." if error is None: user = User.objects.create_user(username=username, email=email, password=password) try: g = Group.objects.get(name="Listener") except Group.DoesNotExist: g = Group(name="Listener") g.save() [g.permissions.add(Permission.objects.get(codename=s)) for s in permissions] g.save() user.groups.add(g) user.save() up = UserProfile(user=user) if LIVE: up.sa_id = profile.get_id() up.save() return HttpResponseRedirect(reverse(django.contrib.auth.views.login)) else: randcode = request.POST['randcode'] else: randcode = get_randcode() form = NewRegisterForm(initial={'randcode': randcode}) authcode = get_authcode(randcode) return render_to_response('register.html', {'form': form, 'authcode': authcode, 'error':error}, context_instance=RequestContext(request))
class RestfulAuthPasswordResetRequestTestCase(TestCase): def setUp(self): self.bronze = Group(name='Bronze') self.bronze.save() self.silver = Group(name='Silver') self.silver.save() self.user = User.objects.create_user('test',email='*****@*****.**',password='******',first_name='Joe',last_name='Bloggs') self.correct_details = { 'username':'******', } self.client = APIClient() def tearDown(self): Group.objects.all().delete() User.objects.all().delete() self.client = None def test_valid_reset_request(self): """Check a password reset email is sent provided all data is entered correctly""" response = self.client.post('/password_reset/',self.correct_details,format='json') self.assertEqual(response.status_code,status.HTTP_201_CREATED) self.assertEqual(len(mail.outbox),1) def test_reset_request_username_missing(self): """Check reset fails if the username is not recognised. Should report this error.""" self.correct_details.pop('username') response = self.client.post('/password_reset/',self.correct_details,format='json') data = json.loads(response.content) self.assertEqual(response.status_code,status.HTTP_401_UNAUTHORIZED) self.assertTrue('username' in data) # Check for error message self.assertEqual(len(mail.outbox),0)
def setUp(self): models.client.GanetiRapiClient = RapiProxy vm, cluster = self.create_virtual_machine() context = {} self.create_standard_users(context) self.create_users([ ('user',{'id':69}), ('user1',{'id':88}), ('vm_admin',{'id':77}), ('vm_modify',{'id':75}), ('cluster_migrate',{'id':78}), ('cluster_admin',{'id':99}), ], context) globals().update(context) vm_admin.grant('admin', vm) vm_modify.grant('modify', vm) cluster_migrate.grant('migrate', cluster) cluster_admin.grant('admin', cluster) group = Group(id=42, name='testing_group') group.save() # XXX ensure namespaces for this module and child classes are updated context['c'] = Client() context['group'] = group context['vm'] = vm context['cluster'] = cluster globals().update(context) self.context.update(context)
def forwards(self, orm): if not db.dry_run: # some object classes can only be seen by root, like all users for # instance. Add the new object class RegistrationRequest to the group # which all project admins are part of, so they don't get a 403 forbidden # when trying to see requests for their project try: projectadmins = Group.objects.get(name="projectadmins") except Group.DoesNotExist as e: projectadmins = Group(name="projectadmins") # TODO add permissions for all comicmodels and registrationRequest projectadmins.save() # my god spent 2 hours on this line. But this fixes any issues with # default permissions for registrationrequest not being found.. db.send_pending_create_signals() # each user in comic is part of this group projectadmins. With the # permission in this group you can determine which types of objects # regular adins can see and edit in the admin interface. self.add_standard_perms("comicmodels", "registrationrequest", projectadmins) self.add_standard_perms("comicmodels", "comicsite", projectadmins) self.add_standard_perms("comicmodels", "page", projectadmins)
def setUpAuth(self): self.user_ctype = ContentType.objects.get_for_model(User) self.group_ctype = ContentType.objects.get_for_model(Group) User.objects.all().delete() self.abe = User(username='******', email='*****@*****.**') self.jack = User(username='******', email='*****@*****.**') self.james = User(username='******', email='*****@*****.**') self.john = User(username='******', email='*****@*****.**') self.elton = User(username='******', email='*****@*****.**', pk=10) self.abe.save() self.jack.save() self.james.save() self.john.save() Group.objects.all().delete() self.rockers = Group(name='rockers') self.bluesmen = Group(name='bluesmen') self.jazzmen = Group(name='jazzmen') self.emos = Group(name='emos', pk=10) self.rockers.save() self.bluesmen.save() self.jazzmen.save() self.emos.save()
def make_group(**kwargs): i = get_next_id() defaults = {'name': 'group{}'.format(i)} defaults.update(**kwargs) obj = Group(**defaults) obj.save() return obj
def setUp(self): g = Group(name='h') g.save() c = Cred(title='testcred', password='******', group=g) c.save() d = Cred(title='todelete', password='******', group=g) d.save() d.delete() u = User(username='******') u.save() u.groups.add(g) u.save() f = User(username='******') f.save() s = User(username='******', is_staff=True) s.save() s.groups.add(g) s.save() self.c = c self.d = d self.u = u self.f = f self.s = s
def add_event_editor(self): group_permissions = [ { 'name': 'Event editor', 'permissions': ['add_event', 'change_event'] }, { 'name': 'Event admin', 'permissions': ['add_event', 'change_event', 'delete_event', 'delete_registration'] }, { 'name': 'Registration editor', 'permissions': ['add_registration', 'change_registration'] }, ] for group_permission in group_permissions: try: group = Group.objects.get(name=group_permission.get('name')) except Group.DoesNotExist: group = Group(name=group_permission.get('name')) group.save() for permission_name in group_permission.get('permissions'): try: permission = Permission.objects.get(codename=permission_name) group.permissions.add(permission) except Permission.DoesNotExist, e: raise e except Group.DoesNotExist, e: raise e
def setUpAuth(self): self.user_ctype = ContentType.objects.get_for_model(User) self.group_ctype = ContentType.objects.get_for_model(Group) User.objects.all().delete() self.abe = User(username="******", email="*****@*****.**") self.jack = User(username="******", email="*****@*****.**") self.james = User(username="******", email="*****@*****.**") self.john = User(username="******", email="*****@*****.**") self.elton = User(username="******", email="*****@*****.**", pk=10) self.abe.save() self.jack.save() self.james.save() self.john.save() Group.objects.all().delete() self.rockers = Group(name="rockers") self.bluesmen = Group(name="bluesmen") self.jazzmen = Group(name="jazzmen") self.emos = Group(name="emos", pk=10) self.rockers.save() self.bluesmen.save() self.jazzmen.save() self.emos.save()
def handle(self, *args, **options): try: importGroup = Group.objects.get(name__exact='Imported Users') except ObjectDoesNotExist, e: importGroup = Group() importGroup.name = 'Imported Users' importGroup.save()
def allGroup(request): newgroupname=request.POST.get('newGroup', '') note=request.POST.get('note', '') #me=userQuerySet.get(username=request.user.username) me=request.user if newgroupname: groupQuerySet=Group.objects.all() newGroup=Group(groupName=newgroupname, note=note) newGroup.memberList.add(me) newGroup.save() os.makedirs('media/'+newgroupname+'/') #me=userQuerySet.get(username=request.user.username) #newGroup.usergroup_set.add(me) me.group_set.add(newGroup) #newGroup.save() me.save() joinGroupName=request.POST.get('join', '') if joinGroupName: groupQuerySet=Group.objects.all() joinGroup=groupQuerySet.get(groupName=joinGroupName) #me=userQuerySet.get(uername=request.user.username) me.group_set.add(joinGroup) me.save() myGroup=me.group_set return render_to_reponse('group.html', {'username': request.user.username, 'allGroup': Group.objects.all(), 'myGroup': myGroup})
def create_group(request): if request.method == "POST": form_group_name = GroupNameHandlerForm(request.POST) form_group_description = GroupDescriptionHandlerForm(request.POST) if form_group_name.is_valid() and form_group_description.is_valid(): # create group group_name = form_group_name.cleaned_data["group_name"] group_description = form_group_description.cleaned_data["group_description"] # group name must be unique! # use user name + created time as group name unique_group_name = "".join(("[real]", request.user.username, unicode(datetime.now()))) group = Group(name=unique_group_name) group.save() # create related group info to handle group information group_info = GroupInfo(name=group_name, description=group_description, group=group, owner=request.user) group_info.save() # add user to group manager group_info.manager.add(request.user) # relate user to group request.user.groups.add(group) # redirect to group page return redirect("group_page", group_info_id=group_info.id) else: form_group_name = GroupNameHandlerForm() form_group_description = GroupDescriptionHandlerForm() render_data_dict = {"form_group_name": form_group_name, "form_group_description": form_group_description} return render(request, "group_info/create_group_page.html", render_data_dict)
def setUpAuthData(self): self.group = Group(name='testgroup') self.group.save() self.othergroup = Group(name='othergroup') self.othergroup.save() self.unorm = User(username='******', email='*****@*****.**') self.unorm.set_password('password') self.normpass = '******' self.unorm.save() self.unorm.groups.add(self.group) self.unorm.save() self.ustaff = User(username='******', email='*****@*****.**', is_staff=True) self.ustaff.set_password('password') self.ustaff.save() self.ustaff.groups.add(self.othergroup) self.ustaff.save() self.unobody = User(username='******', email='*****@*****.**') self.unobody.set_password('password') self.unobody.save() self.norm = Client() self.norm.login(username='******', password='******') self.staff = Client() self.staff.login(username='******', password='******') self.nobody = Client() self.nobody.login(username='******', password='******')
def init(self): from modoboa.admin.models import User, Domain ct = ContentType.objects.get(app_label="admin", model="domain") dagrp = Group.objects.get(name="DomainAdmins") grp = Group(name="Resellers") grp.save() grp.permissions.add(*dagrp.permissions.all()) ct = ContentType.objects.get_for_model(Permission) for pname in ["view_permissions"]: perm = Permission.objects.get(content_type=ct, codename=pname) grp.permissions.add(perm) ct = ContentType.objects.get_for_model(Domain) for pname in ["view_domains", "add_domain", "change_domain", "delete_domain"]: perm = Permission.objects.get(content_type=ct, codename=pname) grp.permissions.add(perm) grp.save() for user in User.objects.filter(groups__name='DomainAdmins'): try: controls.create_pool(user) except IntegrityError: pass
def test_group_logo_is_not_present_on_list_view(self): """ Verify that no logo exists in list view when a group doesn't have one. """ test_group = Group(name="tester") test_profile = GroupProfile( group=test_group, title="test", slug="test", description="test", access="public" ) test_group.save() test_profile.save() response = self.client.get( reverse("api_dispatch_list", kwargs={"api_name": "api", "resource_name": "groups"}) ) response_payload = json.loads(response.content) returned = response_payload["objects"] group = [g for g in returned if g["title"] == test_profile.title][0] self.assertEqual(200, response.status_code) self.assertIsNone(group["logo"])
def setUp(self): self.tearDown() User(id=1, username='******').save() settings.ANONYMOUS_USER_ID=1 user = User(id=2, username='******') user.set_password('secret') user.save() user1 = User(id=3, username='******') user1.set_password('secret') user1.save() group = Group(name='testing_group') group.save() cluster = Cluster(hostname='test.osuosl.test', slug='OSL_TEST') cluster.save() dict_ = globals() dict_['user'] = user dict_['user1'] = user1 dict_['group'] = group dict_['cluster'] = cluster dict_['c'] = Client()
def post_save_project_handler(sender, **kwargs): """ fn that gets called after a QProject is saved; if it's just been created, then the corresponding permissions and groups need to be setup :param sender: :param kwargs: :return: """ created = kwargs.pop("created", True) project = kwargs.pop("instance", None) if created: assert project.groups.count() == 0 for group_suffix, permission_prefixes in GROUP_PERMISSIONS.iteritems(): group_name = "{0}_{1}".format(project.name, group_suffix) group = Group( name=group_name ) group.save() for permission_prefix in permission_prefixes: permission_codename = "{0}_{1}".format(permission_prefix, project.name) permission_description = "{0} {1} instances".format(permission_prefix, project.name) content_type = ContentType.objects.get(app_label=APP_LABEL, model='qproject') (permission, created_permission) = Permission.objects.get_or_create( codename=permission_codename, name=permission_description, content_type=content_type, ) group.permissions.add(permission) group.save() project.groups.add(group)
def group_save(sender, instance, created, *args, **kwargs): ''' Add Group to Django Groups ''' from groups_manager.settings import GROUPS_MANAGER if GROUPS_MANAGER['AUTH_MODELS_SYNC'] and instance.django_auth_sync: # create a name compatible with django group name limit of 80 chars prefix = GROUPS_MANAGER['GROUP_NAME_PREFIX'] suffix = GROUPS_MANAGER['GROUP_NAME_SUFFIX'] if suffix == '_$$random': suffix = '_%s' % str(uuid4())[:8] parent_name = '' if instance.parent: parent_name = '%s-' % instance.parent.name name = '%s%s%s%s' % (prefix, parent_name, instance.name, suffix) if not instance.django_group: django_group = DjangoGroup(name=name) django_group.save() instance.django_group = django_group instance.save() elif (instance.django_group.name != name and GROUPS_MANAGER['GROUP_NAME_SUFFIX'] != '_$$random') \ or (instance.django_group.name[:-len(suffix)] != name[:-len(suffix)] and GROUPS_MANAGER['GROUP_NAME_SUFFIX'] == '_$$random'): instance.django_group.name = name instance.django_group.save()
def test_creation_with_m2m_relation(self): class UserResource(ModelResource): model = User def url(self, instance): return "/users/%i" % instance.id group = Group(name='foo') group.save() form_data = { 'username': '******', 'password': '******', 'groups': [group.id] } request = self.req.post('/groups', data=form_data) cleaned_data = dict(form_data) cleaned_data['groups'] = [group] mixin = CreateModelMixin() mixin.resource = UserResource mixin.CONTENT = cleaned_data response = mixin.post(request) self.assertEquals(1, User.objects.count()) self.assertEquals(1, response.cleaned_content.groups.count()) self.assertEquals('foo', response.cleaned_content.groups.all()[0].name)
def test_permission_group_update_remove_users_with_manage_staff( permission_group_manage_users, staff_users, permission_manage_staff, staff_api_client, permission_manage_apps, permission_manage_users, permission_manage_orders, count_queries, ): query = """ mutation PermissionGroupUpdate( $id: ID!, $input: PermissionGroupUpdateInput!) { permissionGroupUpdate( id: $id, input: $input) { group{ id name permissions { name code } users { email } } permissionGroupErrors{ field code permissions users message } } } """ staff_user, staff_user1, staff_user2 = staff_users groups = Group.objects.bulk_create([ Group(name="manage users"), Group(name="manage staff, order and users") ]) group1, group2 = groups group1.permissions.add(permission_manage_staff, permission_manage_users) group2.permissions.add(permission_manage_staff, permission_manage_orders, permission_manage_users) group1.user_set.add(staff_user1, staff_user2) group2.user_set.add(staff_user2) staff_user.user_permissions.add(permission_manage_users, permission_manage_orders) variables = { "id": graphene.Node.to_global_id("Group", group1.id), "input": { "removeUsers": [ graphene.Node.to_global_id("User", user.id) for user in [staff_user1, staff_user2] ], }, } response = staff_api_client.post_graphql( query, variables, permissions=(permission_manage_staff, )) content = get_graphql_content(response) data = content["data"]["permissionGroupUpdate"] assert len(data["group"]["users"]) == 0
class Meta: model = Group() fields = ('id', 'name')
def populate_groups(): for i in range(1, 100): group = Group(name="Group %02d" % i) group.save()
from django.contrib.auth.models import Group from django.db import connection groups = [ Group(id=1, name='Student'), Group(id=2, name='Organization') ] def truncate(): with connection.cursor() as cursor: cursor.execute('TRUNCATE TABLE public.auth_group RESTART IDENTITY CASCADE') def seed(): for group in groups: if not Group.objects.filter(id=group.id).exists(): group.save()
def sync_unix_users_and_groups(min_uid, max_uid, min_gid, max_gid, check_shell): """ Syncs the Hue database with the underlying Unix system, by importing users and groups from 'getent passwd' and 'getent groups'. This should also pull in users who are accessible via NSS. """ global __users_lock, __groups_lock hadoop_groups = dict((group.gr_name, group) for group in grp.getgrall() \ if (group.gr_gid >= min_gid and group.gr_gid < max_gid) or group.gr_name == 'hadoop') user_groups = dict() __users_lock.acquire() __groups_lock.acquire() # Import groups for name, group in hadoop_groups.iteritems(): try: if len(group.gr_mem) != 0: hue_group = Group.objects.get(name=name) except Group.DoesNotExist: hue_group = Group(name=name) hue_group.save() LOG.info("Created group %s" % (hue_group.name, )) # Build a map of user to groups that the user is a member of members = group.gr_mem for member in members: if member not in user_groups: user_groups[member] = [hue_group] else: user_groups[member].append(hue_group) # Now let's import the users hadoop_users = dict((user.pw_name, user) for user in pwd.getpwall() \ if (user.pw_uid >= min_uid and user.pw_uid < max_uid) or user.pw_name in grp.getgrnam('hadoop').gr_mem) for username, user in hadoop_users.iteritems(): try: if check_shell: pw_shell = user.pw_shell if subprocess.call([pw_shell, "-c", "echo"], stdout=subprocess.PIPE) != 0: continue hue_user = User.objects.get(username=username) except User.DoesNotExist: hue_user = User(username=username, password='******', is_active=True, is_superuser=False) hue_user.set_unusable_password() # We have to do a save here, because the user needs to exist before we can # access the associated list of groups hue_user.save() if username not in user_groups: hue_user.groups = [] else: # Here's where that user to group map we built comes in handy hue_user.groups = user_groups[username] hue_user.save() LOG.info(_("Synced user %s from Unix") % hue_user.username) __users_lock.release() __groups_lock.release()
def setUp(self): # don't build PDF to speed up the tests settings.ZDS_APP['content']['build_pdf_when_published'] = False self.staff = StaffProfileFactory().user settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' self.mas = ProfileFactory().user settings.ZDS_APP['member']['bot_account'] = self.mas.username bot = Group(name=settings.ZDS_APP["member"]["bot_group"]) bot.save() self.external = UserFactory( username=settings.ZDS_APP["member"]["external_account"], password="******") self.beta_forum = ForumFactory( pk=settings.ZDS_APP['forum']['beta_forum_id'], category=CategoryFactory(position=1), position_in_category=1 ) # ensure that the forum, for the beta versions, is created self.licence = LicenceFactory() self.subcategory = SubCategoryFactory() self.user_author = ProfileFactory().user self.user_staff = StaffProfileFactory().user self.user_guest = ProfileFactory().user # create a tutorial self.tuto = PublishableContentFactory(type='TUTORIAL') self.tuto.authors.add(self.user_author) UserGalleryFactory(gallery=self.tuto.gallery, user=self.user_author, mode='W') self.tuto.licence = self.licence self.tuto.subcategory.add(self.subcategory) self.tuto.save() # fill it with one part, containing one chapter, containing one extract self.tuto_draft = self.tuto.load_version() self.part1 = ContainerFactory(parent=self.tuto_draft, db_object=self.tuto) self.chapter1 = ContainerFactory(parent=self.part1, db_object=self.tuto) self.extract1 = ExtractFactory(container=self.chapter1, db_object=self.tuto) # then, publish it ! version = self.tuto_draft.current_version self.published_tuto = publish_content(self.tuto, self.tuto_draft, is_major_update=True) self.tuto.sha_public = version self.tuto.sha_draft = version self.tuto.public_version = self.published_tuto self.tuto.save() # create an article self.article = PublishableContentFactory(type='ARTICLE') self.article.authors.add(self.user_author) UserGalleryFactory(gallery=self.article.gallery, user=self.user_author, mode='W') self.article.licence = self.licence self.article.subcategory.add(self.subcategory) self.article.save() # fill it with one extract self.article_draft = self.article.load_version() self.extract1 = ExtractFactory(container=self.article_draft, db_object=self.article) # then, publish it ! version = self.article_draft.current_version self.published_article = publish_content(self.article, self.article_draft, is_major_update=True) self.article.sha_public = version self.article.sha_draft = version self.article.public_version = self.published_article self.article.save()
#!/usr/bin/env python #-*- coding:utf-8 -*- from django.contrib.auth.models import Group as DjangoGroup gUsers = DjangoGroup(name='Users') gUsers.save() gGroupAdmins = DjangoGroup(name='GroupAdmins') gGroupAdmins.save() # Set users zen = User.objects.create_user('zen', 'zen@emailaddress', 'pwd123') zen.groups = [gUsers]
def add_user_to_groups(user, groups=tuple()): for group_name in groups: group = Group(name=group_name) group.save() group.user_set.add(user) return True
def setUp(self): g = Group(name='admin') g.save() g = Group(name='approver') g.save() g = Group(name='poweruser') g.save() g = Group(name='user') g.save() self.new_customer, created = CustomerCompany.objects.get_or_create( company_name='new customer') self.new_customer_site, created = Customer.objects.get_or_create( name='new customer', customer=self.new_customer) self.new_part, created = Part.objects.get_or_create( description='new part') self.new_part2, created = Part.objects.get_or_create( description='new part2') self.tst_user_username_good = 'tstuser_good' self.tst_user_pw_good = 'password_good' self.tst_user_email_good = '*****@*****.**' self.user = User.objects.create_user(self.tst_user_username_good, self.tst_user_email_good, self.tst_user_pw_good) self.new_rma, created = Rma.objects.get_or_create( last_modified_by=self.user, customer=self.new_customer_site, date='2014-04-04', case_number='1234', reference_number='1234', contact='bob') self.new_item, created = Item.objects.get_or_create(part=self.new_part, quantity=2, rma=self.new_rma) self.attachment = RmaAttachment.objects.get_or_create( rma=self.new_rma, file=SimpleUploadedFile('best_file_eva.txt', 'these are the file contents!'))
def test_filters(self): client = Client() admin_group = Group(name='admin') admin_group.save() manager_group = Group(name='manager') manager_group.save() admin = User.objects.create_user('test_admin', '*****@*****.**', 'pass') admin.is_staff = True admin.groups.add(admin_group) admin.groups.add(manager_group) admin.save() tokens = {} admin.profile.verified = True admin.profile.save() response = client.post("/auth-api/", data=json.dumps({ 'username': '******', 'password': '******' }), content_type="application/json") self.assertEqual(response.status_code, 200, "Now we should get the token!") tokens["admin"] = json.loads(response.content.decode("UTF-8"), "UTF-8")["token"] #add some meal: response = client.post("/meals/", data=json.dumps({ "text": "Apple", "date": "2017-04-02", "time": "15:30", "calories": 40 }), content_type="application/json", HTTP_AUTHORIZATION="JWT " + tokens["admin"]) self.assertEqual(response.status_code, 201, "Should be no problem") response = client.post("/meals/", data=json.dumps({ "text": "Banana", "date": "2017-04-15", "time": "15:30", "calories": 40 }), content_type="application/json", HTTP_AUTHORIZATION="JWT " + tokens["admin"]) self.assertEqual(response.status_code, 201, "Should be no problem") response = client.post("/meals/", data=json.dumps({ "text": "Apple", "date": "2017-04-20", "time": "16:05", "calories": 40 }), content_type="application/json", HTTP_AUTHORIZATION="JWT " + tokens["admin"]) self.assertEqual(response.status_code, 201, "Should be no problem") response = client.post("/meals/", data=json.dumps({ "text": "Banana", "date": "2017-04-20", "time": "17:30", "calories": 40 }), content_type="application/json", HTTP_AUTHORIZATION="JWT " + tokens["admin"]) self.assertEqual(response.status_code, 201, "Should be no problem") self.assertEqual(len(Meal.objects.all()), 4, "We have added 4 fruits") # First no filters: response = client.get("/meals/", content_type="application/json", HTTP_AUTHORIZATION="JWT " + tokens["admin"]) self.assertEqual( len(json.loads(response.content.decode("UTF-8"), "UTF-8")), 4, "Now api") # Search: response = client.get("/meals/?search=potato", content_type="application/json", HTTP_AUTHORIZATION="JWT " + tokens["admin"]) self.assertEqual( len(json.loads(response.content.decode("UTF-8"), "UTF-8")), 0, "No potato here") response = client.get("/meals/?search=apple", content_type="application/json", HTTP_AUTHORIZATION="JWT " + tokens["admin"]) self.assertEqual( len(json.loads(response.content.decode("UTF-8"), "UTF-8")), 2, "Two apples") response = client.get("/meals/?search=apple&time_from=16:00", content_type="application/json", HTTP_AUTHORIZATION="JWT " + tokens["admin"]) self.assertEqual( len(json.loads(response.content.decode("UTF-8"), "UTF-8")), 1, "One apple after 16:00") response = client.get("/meals/?search=apple&date_from=2017-04-16", content_type="application/json", HTTP_AUTHORIZATION="JWT " + tokens["admin"]) self.assertEqual( len(json.loads(response.content.decode("UTF-8"), "UTF-8")), 1, "One apple after 2017-04-16") response = client.get( "/meals/?date_from=2017-04-16&date_to=2017-04-20", content_type="application/json", HTTP_AUTHORIZATION="JWT " + tokens["admin"]) self.assertEqual( len(json.loads(response.content.decode("UTF-8"), "UTF-8")), 2, "Two fruits between these dates (no search)") response = client.get("/meals/?search=apple&time_to=16:00", content_type="application/json", HTTP_AUTHORIZATION="JWT " + tokens["admin"]) self.assertEqual( len(json.loads(response.content.decode("UTF-8"), "UTF-8")), 1, "One apple before 16:00") # anyone else should see no fruits at all, let us create some user response = client.post("/users/", data=json.dumps({ "username": "******", "password": "******", "email": "*****@*****.**" }), content_type="application/json") # print(json.loads(response.content.decode("UTF-8"), "UTF-8")) self.assertEqual(response.status_code, 201, "user should be created") new_user = User.objects.filter(username="******")[0] response = client.get("/verify/" + str(new_user.id) + "/" + new_user.profile.verification_code, content_type="application/json") response = client.post("/auth-api/", data=json.dumps({ 'username': new_user.username, 'password': "******" }), content_type="application/json") self.assertEqual(response.status_code, 200, "Now should be ok") tokens["test_api_1"] = json.loads(response.content.decode("UTF-8"), "UTF-8")["token"] response = client.get("/meals/", content_type="application/json", HTTP_AUTHORIZATION="JWT " + tokens["test_api_1"]) self.assertEqual( len(json.loads(response.content.decode("UTF-8"), "UTF-8")), 0, "Should not see anything") # Now let's add a potato for test_api_1: response = client.post("/meals/", data=json.dumps({ "text": "Banana", "date": "2017-04-15", "time": "15:30", "calories": 40 }), content_type="application/json", HTTP_AUTHORIZATION="JWT " + tokens["test_api_1"]) self.assertEqual(response.status_code, 201, "Should be no problem") # and try again: response = client.get("/meals/", content_type="application/json", HTTP_AUTHORIZATION="JWT " + tokens["test_api_1"]) self.assertEqual( len(json.loads(response.content.decode("UTF-8"), "UTF-8")), 1, "Only potato") # but admin now sees 5 meals: response = client.get("/meals/", content_type="application/json", HTTP_AUTHORIZATION="JWT " + tokens["admin"]) self.assertEqual( len(json.loads(response.content.decode("UTF-8"), "UTF-8")), 5, "Now api")
def test_permission_group_update( permission_group_manage_users, staff_users, permission_manage_staff, staff_api_client, permission_manage_apps, permission_manage_users, permission_manage_orders, count_queries, ): query = """ mutation PermissionGroupUpdate( $id: ID!, $input: PermissionGroupUpdateInput!) { permissionGroupUpdate( id: $id, input: $input) { group{ id name permissions { name code } } permissionGroupErrors{ field code permissions users message } } } """ staff_user = staff_users[0] staff_user.user_permissions.add(permission_manage_apps, permission_manage_users, permission_manage_orders) group1, group2 = Group.objects.bulk_create( [Group(name="manage users"), Group(name="manage staff and users")]) group1.permissions.add(permission_manage_users) group2.permissions.add(permission_manage_users, permission_manage_staff) group1_user = staff_users[1] group1.user_set.add(group1_user) group2.user_set.add(staff_user) group_count = Group.objects.count() variables = { "id": graphene.Node.to_global_id("Group", group1.id), "input": { "name": "New permission group", "addPermissions": [OrderPermissions.MANAGE_ORDERS.name], "removePermissions": [AccountPermissions.MANAGE_USERS.name], "addUsers": [graphene.Node.to_global_id("User", staff_user.pk)], "removeUsers": [graphene.Node.to_global_id("User", group1.user_set.first().pk)], }, } response = staff_api_client.post_graphql(query, variables) content = get_graphql_content(response) data = content["data"]["permissionGroupUpdate"] groups = Group.objects.all() assert data["permissionGroupErrors"] == [] assert len(groups) == group_count
class MemberTests(TestCase): def setUp(self): settings.EMAIL_BACKEND = \ 'django.core.mail.backends.locmem.EmailBackend' self.mas = ProfileFactory() settings.ZDS_APP['member']['bot_account'] = self.mas.user.username self.anonymous = UserFactory( username=settings.ZDS_APP["member"]["anonymous_account"], password="******") self.external = UserFactory( username=settings.ZDS_APP["member"]["external_account"], password="******") self.category1 = CategoryFactory(position=1) self.forum11 = ForumFactory(category=self.category1, position_in_category=1) self.staff = StaffProfileFactory().user self.bot = Group(name=settings.ZDS_APP["member"]["bot_group"]) self.bot.save() def test_karma(self): to_be_karmated = ProfileFactory() rand_member = ProfileFactory() self.client.login(username=rand_member.user.username, password="******") r = self.client.post(reverse("member-modify-karma"), { "profile_pk": to_be_karmated.pk, "points": 42, "warning": "warn" }) self.assertEqual(403, r.status_code) self.client.logout() self.client.login(username=self.staff.username, password="******") # bad id r = self.client.post(reverse("member-modify-karma"), { "profile_pk": "poo", "points": 42, "warning": "warn" }, follow=True) self.assertEqual(404, r.status_code) # good karma r = self.client.post(reverse("member-modify-karma"), { "profile_pk": to_be_karmated.pk, "points": 42, "warning": "warn" }, follow=True) self.assertEqual(200, r.status_code) self.assertIn("<strong>42</strong>", r.content.decode("utf-8")) # more than 100 karma must unvalidate the karma r = self.client.post(reverse("member-modify-karma"), { "profile_pk": to_be_karmated.pk, "points": 420, "warning": "warn" }, follow=True) self.assertEqual(200, r.status_code) self.assertNotIn("<strong>420</strong>", r.content.decode("utf-8")) # empty warning must unvalidate the karma r = self.client.post(reverse("member-modify-karma"), { "profile_pk": to_be_karmated.pk, "points": 41, "warning": "" }, follow=True) self.assertEqual(200, r.status_code) self.assertNotIn("<strong>41</strong>", r.content.decode("utf-8")) def test_list_members(self): """ To test the listing of the members with and without page parameter. """ # create strange member weird = ProfileFactory() weird.user.username = u"ïtrema718" weird.user.email = u"foo@\xfbgmail.com" weird.user.save() # list of members. result = self.client.get(reverse('member-list'), follow=False) self.assertEqual(result.status_code, 200) nb_users = len(result.context['members']) # Test that inactive user don't show up unactive_user = ProfileFactory() unactive_user.user.is_active = False unactive_user.user.save() result = self.client.get(reverse('member-list'), follow=False) self.assertEqual(result.status_code, 200) self.assertEqual(nb_users, len(result.context['members'])) # Add a Bot and check that list didn't change bot_profile = ProfileFactory() bot_profile.user.groups.add(self.bot) bot_profile.user.save() result = self.client.get(reverse('member-list'), follow=False) self.assertEqual(result.status_code, 200) self.assertEqual(nb_users, len(result.context['members'])) # list of members with page parameter. result = self.client.get(reverse('member-list') + u'?page=1', follow=False) self.assertEqual(result.status_code, 200) # page which doesn't exist. result = self.client.get(reverse('member-list') + u'?page=1534', follow=False) self.assertEqual(result.status_code, 404) # page parameter isn't an integer. result = self.client.get(reverse('member-list') + u'?page=abcd', follow=False) self.assertEqual(result.status_code, 404) def test_details_member(self): """ To test details of a member given. """ # details of a staff user. result = self.client.get(reverse('member-detail', args=[self.staff.username]), follow=False) self.assertEqual(result.status_code, 200) # details of an unknown user. result = self.client.get(reverse('member-detail', args=['unknown_user']), follow=False) self.assertEqual(result.status_code, 404) def test_profile_page_of_weird_member_username(self): # create some user with weird username user_1 = ProfileFactory() user_2 = ProfileFactory() user_3 = ProfileFactory() user_1.user.username = u"ïtrema" user_1.user.save() user_2.user.username = u""a" user_2.user.save() user_3.user.username = u"_`_`_`_" user_3.user.save() # profile pages of weird users. result = self.client.get(reverse('member-detail', args=[user_1.user.username]), follow=True) self.assertEqual(result.status_code, 200) result = self.client.get(reverse('member-detail', args=[user_2.user.username]), follow=True) self.assertEqual(result.status_code, 200) result = self.client.get(reverse('member-detail', args=[user_3.user.username]), follow=True) self.assertEqual(result.status_code, 200) def test_modify_member(self): # we need staff right for update other profile self.client.logout() self.client.login(username=self.staff.username, password="******") # an inexistant member return 404 result = self.client.get(reverse('member-settings-mini-profile', args=["xkcd"]), follow=False) self.assertEqual(result.status_code, 404) # an existant member return 200 result = self.client.get(reverse('member-settings-mini-profile', args=[self.mas.user.username]), follow=False) self.assertEqual(result.status_code, 200) def test_login(self): """ To test user login. """ user = ProfileFactory() # login a user. Good password then redirection to the homepage. result = self.client.post(reverse('member-login'), { 'username': user.user.username, 'password': '******', 'remember': 'remember' }, follow=False) self.assertRedirects(result, reverse('homepage')) # login failed with bad password then no redirection # (status_code equals 200 and not 302). result = self.client.post(reverse('member-login'), { 'username': user.user.username, 'password': '******', 'remember': 'remember' }, follow=False) self.assertEqual(result.status_code, 200) # login a user. Good password and next parameter then # redirection to the "next" page. result = self.client.post(reverse('member-login') + '?next=' + reverse('gallery-list'), { 'username': user.user.username, 'password': '******', 'remember': 'remember' }, follow=False) self.assertRedirects(result, reverse('gallery-list')) # check if the login form will redirect if there is # a next parameter. self.client.logout() result = self.client.get( reverse('member-login') + '?next=' + reverse('gallery-list')) self.assertContains(result, reverse('member-login') + '?next=' + reverse('gallery-list'), count=1) def test_register(self): """ To test user registration. """ # register a new user. result = self.client.post(reverse('register-member'), { 'username': '******', 'password': '******', 'password_confirm': 'flavour', 'email': '*****@*****.**' }, follow=False) self.assertEqual(result.status_code, 200) # check email has been sent. self.assertEquals(len(mail.outbox), 1) # check if the new user is well inactive. user = User.objects.get(username='******') self.assertFalse(user.is_active) # make a request on the link which has been sent in mail to # confirm the registration. token = TokenRegister.objects.get(user=user) result = self.client.get(settings.ZDS_APP['site']['url'] + token.get_absolute_url(), follow=False) self.assertEqual(result.status_code, 200) # check a new email hasn't been sent at the new user. self.assertEquals(len(mail.outbox), 1) # check if the new user is active. self.assertTrue(User.objects.get(username='******').is_active) def test_unregister(self): """ To test that unregistering user is working. """ # test not logged user can't unregister. self.client.logout() result = self.client.post(reverse('member-unregister'), follow=False) self.assertEqual(result.status_code, 302) # test logged user can register. user = ProfileFactory() login_check = self.client.login(username=user.user.username, password='******') self.assertEqual(login_check, True) result = self.client.post(reverse('member-unregister'), follow=False) self.assertEqual(result.status_code, 302) self.assertEqual( User.objects.filter(username=user.user.username).count(), 0) # Attach a user at tutorials, articles, topics and private topics. After that, # unregister this user and check that he is well removed in all contents. user = ProfileFactory() user2 = ProfileFactory() alone_gallery = GalleryFactory() UserGalleryFactory(gallery=alone_gallery, user=user.user) shared_gallery = GalleryFactory() UserGalleryFactory(gallery=shared_gallery, user=user.user) UserGalleryFactory(gallery=shared_gallery, user=user2.user) # first case : a published tutorial with only one author published_tutorial_alone = PublishedContentFactory(type='TUTORIAL') published_tutorial_alone.authors.add(user.user) published_tutorial_alone.save() # second case : a published tutorial with two authors published_tutorial_2 = PublishedContentFactory(type='TUTORIAL') published_tutorial_2.authors.add(user.user) published_tutorial_2.authors.add(user2.user) published_tutorial_2.save() # third case : a private tutorial with only one author writing_tutorial_alone = PublishableContentFactory(type='TUTORIAL') writing_tutorial_alone.authors.add(user.user) writing_tutorial_alone.save() writing_tutorial_alone_galler_path = writing_tutorial_alone.gallery.get_gallery_path( ) # fourth case : a private tutorial with at least two authors writing_tutorial_2 = PublishableContentFactory(type='TUTORIAL') writing_tutorial_2.authors.add(user.user) writing_tutorial_2.authors.add(user2.user) writing_tutorial_2.save() self.client.login(username=self.staff.username, password="******") # same thing for articles published_article_alone = PublishedContentFactory(type='ARTICLE') published_article_alone.authors.add(user.user) published_article_alone.save() published_article_2 = PublishedContentFactory(type='ARTICLE') published_article_2.authors.add(user.user) published_article_2.authors.add(user2.user) published_article_2.save() writing_article_alone = PublishableContentFactory(type='ARTICLE') writing_article_alone.authors.add(user.user) writing_article_alone.save() writing_article_2 = PublishableContentFactory(type='ARTICLE') writing_article_2.authors.add(user.user) writing_article_2.authors.add(user2.user) writing_article_2.save() # beta content beta_forum = ForumFactory(category=CategoryFactory()) beta_content = BetaContentFactory(author_list=[user.user], forum=beta_forum) beta_content_2 = BetaContentFactory( author_list=[user.user, user2.user], forum=beta_forum) # about posts and topics authored_topic = TopicFactory(author=user.user, forum=self.forum11) answered_topic = TopicFactory(author=user2.user, forum=self.forum11) PostFactory(topic=answered_topic, author=user.user, position=2) edited_answer = PostFactory(topic=answered_topic, author=user.user, position=3) edited_answer.editor = user.user edited_answer.save() upvoted_answer = PostFactory(topic=answered_topic, author=user2.user, position=4) upvoted_answer.like += 1 upvoted_answer.save() CommentVote.objects.create(user=user.user, comment=upvoted_answer, positive=True) private_topic = PrivateTopicFactory(author=user.user) private_topic.participants.add(user2.user) private_topic.save() PrivatePostFactory(author=user.user, privatetopic=private_topic, position_in_topic=1) # add API key self.assertEqual(Application.objects.count(), 0) self.assertEqual(AccessToken.objects.count(), 0) api_application = Application() api_application.client_id = 'foobar' api_application.user = user.user api_application.client_type = 'confidential' api_application.authorization_grant_type = 'password' api_application.client_secret = '42' api_application.save() token = AccessToken() token.user = user.user token.token = 'r@d0m' token.application = api_application token.expires = datetime.now() token.save() self.assertEqual(Application.objects.count(), 1) self.assertEqual(AccessToken.objects.count(), 1) # login and unregister: login_check = self.client.login(username=user.user.username, password='******') self.assertEqual(login_check, True) result = self.client.post(reverse('member-unregister'), follow=False) self.assertEqual(result.status_code, 302) # check that the bot have taken authorship of tutorial: self.assertEqual(published_tutorial_alone.authors.count(), 1) self.assertEqual(published_tutorial_alone.authors.first().username, settings.ZDS_APP["member"]["external_account"]) self.assertFalse(os.path.exists(writing_tutorial_alone_galler_path)) self.assertEqual(published_tutorial_2.authors.count(), 1) self.assertEqual( published_tutorial_2.authors.filter( username=settings.ZDS_APP["member"] ["external_account"]).count(), 0) # check that published tutorials remain published and accessible self.assertIsNotNone( published_tutorial_2.public_version.get_prod_path()) self.assertTrue( os.path.exists( published_tutorial_2.public_version.get_prod_path())) self.assertIsNotNone( published_tutorial_alone.public_version.get_prod_path()) self.assertTrue( os.path.exists( published_tutorial_alone.public_version.get_prod_path())) self.assertEqual( self.client.get(reverse('tutorial:view', args=[ published_tutorial_alone.pk, published_tutorial_alone.slug ]), follow=False).status_code, 200) self.assertEqual( self.client.get(reverse( 'tutorial:view', args=[published_tutorial_2.pk, published_tutorial_2.slug]), follow=False).status_code, 200) # test that published articles remain accessible self.assertTrue( os.path.exists( published_article_alone.public_version.get_prod_path())) self.assertEqual( self.client.get(reverse('article:view', args=[ published_article_alone.pk, published_article_alone.slug ]), follow=True).status_code, 200) self.assertEqual( self.client.get(reverse( 'article:view', args=[published_article_2.pk, published_article_2.slug]), follow=True).status_code, 200) # check that the tutorial for which the author was alone does not exists anymore self.assertEqual( PublishableContent.objects.filter( pk=writing_tutorial_alone.pk).count(), 0) self.assertFalse(os.path.exists( writing_tutorial_alone.get_repo_path())) # check that bot haven't take the authorship of the tuto with more than one author self.assertEqual(writing_tutorial_2.authors.count(), 1) self.assertEqual( writing_tutorial_2.authors.filter( username=settings.ZDS_APP["member"] ["external_account"]).count(), 0) # authorship for the article for which user was the only author self.assertEqual(published_article_alone.authors.count(), 1) self.assertEqual(published_article_alone.authors.first().username, settings.ZDS_APP["member"]["external_account"]) self.assertEqual(published_article_2.authors.count(), 1) self.assertEqual( PublishableContent.objects.filter( pk=writing_article_alone.pk).count(), 0) self.assertFalse(os.path.exists(writing_article_alone.get_repo_path())) # not bot if another author: self.assertEqual( published_article_2.authors.filter( username=settings.ZDS_APP["member"] ["external_account"]).count(), 0) self.assertEqual(writing_article_2.authors.count(), 1) self.assertEqual( writing_article_2.authors.filter( username=settings.ZDS_APP["member"] ["external_account"]).count(), 0) # topics, gallery and PMs: self.assertEqual( Topic.objects.filter(author__username=user.user.username).count(), 0) self.assertEqual( Post.objects.filter(author__username=user.user.username).count(), 0) self.assertEqual( Post.objects.filter(editor__username=user.user.username).count(), 0) self.assertEqual( PrivatePost.objects.filter( author__username=user.user.username).count(), 0) self.assertEqual( PrivateTopic.objects.filter( author__username=user.user.username).count(), 0) self.assertIsNotNone(Topic.objects.get(pk=authored_topic.pk)) self.assertIsNotNone(PrivateTopic.objects.get(pk=private_topic.pk)) self.assertIsNotNone(Gallery.objects.get(pk=alone_gallery.pk)) self.assertEquals(alone_gallery.get_linked_users().count(), 1) self.assertEquals(shared_gallery.get_linked_users().count(), 1) self.assertEquals( UserGallery.objects.filter(user=user.user).count(), 0) self.assertEquals( CommentVote.objects.filter(user=user.user, positive=True).count(), 0) self.assertEquals( Post.objects.filter(pk=upvoted_answer.id).first().like, 0) # zep 12, published contents and beta self.assertIsNotNone( PublishedContent.objects.filter( content__pk=published_tutorial_alone.pk).first()) self.assertIsNotNone( PublishedContent.objects.filter( content__pk=published_tutorial_2.pk).first()) self.assertTrue( Topic.objects.get(pk=beta_content.beta_topic.pk).is_locked) self.assertFalse( Topic.objects.get(pk=beta_content_2.beta_topic.pk).is_locked) # check API self.assertEqual(Application.objects.count(), 0) self.assertEqual(AccessToken.objects.count(), 0) def test_forgot_password(self): """To test nominal scenario of a lost password.""" # Empty the test outbox mail.outbox = [] result = self.client.post(reverse('member-forgot-password'), { 'username': self.mas.user.username, 'email': '', }, follow=False) self.assertEqual(result.status_code, 200) # check email has been sent self.assertEquals(len(mail.outbox), 1) # clic on the link which has been sent in mail user = User.objects.get(username=self.mas.user.username) token = TokenForgotPassword.objects.get(user=user) result = self.client.get(settings.ZDS_APP['site']['url'] + token.get_absolute_url(), follow=False) self.assertEqual(result.status_code, 200) def test_sanctions(self): """ Test various sanctions. """ staff = StaffProfileFactory() login_check = self.client.login(username=staff.user.username, password='******') self.assertEqual(login_check, True) # list of members. result = self.client.get(reverse('member-list'), follow=False) self.assertEqual(result.status_code, 200) nb_users = len(result.context['members']) # Test: LS user_ls = ProfileFactory() result = self.client.post(reverse('member-modify-profile', kwargs={'user_pk': user_ls.user.id}), { 'ls': '', 'ls-text': 'Texte de test pour LS' }, follow=False) user = Profile.objects.get(id=user_ls.id) # Refresh profile from DB self.assertEqual(result.status_code, 302) self.assertFalse(user.can_write) self.assertTrue(user.can_read) self.assertIsNone(user.end_ban_write) self.assertIsNone(user.end_ban_read) ban = Ban.objects.filter(user__id=user.user.id).order_by('-pubdate')[0] self.assertEqual(ban.type, 'Lecture Seule') self.assertEqual(ban.text, 'Texte de test pour LS') self.assertEquals(len(mail.outbox), 1) result = self.client.get(reverse('member-list'), follow=False) self.assertEqual(result.status_code, 200) self.assertEquals(nb_users + 1, len( result.context['members'])) # LS guy still shows up, good # Test: Un-LS result = self.client.post(reverse('member-modify-profile', kwargs={'user_pk': user_ls.user.id}), { 'un-ls': '', 'unls-text': 'Texte de test pour un-LS' }, follow=False) user = Profile.objects.get(id=user_ls.id) # Refresh profile from DB self.assertEqual(result.status_code, 302) self.assertTrue(user.can_write) self.assertTrue(user.can_read) self.assertIsNone(user.end_ban_write) self.assertIsNone(user.end_ban_read) ban = Ban.objects.filter(user__id=user.user.id).order_by('-id')[0] self.assertEqual(ban.type, u'Autorisation d\'écrire') self.assertEqual(ban.text, 'Texte de test pour un-LS') self.assertEquals(len(mail.outbox), 2) result = self.client.get(reverse('member-list'), follow=False) self.assertEqual(result.status_code, 200) self.assertEquals(nb_users + 1, len( result.context['members'])) # LS guy still shows up, good # Test: LS temp user_ls_temp = ProfileFactory() result = self.client.post( reverse('member-modify-profile', kwargs={'user_pk': user_ls_temp.user.id}), { 'ls-temp': '', 'ls-jrs': 10, 'ls-text': u'Texte de test pour LS TEMP' }, follow=False) user = Profile.objects.get( id=user_ls_temp.id) # Refresh profile from DB self.assertEqual(result.status_code, 302) self.assertFalse(user.can_write) self.assertTrue(user.can_read) self.assertIsNotNone(user.end_ban_write) self.assertIsNone(user.end_ban_read) ban = Ban.objects.filter(user__id=user.user.id).order_by('-id')[0] self.assertEqual(ban.type, u'Lecture Seule Temporaire') self.assertEqual(ban.text, u'Texte de test pour LS TEMP') self.assertEquals(len(mail.outbox), 3) # reset nb_users result = self.client.get(reverse('member-list'), follow=False) self.assertEqual(result.status_code, 200) nb_users = len(result.context['members']) # Test: BAN user_ban = ProfileFactory() result = self.client.post(reverse('member-modify-profile', kwargs={'user_pk': user_ban.user.id}), { 'ban': '', 'ban-text': u'Texte de test pour BAN' }, follow=False) user = Profile.objects.get(id=user_ban.id) # Refresh profile from DB self.assertEqual(result.status_code, 302) self.assertTrue(user.can_write) self.assertFalse(user.can_read) self.assertIsNone(user.end_ban_write) self.assertIsNone(user.end_ban_read) ban = Ban.objects.filter(user__id=user.user.id).order_by('-id')[0] self.assertEqual(ban.type, u'Ban définitif') self.assertEqual(ban.text, u'Texte de test pour BAN') self.assertEquals(len(mail.outbox), 4) result = self.client.get(reverse('member-list'), follow=False) self.assertEqual(result.status_code, 200) self.assertEquals(nb_users, len( result.context['members'])) # Banned guy doesn't show up, good # Test: un-BAN result = self.client.post(reverse('member-modify-profile', kwargs={'user_pk': user_ban.user.id}), { 'un-ban': '', 'unban-text': u'Texte de test pour BAN' }, follow=False) user = Profile.objects.get(id=user_ban.id) # Refresh profile from DB self.assertEqual(result.status_code, 302) self.assertTrue(user.can_write) self.assertTrue(user.can_read) self.assertIsNone(user.end_ban_write) self.assertIsNone(user.end_ban_read) ban = Ban.objects.filter(user__id=user.user.id).order_by('-id')[0] self.assertEqual(ban.type, u'Autorisation de se connecter') self.assertEqual(ban.text, u'Texte de test pour BAN') self.assertEquals(len(mail.outbox), 5) result = self.client.get(reverse('member-list'), follow=False) self.assertEqual(result.status_code, 200) self.assertEquals(nb_users + 1, len( result.context['members'])) # UnBanned guy shows up, good # Test: BAN temp user_ban_temp = ProfileFactory() result = self.client.post( reverse('member-modify-profile', kwargs={'user_pk': user_ban_temp.user.id}), { 'ban-temp': '', 'ban-jrs': 10, 'ban-text': u'Texte de test pour BAN TEMP' }, follow=False) user = Profile.objects.get( id=user_ban_temp.id) # Refresh profile from DB self.assertEqual(result.status_code, 302) self.assertTrue(user.can_write) self.assertFalse(user.can_read) self.assertIsNone(user.end_ban_write) self.assertIsNotNone(user.end_ban_read) ban = Ban.objects.filter(user__id=user.user.id).order_by('-id')[0] self.assertEqual(ban.type, u'Ban Temporaire') self.assertEqual(ban.text, u'Texte de test pour BAN TEMP') self.assertEquals(len(mail.outbox), 6) def test_failed_bot_sanctions(self): staff = StaffProfileFactory() login_check = self.client.login(username=staff.user.username, password='******') self.assertEqual(login_check, True) bot_profile = ProfileFactory() bot_profile.user.groups.add(self.bot) bot_profile.user.save() # Test: LS result = self.client.post( reverse('member-modify-profile', kwargs={'user_pk': bot_profile.user.id}), { 'ls': '', 'ls-text': 'Texte de test pour LS' }, follow=False) user = Profile.objects.get( id=bot_profile.id) # Refresh profile from DB self.assertEqual(result.status_code, 403) self.assertTrue(user.can_write) self.assertTrue(user.can_read) self.assertIsNone(user.end_ban_write) self.assertIsNone(user.end_ban_read) def test_nonascii(self): user = NonAsciiProfileFactory() result = self.client.get( reverse('member-login') + '?next=' + reverse('member-detail', args=[user.user.username]), follow=False) self.assertEqual(result.status_code, 200) def test_promote_interface(self): """ Test promotion interface. """ # create users (one regular, one staff and one superuser) tester = ProfileFactory() staff = StaffProfileFactory() tester.user.is_active = False tester.user.save() staff.user.is_superuser = True staff.user.save() # create groups group = Group.objects.create(name="DummyGroup_1") groupbis = Group.objects.create(name="DummyGroup_2") # create Forums, Posts and subscribe member to them. category1 = CategoryFactory(position=1) forum1 = ForumFactory(category=category1, position_in_category=1) forum1.group.add(group) forum1.save() forum2 = ForumFactory(category=category1, position_in_category=2) forum2.group.add(groupbis) forum2.save() forum3 = ForumFactory(category=category1, position_in_category=3) topic1 = TopicFactory(forum=forum1, author=staff.user) topic2 = TopicFactory(forum=forum2, author=staff.user) topic3 = TopicFactory(forum=forum3, author=staff.user) # LET THE TEST BEGIN ! # tester shouldn't be able to connect login_check = self.client.login(username=tester.user.username, password='******') self.assertEqual(login_check, False) # connect as staff (superuser) login_check = self.client.login(username=staff.user.username, password='******') self.assertEqual(login_check, True) # check that we can go through the page result = self.client.get(reverse('member-settings-promote', kwargs={'user_pk': tester.user.id}), follow=False) self.assertEqual(result.status_code, 200) # give user rights and groups thanks to staff (but account still not activated) result = self.client.post(reverse('member-settings-promote', kwargs={'user_pk': tester.user.id}), { 'groups': [group.id, groupbis.id], 'superuser': "******", }, follow=False) self.assertEqual(result.status_code, 302) tester = Profile.objects.get(id=tester.id) # refresh self.assertEqual(len(tester.user.groups.all()), 2) self.assertFalse(tester.user.is_active) self.assertTrue(tester.user.is_superuser) # Now our tester is going to follow one post in every forum (3) TopicAnswerSubscription.objects.toggle_follow(topic1, tester.user) TopicAnswerSubscription.objects.toggle_follow(topic2, tester.user) TopicAnswerSubscription.objects.toggle_follow(topic3, tester.user) self.assertEqual( len( TopicAnswerSubscription.objects.get_objects_followed_by( tester.user)), 3) # retract all right, keep one group only and activate account result = self.client.post(reverse('member-settings-promote', kwargs={'user_pk': tester.user.id}), { 'groups': [group.id], 'activation': "on" }, follow=False) self.assertEqual(result.status_code, 302) tester = Profile.objects.get(id=tester.id) # refresh self.assertEqual(len(tester.user.groups.all()), 1) self.assertTrue(tester.user.is_active) self.assertFalse(tester.user.is_superuser) self.assertEqual( len( TopicAnswerSubscription.objects.get_objects_followed_by( tester.user)), 2) # no groups specified result = self.client.post(reverse('member-settings-promote', kwargs={'user_pk': tester.user.id}), {'activation': "on"}, follow=False) self.assertEqual(result.status_code, 302) tester = Profile.objects.get(id=tester.id) # refresh self.assertEqual( len( TopicAnswerSubscription.objects.get_objects_followed_by( tester.user)), 1) # check that staff can't take away it's own super user rights result = self.client.post(reverse('member-settings-promote', kwargs={'user_pk': staff.user.id}), {'activation': "on"}, follow=False) self.assertEqual(result.status_code, 302) staff = Profile.objects.get(id=staff.id) # refresh self.assertTrue(staff.user.is_superuser) # still superuser ! # Finally, check that user can connect and can not access the interface login_check = self.client.login(username=tester.user.username, password='******') self.assertEqual(login_check, True) result = self.client.post(reverse('member-settings-promote', kwargs={'user_pk': staff.user.id}), {'activation': "on"}, follow=False) self.assertEqual(result.status_code, 403) # forbidden ! def test_filter_member_ip(self): """ Test filter member by ip. """ # create users (one regular and one staff and superuser) tester = ProfileFactory() staff = StaffProfileFactory() # test login normal user result = self.client.post(reverse('member-login'), { 'username': tester.user.username, 'password': '******', 'remember': 'remember' }, follow=False) # good password then redirection self.assertEqual(result.status_code, 302) # Check that the filter can't be access from normal user result = self.client.post( reverse('member-from-ip', kwargs={'ip_address': tester.last_ip_address}), {}, follow=False) self.assertEqual(result.status_code, 403) # log the staff user result = self.client.post(reverse('member-login'), { 'username': staff.user.username, 'password': '******', 'remember': 'remember' }, follow=False) # good password then redirection self.assertEqual(result.status_code, 302) # test that we retrieve correctly the 2 members (staff + user) from this ip result = self.client.post( reverse('member-from-ip', kwargs={'ip_address': staff.last_ip_address}), {}, follow=False) self.assertEqual(result.status_code, 200) self.assertEqual(len(result.context['members']), 2) def test_modify_user_karma(self): """ To test karma of a user modified by a staff user. """ tester = ProfileFactory() staff = StaffProfileFactory() # login as user result = self.client.post(reverse('member-login'), { 'username': tester.user.username, 'password': '******' }, follow=False) self.assertEqual(result.status_code, 302) # check that user can't use this feature result = self.client.post(reverse('member-modify-karma'), follow=False) self.assertEqual(result.status_code, 403) # login as staff result = self.client.post(reverse('member-login'), { 'username': staff.user.username, 'password': '******' }, follow=False) self.assertEqual(result.status_code, 302) # try to give a few bad points to the tester result = self.client.post(reverse('member-modify-karma'), { 'profile_pk': tester.pk, 'warning': 'Bad tester is bad !', 'points': '-50' }, follow=False) self.assertEqual(result.status_code, 302) tester = Profile.objects.get(pk=tester.pk) self.assertEqual(tester.karma, -50) self.assertEqual(KarmaNote.objects.filter(user=tester.user).count(), 1) # Now give a few good points result = self.client.post(reverse('member-modify-karma'), { 'profile_pk': tester.pk, 'warning': 'Good tester is good !', 'points': '10' }, follow=False) self.assertEqual(result.status_code, 302) tester = Profile.objects.get(pk=tester.pk) self.assertEqual(tester.karma, -40) self.assertEqual(KarmaNote.objects.filter(user=tester.user).count(), 2) # Now access some unknow user result = self.client.post(reverse('member-modify-karma'), { 'profile_pk': 9999, 'warning': 'Good tester is good !', 'points': '10' }, follow=False) self.assertEqual(result.status_code, 404) # Now give unknow point result = self.client.post(reverse('member-modify-karma'), { 'profile_pk': tester.pk, 'warning': 'Good tester is good !', 'points': '' }, follow=False) self.assertEqual(result.status_code, 302) tester = Profile.objects.get(pk=tester.pk) self.assertEqual(tester.karma, -40) self.assertEqual(KarmaNote.objects.filter(user=tester.user).count(), 3) # Now give no point at all result = self.client.post(reverse('member-modify-karma'), { 'profile_pk': tester.pk, 'warning': 'Good tester is good !' }, follow=False) self.assertEqual(result.status_code, 302) tester = Profile.objects.get(pk=tester.pk) self.assertEqual(tester.karma, -40) self.assertEqual(KarmaNote.objects.filter(user=tester.user).count(), 4) # Now access without post result = self.client.get(reverse('member-modify-karma'), follow=False) self.assertEqual(result.status_code, 405) def test_karma_and_pseudo_change(self): """ To test that a karma note is added when a member change its pseudo """ tester = ProfileFactory() old_pseudo = tester.user.username self.client.login(username=tester.user.username, password="******") data = {'username': '******', 'email': ''} result = self.client.post(reverse('update-username-email-member'), data, follow=False) self.assertEqual(result.status_code, 302) notes = KarmaNote.objects.filter(user=tester.user).all() self.assertEqual(len(notes), 1) self.assertTrue(old_pseudo in notes[0].comment and 'dummy' in notes[0].comment) def test_ban_member_is_not_contactable(self): """ When a member is ban, we hide the button to send a PM. """ user_ban = ProfileFactory() user_ban.can_read = False user_ban.can_write = False user_ban.save() user_1 = ProfileFactory() user_2 = ProfileFactory() phrase = "Envoyer un message privé" result = self.client.get(reverse('member-detail', args=[user_1.user.username]), follow=False) self.assertNotContains(result, phrase) result = self.client.get(reverse('member-detail', args=[user_ban.user.username]), follow=False) self.assertNotContains(result, phrase) self.assertTrue( self.client.login(username=user_2.user.username, password='******')) result = self.client.get(reverse('member-detail', args=[user_1.user.username]), follow=False) self.client.logout() self.assertContains(result, phrase) self.assertTrue( self.client.login(username=user_2.user.username, password='******')) result = self.client.get(reverse('member-detail', args=[user_ban.user.username]), follow=False) self.client.logout() self.assertNotContains(result, phrase) self.assertTrue( self.client.login(username=user_1.user.username, password='******')) result = self.client.get(reverse('member-detail', args=[user_1.user.username]), follow=False) self.client.logout() self.assertNotContains(result, phrase) def tearDown(self): if os.path.isdir(settings.ZDS_APP['content']['repo_private_path']): shutil.rmtree(settings.ZDS_APP['content']['repo_private_path']) if os.path.isdir(settings.ZDS_APP['content']['repo_public_path']): shutil.rmtree(settings.ZDS_APP['content']['repo_public_path']) if os.path.isdir(settings.MEDIA_ROOT): shutil.rmtree(settings.MEDIA_ROOT)
def test_reachable_manager(self): # profile types profile_normal = ProfileFactory() profile_superuser = ProfileFactory() profile_superuser.user.is_superuser = True profile_superuser.user.save() profile_inactive = ProfileFactory() profile_inactive.user.is_active = False profile_inactive.user.save() profile_bot = ProfileFactory() profile_bot.user.username = settings.ZDS_APP['member']['bot_account'] profile_bot.user.save() profile_anonymous = ProfileFactory() profile_anonymous.user.username = settings.ZDS_APP['member']['anonymous_account'] profile_anonymous.user.save() profile_external = ProfileFactory() profile_external.user.username = settings.ZDS_APP['member']['external_account'] profile_external.user.save() profile_ban_def = ProfileFactory() profile_ban_def.can_read = False profile_ban_def.can_write = False profile_ban_def.save() profile_ban_temp = ProfileFactory() profile_ban_temp.can_read = False profile_ban_temp.can_write = False profile_ban_temp.end_ban_read = datetime.now() + timedelta(days=1) profile_ban_temp.save() profile_unban = ProfileFactory() profile_unban.can_read = False profile_unban.can_write = False profile_unban.end_ban_read = datetime.now() - timedelta(days=1) profile_unban.save() profile_ls_def = ProfileFactory() profile_ls_def.can_write = False profile_ls_def.save() profile_ls_temp = ProfileFactory() profile_ls_temp.can_write = False profile_ls_temp.end_ban_write = datetime.now() + timedelta(days=1) profile_ls_temp.save() # groups bot = Group(name=settings.ZDS_APP['member']['bot_group']) bot.save() # associate account to groups bot.user_set.add(profile_anonymous.user) bot.user_set.add(profile_external.user) bot.user_set.add(profile_bot.user) bot.save() # test reachable user profiles_reacheable = Profile.objects.contactable_members().all() self.assertIn(profile_normal, profiles_reacheable) self.assertIn(profile_superuser, profiles_reacheable) self.assertNotIn(profile_inactive, profiles_reacheable) self.assertNotIn(profile_anonymous, profiles_reacheable) self.assertNotIn(profile_external, profiles_reacheable) self.assertNotIn(profile_bot, profiles_reacheable) self.assertIn(profile_unban, profiles_reacheable) self.assertNotIn(profile_ban_def, profiles_reacheable) self.assertNotIn(profile_ban_temp, profiles_reacheable) self.assertIn(profile_ls_def, profiles_reacheable) self.assertIn(profile_ls_temp, profiles_reacheable)
# "Does the user have a specific permission?" # # Simplest possible answer: Yes, always # return True # def has_module_perms(self, app_label): # "Does the user have permissions to view the app `app_label`?" # # Simplest possible answer: Yes, always # return True # @property # def is_staff(self): # "Is the user a member of staff?" # # Simplest possible answer: All admins are staff # return self.is_admin Group.add_to_class('VG', models.CharField(max_length=180,null=True, blank=True)) Group.add_to_class('rol', models.CharField(max_length=180,null=True, blank=True)) class TAapplicationmodel(models.Model): firmname=models.TextField() addr1=models.TextField() addr2=models.TextField() tot=models.TextField() item_name=models.TextField() part_no=models.TextField() desc=models.TextField() spec=models.TextField() dal_mdi=models.TextField() bom=models.TextField() sop_acbs = models.TextField()
def run(*script_args): """ Script to creates group and users in the platform from a CSV file with a column containing email addresses. Invocation example: python manage.py runscript initial_data \ --script-args "-d -i -e 'emailcolumn' users.csv" :param script_args: Arguments given to the script. -d Turns on debug -i make users members of the instructor group (def. False) -e <string> email column name (def. email) <filename> CSV filename containing the data :return: Changes reflected in the dt The script executes two tasks: 1) Creates the group "instructor" if needed 2) Process the CSV files (if given) by selecting the column with the given name (option -e) or 'email' and creating the users accordingly. """ # Parse the arguments argv = [] if script_args: argv = shlex.split(script_args[0]) # Default values for the arguments debug = False email_column_name = 'email' make_instructors = False password = '******' # Parse options try: opts, args = getopt.getopt(argv, "de:ip:") except getopt.GetoptError as e: print(e.msg) print(run.__doc__) sys.exit(2) # Store option values for optstr, value in opts: if optstr == "-d": debug = True elif optstr == "-i": make_instructors = True elif optstr == "-e": email_column_name = value elif optstr == "-p": password = value filenames = args if debug: print('Options:') print(' Debug:' + str(debug)) print(' Email column name:', email_column_name) print(' Make instructors:', str(make_instructors)) print(' Default password: '******' Files: ' + ', '.join(filenames)) if debug: print('Step: Creating the instructor group') group = Group.objects.filter(name='instructor').first() # Create the instructor group if it does not exist if not group: group = Group(name='instructor') group.save() elif debug: print('Group already exists. Bypassing.') if debug: print('Done') if not make_instructors: group = None # If there is no argument we are done. if len(script_args) == 0: return if debug: print('Step: Creating users') if not make_instructors: group = None not_present = [x for x in filenames if not os.path.exists(x)] if not_present: print('These files were not found: ', ', '.join(not_present)) filenames = [x for x in filenames if x not in not_present] if not filenames: print('No files provided to create users. Terminating') return # Get the emails emails = get_column_value_list(filenames, email_column_name, debug) create_users(emails, password, group, debug)
from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, Group from django.utils.translation import gettext as _ Group.add_to_class('description', models.TextField(max_length=140, null=True)) Group.add_to_class('isPrivate', models.BooleanField(default=False)) ''' class InviteManager(models.Manager): def create_invite(self, toUser=None, fromUser=None, groupID=None): invite = self.model(toUser=self.toUser, fromUser=self.fromUser, groupID=self.groupID) return invite class Invite(models.Model): toUser = models.ForeignKey(User, related_name='received_invite', verbose_name=_('invitee')) fromUser = models.ForeignKey(User, related_name='sent_invite', verbose_name=_('inviter')) groupID = models.ForeignKey(Group, ) ''' class UserManager(BaseUserManager): def create_user(self, email=None, password=None): user = self.model(email=self.normalize_email(email)) user.set_password(password) return user def create_normal_user(self, email=None, first_name=None, last_name=None, password=None): user = self.create_user(email=email, password=password)
def create_group(request): if 'group' not in request.GET: response = render_response_index( request, 'tardis_portal/ajax/create_group.html', {}) return response admin = None groupname = None if 'group' in request.GET: groupname = request.GET['group'] if not groupname: return JsonResponse(dict(message='Group name cannot be blank', field='id_addgroup'), status=400) if 'admin' in request.GET: admin = request.GET['admin'] try: with transaction.atomic(): group = Group(name=groupname) group.save() except IntegrityError: return JsonResponse(dict( message=('Could not create group %s ' '(It is likely that it already exists)' % groupname), field='id_addgroup'), status=409) adminuser = None if admin: try: adminuser = User.objects.get(username=admin) except User.DoesNotExist: return JsonResponse(dict(message='User %s does not exist' % admin, field='id_groupadmin'), status=400) # create admin for this group and add it to the group groupadmin = GroupAdmin(user=adminuser, group=group) groupadmin.save() adminuser.groups.add(group) adminuser.save() # add the current user as admin as well for newly created groups if request.user != adminuser: user = request.user groupadmin = GroupAdmin(user=user, group=group) groupadmin.save() user.groups.add(group) user.save() c = {'group': group} response = render_response_index(request, 'tardis_portal/ajax/create_group.html', c) return response
def test_edit_group_happy_path_for_superuser(self): request = self.wagtail_factory.post('/') request.user = self.superuser request.site = self.wagtail_site request.POST = self.happy_path_form_data # Generate a Group based on the happy path data. group = Group() form = MultitenantGroupForm(request.POST, instance=group, request=request) permission_panels = get_permission_panel_instances(request, group) form.is_valid() new_group = form.save() for panel in permission_panels: panel.save() # Now, edit the group and make sure the edits come through correctly. request = self.wagtail_factory.post('/') request.user = self.superuser request.site = self.wagtail_site request.POST = copy.deepcopy(self.happy_path_form_data) # Add "add_redirect" and remove "change_user". request.POST['permissions'] = [ self.perm_map['change_settings'].pk, self.perm_map['change_group'].pk, self.perm_map['access_admin'].pk, self.perm_map['add_redirect'].pk, ] # Remove publish and lock permissions. request.POST['page_permissions-0-permission_types'] = [ 'add', 'edit', 'bulk_delete' ] # Remove permission to change documents, but leave image_permissions unchanged. request.POST['image_permissions-INITIAL_FORMS'] = 1 request.POST['document_permissions-INITIAL_FORMS'] = 1 request.POST['document_permissions-0-permissions'] = [ self.perm_map['add_document'].pk ] form = MultitenantGroupForm(request.POST, instance=new_group, request=request) permission_panels = get_permission_panel_instances(request, new_group) valid = form.is_valid() self.assertTrue(valid) new_group = form.save() for panel in permission_panels: panel.save() self.assertEqual(new_group.name, request.POST['name']) perm_ids = set(perm.pk for perm in new_group.permissions.all()) self.assertEqual(perm_ids, set(request.POST['permissions'])) page_perm_codenames = set(perm.permission_type for perm in new_group.page_permissions.all()) self.assertEqual( page_perm_codenames, set(request.POST['page_permissions-0-permission_types'])) for collection_perm in new_group.collection_permissions.all(): self.assertEqual(collection_perm.collection.pk, self.wagtail_collection.pk) collection_perm_ids = set( perm.permission.pk for perm in new_group.collection_permissions.all()) self.assertEqual( collection_perm_ids, set(request.POST['document_permissions-0-permissions'] + request.POST['image_permissions-0-permissions']))
def forwards(self, orm): "Write your forwards methods here." moderators = Group(name='askbot_moderators') moderators.save()
@date 18-01-2017 @version 1.0.0 """ from django.db import models from django.contrib.auth.models import (Group, User) from utils.models import ( TipoDocumento, ) from organizaciones.models import ( Vocero, ) """ Se agrega un campo de descripcion al modelo group para describir el grupo de usuarios """ Group.add_to_class('descripcion', models.TextField(blank=True)) class UserProfile(models.Model): """! Clase que construye el modelo de datos para el perfil de usuario @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> @date 18-01-2017 @version 1.0.0 """ fk_user = models.OneToOneField(User) fk_tipo_documento = models.ForeignKey(TipoDocumento) id_perfil = models.CharField(unique=True, max_length=12,
class AutocompleteTestCase(unittest.TestCase): autocomplete_mock = None def setUpAuth(self): self.user_ctype = ContentType.objects.get_for_model(User) self.group_ctype = ContentType.objects.get_for_model(Group) User.objects.all().delete() self.abe = User(username='******', email='*****@*****.**') self.jack = User(username='******', email='*****@*****.**') self.james = User(username='******', email='*****@*****.**') self.john = User(username='******', email='*****@*****.**') self.elton = User(username='******', email='*****@*****.**', pk=10) self.abe.save() self.jack.save() self.james.save() self.john.save() Group.objects.all().delete() self.rockers = Group(name='rockers') self.bluesmen = Group(name='bluesmen') self.jazzmen = Group(name='jazzmen') self.emos = Group(name='emos', pk=10) self.rockers.save() self.bluesmen.save() self.jazzmen.save() self.emos.save() def assert_choices_equal(self, result, test): self.assertEqual(result, test['expected']) def test_choices_for_request(self): if not hasattr(self, 'get_choices_for_request_tests'): return for test in self.get_choices_for_request_tests(): mock = self.autocomplete_mock(request=test['fixture']) result = mock.choices_for_request() self.assert_choices_equal(list(result), test) def test_choices_for_values(self): if not hasattr(self, 'get_choices_for_values_tests'): return for test in self.get_choices_for_values_tests(): mock = self.autocomplete_mock(values=test['fixture']) result = mock.choices_for_values() self.assert_choices_equal(result, test) def assert_validate_success(self, result, test): self.assertEqual( result, test['expected'], u'Got %s for test %s %s' % (result, self.__class__.__name__, test)) def test_validate(self): if not hasattr(self, 'get_validate_tests'): return for test in self.get_validate_tests(): mock = self.autocomplete_mock(values=test['fixture']) result = mock.validate_values() self.assert_validate_success(result, test) def test_autocomplete_html(self): if not hasattr(self, 'get_autocomplete_html_tests'): return for test in self.get_autocomplete_html_tests(): mock = self.autocomplete_mock(request=test['fixture']) result = mock.autocomplete_html() self.assert_html_equals(result, test) def assert_html_equals(self, result, test): self.assertEqual( result, test['expected'], u'Got %s for test %s %s' % (result, self.__class__.__name__, test)) def test_widget(self): form_class = None if not hasattr(self, 'get_widget_tests'): return for test in self.get_widget_tests(): if 'form_class' in test.keys(): form_class = test['form_class'] # for display test['form_class'] = form_class.__name__ form = form_class(http.QueryDict(test['fixture'])) try: valid = form.is_valid() except TypeError: print self.__class__, test, self.get_widget_tests() raise self.assertEqual( valid, test['expected_valid'], u'Unexepected valid: %s for test %s %s' % (valid, self.__class__.__name__, test)) if valid: data = form.cleaned_data['x'] self.assertEqual( str(data), str(test['expected_data']), u'Unexepected data: %s for test %s %s' % (data, self.__class__.__name__, test))
gz2 = GlobalSetting(id=2,heat_setpoint=70, cool_setpoint=72, illuminance=67, zone_id=2) gz2.save() gz3 = GlobalSetting(id=3,heat_setpoint=70, cool_setpoint=72, illuminance=67, zone_id=3) gz3.save() gz4 = GlobalSetting(id=4,heat_setpoint=70, cool_setpoint=72, illuminance=67, zone_id=4) gz4.save() ''' gz999 = GlobalSetting(id=999,heat_setpoint=70, cool_setpoint=72, illuminance=67, zone_id=999) gz999.save() #User groups tenant = Group(id=1, name="Tenant") tenant.save() zonemgr = Group(id=2, name="Zone Manager") zonemgr.save() admin = Group(id=3, name="Admin") admin.save() #Add admin to user profile admin = User.objects.get(username='******') admin.first_name = "Admin" admin.save() #user_id = admin.id #uprof = UserProfile(user_id=1) #uprof.save()
class AddParticipantViewTest(TestCase): def setUp(self): self.profile1 = ProfileFactory() self.profile2 = ProfileFactory() self.anonymous_account = UserFactory(username=settings.ZDS_APP['member']['anonymous_account']) self.bot_group = Group() self.bot_group.name = settings.ZDS_APP['member']['bot_group'] self.bot_group.save() self.anonymous_account.groups.add(self.bot_group) self.anonymous_account.save() self.topic1 = PrivateTopicFactory(author=self.profile1.user) self.topic1.participants.add(self.profile2.user) self.post1 = PrivatePostFactory( privatetopic=self.topic1, author=self.profile1.user, position_in_topic=1) self.post2 = PrivatePostFactory( privatetopic=self.topic1, author=self.profile2.user, position_in_topic=2) self.assertTrue( self.client.login( username=self.profile1.user.username, password='******' ) ) def test_denies_anonymous(self): self.client.logout() response = self.client.get( reverse('mp-edit-participant', args=[1, 'private-topic']), follow=True ) self.assertRedirects( response, reverse('member-login') + '?next=' + reverse('mp-edit-participant', args=[1, 'private-topic'])) def test_fail_add_participant_topic_no_exist(self): response = self.client.post( reverse('mp-edit-participant', args=[451, 'private-topic']), follow=True ) self.assertEqual(404, response.status_code) def test_test_fail_add_bot_as_participant(self): self.client.logout() self.assertTrue( self.client.login( username=self.profile1.user.username, password='******' ) ) self.client.post( reverse('mp-edit-participant', args=[self.topic1.pk, self.topic1.slug]), { 'username': self.anonymous_account.username } ) self.assertFalse(self.anonymous_account in self.topic1.participants.all()) def test_fail_add_participant_who_no_exist(self): response = self.client.post( reverse('mp-edit-participant', args=[self.topic1.pk, self.topic1.slug]), { 'username': '******' }, follow=True ) self.assertEqual(200, response.status_code) self.assertEqual(1, len(response.context['messages'])) def test_fail_add_participant_with_no_right(self): profile3 = ProfileFactory() self.client.logout() self.assertTrue( self.client.login( username=profile3.user.username, password='******' ) ) response = self.client.post( reverse('mp-edit-participant', args=[self.topic1.pk, self.topic1.slug]), { 'username': profile3.user.username } ) self.assertEqual(403, response.status_code) self.assertNotIn( profile3.user, PrivateTopic.objects.get(pk=self.topic1.pk).participants.all() ) def test_fail_add_participant_already_in(self): response = self.client.post( reverse('mp-edit-participant', args=[self.topic1.pk, self.topic1.slug]), { 'username': self.profile2.user.username }, follow=True ) self.assertEqual(200, response.status_code) self.assertEqual(1, len(response.context['messages'])) def test_success_add_participant(self): profile3 = ProfileFactory() response = self.client.post( reverse('mp-edit-participant', args=[self.topic1.pk, self.topic1.slug]), { 'username': profile3.user.username }, follow=True ) self.assertEqual(200, response.status_code) self.assertEqual(1, len(response.context['messages'])) self.assertIn( profile3.user, PrivateTopic.objects.get(pk=self.topic1.pk).participants.all() )
from utils.aoi_utils import simplify_geom, force2d from django.contrib import admin import rasterio from rasterio import mask from osm_export_tool.mapping import Mapping from hdx_exports.hdx_export_set import HDXExportSet LOG = logging.getLogger(__name__) MAX_TILE_COUNT = 10000 DIR = os.path.dirname(os.path.abspath(__file__)) RASTER = rasterio.open(os.path.join(DIR,'osm_nodes.tif')) Group.add_to_class('is_partner', models.BooleanField(null=False, default=False)) def get_geodesic_area(geom): bbox = geom.envelope """ Uses the algorithm to calculate geodesic area of a polygon from OpenLayers 2. See http://bit.ly/1Mite1X. Args: geom (GEOSGeometry): the export extent as a GEOSGeometry. Returns area (float): the geodesic area of the provided geometry. """ area = 0.0 coords = bbox.coords[0]
def test_non_ascii(self): group = Group(name="清風") output = self.engine.render_to_string('non_ascii', {'group': group}) self.assertTrue( output.startswith('{'group': <Group: 清風>}'))
class LeaveViewTest(TestCase): def setUp(self): self.profile1 = ProfileFactory() self.profile2 = ProfileFactory() self.anonymous_account = UserFactory(username=settings.ZDS_APP['member']['anonymous_account']) self.bot_group = Group() self.bot_group.name = settings.ZDS_APP['member']['bot_group'] self.bot_group.save() self.anonymous_account.groups.add(self.bot_group) self.anonymous_account.save() self.topic1 = PrivateTopicFactory(author=self.profile1.user) self.topic1.participants.add(self.profile2.user) self.post1 = PrivatePostFactory( privatetopic=self.topic1, author=self.profile1.user, position_in_topic=1) self.post2 = PrivatePostFactory( privatetopic=self.topic1, author=self.profile2.user, position_in_topic=2) self.assertTrue( self.client.login( username=self.profile1.user.username, password='******' ) ) def test_denies_anonymous(self): self.client.logout() response = self.client.get(reverse('mp-delete', args=[1, 'private-topic']), follow=True) self.assertRedirects( response, reverse('member-login') + '?next=' + reverse('mp-delete', args=[1, 'private-topic'])) def test_fail_leave_topic_no_exist(self): response = self.client.post(reverse('mp-delete', args=[999, 'private-topic'])) self.assertEqual(404, response.status_code) def test_success_leave_topic_as_author_no_participants(self): self.topic1.participants.clear() self.topic1.save() response = self.client.post(reverse('mp-delete', args=[self.topic1.pk, self.topic1.slug]), follow=True) self.assertEqual(200, response.status_code) self.assertEqual( 0, PrivateTopic.objects.filter(pk=self.topic1.pk).all().count() ) def test_success_leave_topic_as_author(self): response = self.client.post(reverse('mp-delete', args=[self.topic1.pk, self.topic1.slug]), follow=True) self.assertEqual(200, response.status_code) self.assertEqual( 1, PrivateTopic.objects.filter(pk=self.topic1.pk).all().count() ) self.assertEqual( self.profile2.user, PrivateTopic.objects.get(pk=self.topic1.pk).author ) def test_success_leave_topic_as_participant(self): self.client.logout() self.assertTrue( self.client.login( username=self.profile2.user.username, password='******' ) ) response = self.client.post(reverse('mp-delete', args=[self.topic1.pk, self.topic1.slug]), follow=True) self.assertEqual(200, response.status_code) self.assertNotIn( self.profile2.user, PrivateTopic.objects.get(pk=self.topic1.pk).participants.all() ) self.assertNotEqual( self.profile2.user, PrivateTopic.objects.get(pk=self.topic1.pk).author )
def setUp(self): self.wf = None # Creamos los datos del proceso para pruebas self.p = [ Storage(id=1, nombre="Prueba", descripcion="esta es una prueba de un proceso", activo=True, fecha_desactivacion=None), Storage(id=2, nombre="Prueba Numero Dos", descripcion="esta es una prueba de un proceso", activo=True, fecha_desactivacion=None), Storage(id=3, nombre="Prueba Numero Tres", descripcion="esta es una prueba de un proceso", activo=True, fecha_desactivacion=None), Storage(id=4, nombre="Prueba", descripcion="esta es una prueba de un proceso version 2", activo=False, fecha_desactivacion=None) ] self.inactivo = Storage(id=5, nombre="Prueba Inactivo", descripcion="esta es una prueba de un proceso", activo=False, fecha_desactivacion=datetime.now()) self.sin_flujo = Storage( id=6, nombre="Prueba Sin flujo", descripcion="esta es una prueba de un proceso", activo=True, fecha_desactivacion=None) #Creamos grupos de usuarios self.objGroup = [] grupos = [ Storage(name="Nombre del grupo uno"), Storage(name="Nombre del grupo dos"), Storage(name="Nombre del grupo tres"), Storage(name="Nombre del grupo cuatro") ] # Guardamos los datos del proceso y los grupos de usuarios self.proceso_inactivo = Proceso(**self.inactivo) self.proceso_sin_flujo = Proceso(**self.sin_flujo) self.proceso_inactivo.save() self.proceso_sin_flujo.save() for p in self.p: self.proceso = Proceso(**p) self.proceso.save() for gp in grupos: g = Group(**gp) g.save() self.objGroup.append(g) #Asignamos grupos a los usuarios registrados users = User.objects.all()[0:4] for i, u in enumerate(users): u.groups.add(self.objGroup[1 - i]) # Creamos los datos del flujo para el proceso flujos = [ Storage(proceso=None, grupo=self.objGroup[0], nombre="Primer paso", inicio=True, fin=False), Storage(proceso=None, grupo=self.objGroup[1], nombre="Segundo paso", inicio=False, fin=False), Storage(proceso=None, grupo=self.objGroup[0], nombre="Regresando paso uno", inicio=False, fin=False), Storage(proceso=None, grupo=self.objGroup[2], nombre="Tercer paso", inicio=False, fin=False), Storage(proceso=None, grupo=self.objGroup[3], nombre="Cuarto paso fin", inicio=False, fin=True) ] # Creamos instancias de los objetos y los guardamos for p in self.p: fls = flujos for fl in fls: fl.proceso = Proceso.objects.get(pk=p.id) f = Flujo(**fl) f.save() for p in self.p: fls = Flujo.objects.filter(proceso=p.id) proceso = Proceso.objects.get(pk=p.id) fujos_secuencias = [ Storage(actual=fls[0].id, siguiente=fls[1].id, proceso=proceso), Storage(actual=fls[1].id, siguiente=fls[2].id, proceso=proceso), Storage(actual=fls[2].id, siguiente=fls[0].id, proceso=proceso), Storage(actual=fls[3].id, siguiente=fls[4].id, proceso=proceso) ] for fs in fujos_secuencias: f = FlujoSecuencia(**fs) f.save() #Obteniendo pst aleatorio para las pruebas self.proceso = Proceso.objects.get( pk=random.randint(1, len(self.p) - 1)) random_id = random.randint(1, Pst.objects.count()) self.pst = Pst.objects.get(id=random_id)
def handle(self, *group_names, interactive, verbosity, dry_run, **options): message = [] if dry_run: print( '\nYou have activated the --dry-run option so nothing will be modified.\n' ) try: filepath = options.get('file') or settings.GROUP_SYNC_FILENAME with open(filepath) as file: file_data = json.load(file) except FileNotFoundError as e: raise CommandError('File "{}" not found.'.format(filepath)) data_groups = file_data['groups'].keys() ######################################################## # Prepare data if group_names: # check if selected groups are in file for gn in group_names: if gn not in data_groups: raise CommandError( 'Group "{}" not found in file groups.'.format(gn)) else: group_names = data_groups # check if groups are present in database groups = Group.objects.prefetch_related('permissions').filter( name__in=group_names).values_list('name', flat=True) groups_to_create = set(group_names).difference(groups) groups_to_sync = set(group_names) - groups_to_create if not dry_run and interactive: if verbosity: message.append('') if groups_to_create: message.append('Groups to be created: {}'.format( '; '.join(groups_to_create))) if groups_to_sync: message.append('Groups to be synced: {}'.format( '; '.join(groups_to_sync))) print('\n'.join(message)) message = [''] if input('\nDo you want to sync? [type "yes" to continue] ' ) != 'yes': print() raise CommandError('Group sync cancelled.') for g_name in group_names: permissions = [] # check if all apps and models exist in Content Types missing_apps_models = {} missing_models_permissions = {} for app_label, app_models in file_data['groups'][g_name].items(): content_types = ContentType.objects.filter( model__in=app_models) if content_types.count() != len(app_models): missing_models = set(app_models) - set( content_types.values_list('model', flat=True)) missing_apps_models[app_label] = missing_models # check if permissions exist for ct in content_types: ct_permissions = ct.permission_set.filter( codename__in=app_models[ct.model]) perms_codenames = ct_permissions.values_list('codename', flat=True) if len(perms_codenames) != len(app_models[ct.model]): missing_permissions = set( app_models[ct.model]) - set(perms_codenames) missing_models_permissions[ ct.model] = missing_permissions else: permissions.extend(ct_permissions) if missing_apps_models or missing_models_permissions: if missing_apps_models: message.append('ContentType app models are missing:') for app_label, missing_models in missing_apps_models.items( ): message.append(' - {}: {}'.format( app_label, ', '.join(missing_models), )) if missing_models_permissions: if message: message.append('\n') message.append('Model permissions are missing:') for model, perms in missing_models_permissions.items(): message.append(' - {}: {}'.format( model, ', '.join(perms), )) print('\n'.join(message)) raise CommandError('Group sync cannot continue') ################################################################### # do the main sync if dry_run: if g_name in groups_to_create: g = Group(name=g_name) group_created = True else: g = Group.objects.get(name=g_name) group_created = False else: g, group_created = Group.objects.get_or_create(name=g_name) if group_created: to_create = permissions else: to_create = set(permissions).difference(g.permissions.all()) if not dry_run: g.permissions.add(*to_create) to_remove = [] if not group_created: to_remove = set(g.permissions.all()) - set(permissions) if not dry_run and to_remove: g.permissions.remove(*to_remove) if verbosity and (to_create or to_remove): group_state = 'synced' if group_created: group_state = 'created' if dry_run and group_created: permissions_count = len(permissions) else: permissions_count = g.permissions.count() message.append('Group "{}" {} and has {} permissions:'.format( g.name, group_state, permissions_count, )) message.append(' - assigned: {} permissions'.format( len(to_create))) if not group_created: message.append(' - removed: {} permissions'.format( len(to_remove))) else: if verbosity: message.append( 'Group "{}" already in sync and has {} permissions.'. format( g.name, g.permissions.count(), )) if verbosity: message.append('\nDone...') print('\n'.join(message))
def createGroup(group_name): group = Group(name=group_name) group.save() print "Created group: %s" % group.name return group
from django.core.management import call_command from shutil import copyfile import os, django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "vmwebman.settings") django.setup() # setup django environment # Migrate database call_command("makemigrations", "vmapp") call_command("migrate") # Create super user for admin panel call_command("createsuperuser") from django.contrib.auth.models import Group group = Group(name="change_power_operation") group.save() copyfile("vmapp/config.sample.ini", "vmapp/config.ini") print( "OK! Now modify vmapp/config.ini, and run `python manage.py runserver` to run server" )