def create_group(request, ): """ Create group for the professor user. """ if request.method == "GET": form = GroupForm() # Set the choices field for the member fields. form.fields['members'].choices = get_related_candidates(request.user) return render(request, 'core/create_group.html', { 'form': form, }) # The request is a POST method. elif request.method == "POST": """ We need to set the choices field for the form, so that it can validates itself. """ form = GroupForm(request.POST) form.fields['members'].choices = get_related_candidates(request.user) if form.is_valid(): members = form.cleaned_data['members'] title = form.cleaned_data['title'] group = Group() group.creator = request.user.professor group.title = title group.save() for student in members: candidate = User.objects.get(username=student).candidate group.members.add(candidate) return redirect("core:connection") else: print(form.errors)
def applygroup(request): ''' Method: applygroup Description: View that manages when a user tries to apply to a group Input parameters: request object Return: Void ''' context_dict = {} context_dict['date'] = False # we check that the start date is not in the future if OtherConstraints.objects.all()[0].selectGroupStartDate > date.today(): return render(request, 'applygroup.html', context=context_dict) # if the start date is in the past, we set the context flag date to true context_dict['date'] = True # we get the students object of the user logged in and the pair # that it belongs to, if any user = Student.objects.get(user_ptr_id=request.user.id) pair = Pair.objects.filter((Q(student1=user) | Q(student2=user)) & Q(validated=True)) context_dict['group_form'] = GroupForm(user=user) context_dict['group_user'] = user.labGroup # if the user does no tbelong to any group if user.labGroup is None: # if the method is a POST if request.method == 'POST': # get the group requested by the user form = GroupForm(user=user, data=request.POST) # check that the group is a valid one if form.is_valid(): group = LabGroup.objects.get(id=request.POST.get('labId')) context_dict['group_user'] = group # if the user has no partner, add it to # the labgroup and encrease the counter if len(pair) == 0: group.counter = group.counter + 1 user.labGroup = group user.save() group.save() # if the user has a partner, add both components of # the pair to that labgroup # and increase the counter by 2 else: group.counter = group.counter + 2 pair[0].student1.labGroup = group pair[0].student2.labGroup = group pair[0].student1.save() pair[0].student2.save() group.save() return render(request, 'applygroup.html', context=context_dict)
def mutate(self, info, **kwargs): if not info.context.user: raise GraphQLError(json.dumps({"error": "Not authorized"})) form = GroupForm(kwargs) if form.is_valid(): form.save() UserGroupLink.objects.create(group=form.instance, user=info.context.user, permission=3) return CreateGroupMutation(group=form.instance, user=info.context.user) raise GraphQLError(json.dumps(form.errors))
def mutate(self, info, **kwargs): if not info.context.user: raise GraphQLError(json.dumps({"error": "Not authorized"})) group = Group.objects.filter(id=kwargs["id"]) if not group: raise GraphQLError('{"group": ["Does not exist"]}') if not groups_run_by_user(info.context.user).filter(id=kwargs["id"]): raise GraphQLError('{"group": ["Not an admin"]}') form = GroupForm(kwargs, instance=group.first()) if form.is_valid(): form.save() return UpdateGroupMutation(group=form.instance, user=info.context.user) raise GraphQLError(json.dumps(form.errors))
def create_group(request): """ 新建权限组 :param request: :return: """ result = {"status": 0, "apiVersion": "1.0", "msg": "", "data": {}} form = GroupForm(request.POST) if form.is_valid(): form.save() else: result['msg'] = u'表单填写错误' return json_response(result) result['status'] = 1 result['msg'] = u'新建成功' return json_response(result)
def reg_group(): '''단체신청''' form = GroupForm(request.form) form.set_camp(campcode) if request.method == "POST": group_idx = form.insert(Camp.get_idx(campcode)) session['type'] = '단체' session['idx'] = group_idx flash('신청이 완료되었습니다.') return redirect(url_for('.group_info')) script_file = 'common/js/reg-group.js' return render_template('{0}/form.html'.format(campcode), form=form, page_header="단체신청", script=url_for('static', filename=script_file))
def put(self, request): '''This method is intended for updating Groups.''' response = [] for item in request.data: pkval = item.get('id') g = item.get('group') if not (pkval and g): log.error("Unable to update group. No group or ID provided") return Response(status=status.HTTP_400_BAD_REQUEST) current_client_key = g.get('current_client_key', None) if not current_client_key: log.error("Unable to update group. No client key provided") return Response(status=status.HTTP_400_BAD_REQUEST) try: grp = Group.objects.get(pk=pkval) if not grp.verify_client_key(current_client_key): log.error("Unable to update group. Bad client key") return Response(status=status.HTTP_401_UNAUTHORIZED) name = g.get('name', grp.name) lock = g.get('is_locking', grp.is_locking) des = g.get('description', grp.description) client_key = g.get('client_key', current_client_key) js = { "name": name, "client_key": client_key, "is_locking": lock, "description": des } form = GroupForm(js, instance=grp) rd = FormHelpers.processFormJsonResponse( form, response, invalid_dict={'id': pkval}) if rd.get('success', False): grp = Group.objects.get(pk=rd.get('id')) rd['ehb_key'] = grp.ehb_key.key else: return Response except Group.DoesNotExist: log.error("Unable to update group. Group does not exist.") response.append({ 'id': pkval, 'success': False, 'errors': [{ 'id': ErrorConstants.ERROR_RECORD_ID_NOT_FOUND }] }) return Response(response)
def edit_group(): '''단체 수정''' idx = session['idx'] form = GroupForm(request.form) form.set_camp(campcode) if request.method == "POST": form.update(idx) flash("단체 정보 수정이 완료되었습니다.") return redirect(url_for('.group_info')) group = db.session.query(Group).filter(Group.idx == idx).one() form.set_group_data(group) script_file = 'common/js/reg-group-edit.js' return render_template('{0}/form.html'.format(campcode), form=form, page_header="단체신청 수정", script=url_for('static', filename=script_file), editmode=True)
def post(self, request): '''This method is intended for creating Groups.''' response = [] for g in request.data: form = GroupForm(g) args = {'name': g.get('name')} rd = FormHelpers.processFormJsonResponse(form, response, valid_dict=args, invalid_dict=args) if rd.get('success', False): grp = Group.objects.get(pk=rd.get('id')) rd['ehb_key'] = grp.ehb_key.key return Response(response)
def manage_group(request, group_id=None): if request.user.is_superuser: if group_id: actual_group = get_object_or_404(Group, pk=group_id) else: actual_group = Group() # POST mode if request.method == 'POST': form = GroupForm(request.POST, instance=actual_group) if form.is_valid(): form.save() return redirect('group-list') else: # Non-POST mode, show only form = GroupForm(instance=actual_group) return render(request, 'core/groups/create_edit_group.html', locals()) else: raise Http404
def __test_get_fields_by_user(self): fields = [ 'editor_user', 'viewer_users', 'editor_user_groups', 'viewer_user_groups' ] request = self.factory.request() for u in ('user_admin01', 'user_admin02', 'user_editor1', 'user_editor2'): request.user = getattr(self, u) core_form_group = GroupForm(**{'request': request}) filtered_fields = map(lambda f: f.get_field_names()[0][1], get_fields_by_user(request.user, core_form_group)) self.assertTrue(filtered_fields == fields) del(core_form_group)
def group_edit(group_idx): ''' 신청서 수정 ''' form = GroupForm(request.form) form.set_camp(campcode) if request.method == "POST": form.update(group_idx) flash('수정이 완료되었습니다') return redirect(url_for('.member_list')) group = db.session.query(Group).filter(Group.idx == group_idx).one() form.set_group_data(group) params = { 'form': form, 'page_header': "단체 정보 수정", # 'script': url_for('static', filename='{0}/js/reg-individual-edit.js'.format(campcode)), 'editmode': True } return render_template('{0}/form.html'.format(campcode), **params)
def test_groups_form(self): # set user as admin01 self.request.user = self.test_user1 # empty form form = GroupForm(request=self.request) self.assertFalse(form.is_valid()) # upload header_logo_image uf = create_dff_image(field_name='header_logo_img') # Test Create # ------------------------------ name = 'Map group test' form_data = { 'title': name, 'name': name, 'description': 'Test', 'srid': self.epsg.pk, 'form_id': uf.form_id, 'lang': 'it', 'mapcontrols': [mp.pk for mp in self.map_controls] } # Test ACL form_data.update({ 'editor_user': self.test_editor1.pk, 'editor2_user': self.test_editor2.pk, 'viewer_users': [self.test_viewer1.pk, self.test_viewer1_2.pk], 'editor_user_groups': [self.test_gu_editor1.pk], 'viewer_user_groups': [self.test_gu_viewer1.pk, self.test_gu_viewer2.pk] }) form = GroupForm(request=self.request, data=form_data) self.assertTrue(form.is_valid()) # Check possible choices values # editor1 editor1.2 editor1.3 self.assertEqual(len(form.fields['editor_user'].queryset), 3) # editor2 editor2.2 editor2.3 self.assertEqual(len(form.fields['editor2_user'].queryset), 3) # viewer1 viewer1.2 viewer1.3 anonymous self.assertEqual(len(form.fields['viewer_users'].queryset), 4) # GU_EDITOR1 GU_EDITOR2 GU_EDITOR1_E1_2 self.assertEqual(len(form.fields['editor_user_groups'].queryset), 3) # GU_VIEWER1 GU_VIEWER2 GU_VIEWER_E1_2 self.assertEqual(len(form.fields['viewer_user_groups'].queryset), 3) form.save() # check is it saved into db mg = Group.objects.get(name='Map group test') self.assertEqual(mg.name, name) self.assertEqual(mg.srid.srid, self.epsg.srid) # check ACL self.assertTrue(self.test_editor1.has_perm('core.change_group', mg)) self.assertFalse(self.test_editor2.has_perm('core.change_group', mg)) self.assertTrue( self.test_editor1.has_perm('core.add_project_to_group', mg)) self.assertTrue( self.test_editor2.has_perm('core.add_project_to_group', mg)) self.assertTrue(self.test_viewer1.has_perm('core.view_group', mg)) self.assertTrue(self.test_viewer1_2.has_perm('core.view_group', mg)) self.assertTrue( self.test_editor2_3.has_perm('core.add_project_to_group', mg)) self.assertTrue(self.test_viewer1_3.has_perm('core.view_group', mg)) # Test Update # ------------------------------ initial_form_data = copy.copy(form_data) name = 'Map group test update' form_data.update({ 'name': name, }) # Test ACL form_data.update({ 'editor_user': self.test_editor1_2.pk, 'editor2_user': self.test_editor2_2.pk, 'viewer_users': [self.test_viewer1_3.pk], 'editor_user_groups': [], 'viewer_user_groups': [] }) form = GroupForm(request=self.request, data=form_data, instance=mg, initial=initial_form_data) self.assertTrue(form.is_valid()) form.save() # Reload form db mg.refresh_from_db() self.assertEqual(mg.name, name) # check ACL self.assertFalse(self.test_editor1.has_perm('core.change_group', mg)) self.assertTrue(self.test_editor1_2.has_perm('core.change_group', mg)) self.assertFalse(self.test_editor2.has_perm('core.change_group', mg)) self.assertFalse(self.test_editor2_2.has_perm('core.change_group', mg)) self.assertTrue( self.test_editor1_2.has_perm('core.add_project_to_group', mg)) self.assertTrue( self.test_editor2_2.has_perm('core.add_project_to_group', mg)) self.assertTrue(self.test_viewer1_3.has_perm('core.view_group', mg)) self.assertFalse(self.test_viewer1_2.has_perm('core.view_group', mg)) self.assertFalse( self.test_editor2_3.has_perm('core.add_project_to_group', mg)) self.assertTrue(self.test_viewer1_3.has_perm('core.view_group', mg)) # Testing for editor level 1 use # ==================================================== # editor1 # ----------------- self.request.user = self.test_editor1 form = GroupForm(request=self.request) self.assertFalse(form.is_valid()) self.assertCountEqual(form.fields['editor2_user'].queryset, []) # editor1.2 # ----------------- self.request.user = self.test_editor1_2 form = GroupForm(request=self.request) self.assertFalse(form.is_valid()) # editor2.2 and editor2.3 self.assertEqual(len(form.fields['editor2_user'].queryset), 2) self.assertEqual( list(form.fields['editor2_user'].queryset.order_by('pk')), [self.test_editor2_2, self.test_editor2_3]) # Anonymous user always present # Anonymoususer, viewer2.3 self.assertEqual(len(form.fields['viewer_users'].queryset), 2) self.assertEqual( list(form.fields['viewer_users'].queryset.order_by('pk')), [self.anonymoususer, self.test_viewer1_3]) # Only editor and viewer user groups for test_editor1_2 self.assertEqual(len(form.fields['editor_user_groups'].queryset), 1) self.assertEqual(len(form.fields['viewer_user_groups'].queryset), 1)
def test_qdjango_project_form(self): """ Test qdjango project form, particular attention to ACL :return: None """ # set user as admin01 self.request.user = self.test_user1 # empty form form = QdjangoProjetForm(request=self.request, group=self.project_group) self.assertFalse(form.is_valid()) # upload qgis_file uf = create_dff_project('qgis_file') # Test Create # ========================================= form_data = { 'form_id': uf.form_id, 'feature_count_wms': 10, 'multilayer_query': 'single', 'multilayer_querybybbox': 'single', 'multilayer_querybypolygon': 'single', 'url_alias': 'test_url_alias_name' } form = QdjangoProjetForm(request=self.request, group=self.project_group, data=form_data) self.assertTrue(form.is_valid()) # check ACL users and group users # Check possible choices values # No editor1 self.assertEqual(len(form.fields['editor_user'].queryset), 0) # No editor2 self.assertEqual(len(form.fields['editor2_user'].queryset), 0) # only anonymous self.assertEqual(len(form.fields['viewer_users'].queryset), 1) self.assertEqual(form.fields['viewer_users'].queryset[0], self.anonymoususer) # No Editors group self.assertEqual(len(form.fields['editor_user_groups'].queryset), 0) # No Viewer group self.assertEqual(len(form.fields['viewer_user_groups'].queryset), 0) self.assertEqual(len(Project.objects.all()), 2) # Save project as into project CRUD views form.qgisProject.save(**form.cleaned_data) if not form.instance.pk: form.instance = form.qgisProject.instance form.save() self.assertEqual(len(Project.objects.all()), 3) # check for ProjectMapUrlAlias instance url_aliases = ProjectMapUrlAlias.objects.all() self.assertEqual(len(url_aliases), 1) self.assertEqual(url_aliases[0].alias, 'test_url_alias_name') # CHECK ACL users and Group users by map group # ================================================= assign_perm('core.change_group', self.test_editor1, self.project_group) assign_perm('core.add_project_to_group', self.test_editor2, self.project_group) assign_perm('core.view_group', self.test_viewer1_2, self.project_group) assign_perm('core.view_group', self.test_gu_viewer1, self.project_group) assign_perm('core.view_group', self.test_gu_viewer2, self.project_group) assign_perm('core.view_group', self.test_gu_editor1, self.project_group) assign_perm('core.add_project_to_group', self.test_gu_editor1, self.project_group) # Add ACL user and groups to form_data form_data.update({ 'editor_user': self.test_editor1.pk, 'editor2_user': self.test_editor2.pk, 'viewer_users': [self.test_viewer1_2.pk, self.anonymoususer.pk], 'editor_user_groups': [self.test_gu_editor1.pk], 'viewer_user_groups': [self.test_gu_viewer1.pk] }) # Update for check permission saved form = QdjangoProjetForm(request=self.request, group=self.project_group, data=form_data, instance=form.instance, initial={}) self.assertTrue(form.is_valid()) # check ACL users and group users # Check possible choices values # editor1 self.assertEqual(len(form.fields['editor_user'].queryset), 1) self.assertEqual(form.fields['editor_user'].queryset[0], self.test_editor1) # editor2 self.assertEqual(len(form.fields['editor2_user'].queryset), 1) self.assertEqual(form.fields['editor2_user'].queryset[0], self.test_editor2) # Viewer group GU-VIEWER1 GU-VIEWER2 self.assertEqual(len(form.fields['viewer_user_groups'].queryset), 2) # Editor group GU-EDITOR1 self.assertEqual(len(form.fields['editor_user_groups'].queryset), 1) # Save project as into project CRUD views form.qgisProject.save(**form.cleaned_data) if not form.instance.pk: form.instance = form.qgisProject.instance form.save() # Check ACL after save p = Project.objects.get(pk=form.instance.pk) self.assertTrue(self.test_editor1.has_perm('qdjango.change_project', p)) self.assertFalse( self.test_editor1_2.has_perm('qdjango.change_project', p)) self.assertTrue(self.test_editor2.has_perm('qdjango.change_project', p)) self.assertTrue(self.test_viewer1.has_perm('qdjango.view_project', p)) self.assertTrue(self.anonymoususer.has_perm('qdjango.view_project', p)) self.assertFalse( self.test_viewer1_3.has_perm('qdjango.view_project', p)) # by viewer groups self.assertTrue(self.test_viewer1_2.has_perm('qdjango.view_project', p)) # by editor groups self.assertTrue( self.test_editor2_3.has_perm('qdjango.change_project', p)) # CHECK GROUP PROPAGATION OPTIONS # only new viewers and new viwer users group # =========================================== # upload header_logo_image uf = create_dff_image(field_name='header_logo_img') # Update self.project_group # ------------------------------ form_data = { 'title': self.project_group.title, 'name': self.project_group.name, 'description': self.project_group.description, 'srid': self.project_group.srid_id, 'form_id': uf.form_id, 'lang': 'it', 'mapcontrols': [mp.pk for mp in self.map_controls] } initial_form_data = copy(form_data) initial_form_data.update({ 'editor_user': self.test_editor1.pk, 'editor2_user': self.test_editor2.pk, 'viewer_users': [self.test_viewer1_2.pk], 'editor_user_groups': [self.test_gu_editor1.pk], 'viewer_user_groups': [self.test_gu_viewer1.pk, self.test_gu_viewer2.pk] }) # create a ne user new_viewer = User.objects.create_user(username='******', password='******') new_viewer.groups.add(AuthGroup.objects.get(name=G3W_VIEWER1)) # Test ACL form_data.update({ 'editor_user': self.test_editor1_2.pk, 'editor2_user': self.test_editor2_3.pk, 'viewer_users': [self.test_viewer1.pk, self.test_viewer1_2.pk, new_viewer.pk], 'editor_user_groups': [self.test_gu_editor1.pk, self.test_gu_editor2.pk], 'viewer_user_groups': [self.test_gu_viewer1.pk, self.test_gu_viewer2.pk] }) form = GroupForm(request=self.request, data=form_data, instance=self.project_group, initial=initial_form_data) self.assertTrue(form.is_valid()) form.save() p.refresh_from_db() self.assertFalse( self.test_editor1.has_perm('qdjango.change_project', p)) self.assertTrue( self.test_editor1_2.has_perm('qdjango.change_project', p)) self.assertTrue(self.test_editor2.has_perm('qdjango.change_project', p)) self.assertTrue( self.test_editor2_3.has_perm('qdjango.change_project', p)) self.assertTrue(self.test_viewer1.has_perm('qdjango.view_project', p)) self.assertTrue(self.test_viewer1_2.has_perm('qdjango.view_project', p)) self.assertFalse(new_viewer.has_perm('qdjango.view_project', p)) self.assertTrue(self.anonymoususer.has_perm('qdjango.view_project', p)) self.assertFalse( self.test_viewer1_3.has_perm('qdjango.view_project', p)) # TEST PROPAGATE PERMISSION FROM GROUP TO PROJECT # New Viewer and Viewer groups # ================================================ # Reset permission on group for test propagation remove_perm('core.view_group', self.test_gu_viewer2, self.project_group) # add propagation form_data.update({'propagate_viewers': 1}) # Run again form form = GroupForm(request=self.request, data=form_data, instance=self.project_group, initial=initial_form_data) self.assertTrue(form.is_valid()) form.save() self.assertTrue(new_viewer.has_perm('qdjango.view_project', p))