def clean(self): super().clean() if self.cleaned_data.get( 'DELETE') and not self.instance.can_manager_delete: raise SuspiciousOperation("Deleting course type not allowed")
def get_filters(self, request): lookup_params = self.params.copy() # a dictionary of the query string use_distinct = False # Remove all the parameters that are globally and systematically # ignored. for ignored in IGNORED_PARAMS: if ignored in lookup_params: del lookup_params[ignored] # Normalize the types of keys for key, value in lookup_params.items(): if not isinstance(key, str): # 'key' will be used as a keyword argument later, so Python # requires it to be a string. del lookup_params[key] lookup_params[smart_str(key)] = value if not self.model_admin.lookup_allowed(key, value): raise SuspiciousOperation("Filtering by %s not allowed" % key) filter_specs = [] if self.list_filter: for list_filter in self.list_filter: if callable(list_filter): # This is simply a custom list filter class. spec = list_filter(request, lookup_params, self.model, self.model_admin) else: field_path = None if isinstance(list_filter, (tuple, list)): # This is a custom FieldListFilter class for a given field. field, field_list_filter_class = list_filter else: # This is simply a field name, so use the default # FieldListFilter class that has been registered for # the type of the given field. field, field_list_filter_class = list_filter, FieldListFilter.create if not isinstance(field, models.Field): field_path = field field = get_fields_from_path(self.model, field_path)[-1] spec = field_list_filter_class(field, request, lookup_params, self.model, self.model_admin, field_path=field_path) # Check if we need to use distinct() use_distinct = (use_distinct or lookup_needs_distinct(self.lookup_opts, field_path)) if spec and spec.has_output(): filter_specs.append(spec) # At this point, all the parameters used by the various ListFilters # have been removed from lookup_params, which now only contains other # parameters passed via the query string. We now loop through the # remaining parameters both to ensure that all the parameters are valid # fields and to determine if at least one of them needs distinct(). If # the lookup parameters aren't real fields, then bail out. try: for key, value in lookup_params.items(): lookup_params[key] = prepare_lookup_value(key, value) use_distinct = (use_distinct or lookup_needs_distinct(self.lookup_opts, key)) return filter_specs, bool(filter_specs), lookup_params, use_distinct except FieldDoesNotExist, e: raise IncorrectLookupParameters(e)
def create_classification_entry(cls, name, rank_id, parent, language, layout=None, descriptors=None): """ Create a new classification entry with a unique name. The level must be greater than its parent level. :param name: Unique classification entry name. :param rank_id: Classification rank with a greater level than its parent rank. :param parent: None or valid Classification entry instance. :param language: Language code of the primary synonym created with name. :param layout: Layout instance or None. :param descriptors: Descriptors values or None if no layout. :return: None or new Classification entry instance. """ if ClassificationEntry.objects.filter(name=name).exists(): raise SuspiciousOperation( _("A classification entry with this name already exists")) try: classification_rank = ClassificationRank.objects.get(id=rank_id) except ClassificationRank.DoesNotExist: raise SuspiciousOperation( _("The given classification rank does not exists")) if parent: if parent.rank.classification_id != classification_rank.classification_id: raise SuspiciousOperation( _("The parent and the children classification rank must be of the same nature" )) if parent.rank.level >= classification_rank.level: raise SuspiciousOperation( _("The rank level of the parent must be lesser than the rank level of the new classification entry" )) classification_entry = ClassificationEntry() classification_entry.name = name classification_entry.rank = classification_rank classification_entry.parent = parent classification_entry.parent_list = [] classification_entry.layout = layout if parent: try: ClassificationEntryManager.update_parents( classification_entry, parent) except ClassificationEntry.DoesNotExist: return None # descriptors if layout is not None: descriptors_builder = DescriptorsBuilder(classification_entry) descriptors_builder.check_and_update(layout, descriptors) classification_entry.descriptors = descriptors_builder.descriptors classification_entry.save() # first name a primary synonym primary_synonym = ClassificationEntrySynonym( entity_id=classification_entry.id, name=name, synonym_type_id=localsettings. synonym_type_classification_entry_name, language=language) primary_synonym.save() return classification_entry
def get_object(self, uid, user_id): try: return MLModel.create(**self.get_document(ObjectId(uid), user_id)) except (TypeError, InvalidId): raise SuspiciousOperation('Invalid ID')
def validate_team(request): if request.method != "POST": raise SuspiciousOperation( "Illegal request; This is event is reported and you will be blocked from any further access to this website" ) team = request.POST.get('team', None) user = User.objects.get(username=request.user) code = request.POST.get('code', None) event = request.POST.get('event', None) email = request.POST.get('email', None) catg = request.POST.get('catg', None) print team, user, code, event, email, catg team = team.upper() #code = code.upper() team_leader = user.get_full_name() category_dict = { 'Indian Vocal Solo ': 0, 'Western Vocal Solo': 1, 'Instrumental Solo': 2, 'Group Musical': 3, None: None } catg_choice = Participant.dhwanit_category # because one team per user per event is allowed event_obj = Event.objects.get(name=event) is_taken = Team.objects.filter(created_by=user).filter( event_name=event_obj).exists() or Team.objects.filter( team_pass=code).exists( ) #returns true if logged in user has already created a team if is_taken: data = {'is_taken': is_taken} return JsonResponse(data) # If team doesn't already exist, allow user to create one if not is_taken: #participant cannot register with null value of code if team and code: does_exist = Team.objects.filter(team_name=team).filter( team_pass=code).exists( ) # returns true of team and code pair already exists if not does_exist and catg: team_obj = Team( team_name=team, team_pass=code, created_by=user, event_name=event_obj, category=catg_choice[category_dict[str(catg)]][0]) team_obj.save( ) # Team leader is not added untill he submits his details in join team module response = send_team_code(email, team_leader, code, event) if response: print "added and mail sent" if not does_exist and not catg: team_obj = Team(team_name=team, team_pass=code, created_by=user, event_name=event_obj, category=None) team_obj.save( ) # Team leader is not added untill he submits his details in join team module response = send_team_code(email, team_leader, code, event) if response: print "added and mail sent" else: is_taken = True data = {'is_taken': is_taken} return JsonResponse(data)
def suspicious(request): raise SuspiciousOperation('Raising exception to test logging.')
def sign_up(request): if not settings.RELATE_REGISTRATION_ENABLED: raise SuspiciousOperation( _("self-registration is not enabled")) if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): if get_user_model().objects.filter( username=form.cleaned_data["username"]).count(): messages.add_message(request, messages.ERROR, _("A user with that username already exists.")) elif get_user_model().objects.filter( email__iexact=form.cleaned_data["email"]).count(): messages.add_message(request, messages.ERROR, _("That email address is already in use. " "Would you like to " "<a href='%s'>reset your password</a> instead?") % reverse( "relate-reset_password")), else: email = form.cleaned_data["email"] user = get_user_model()( email=email, username=form.cleaned_data["username"]) user.set_unusable_password() user.status = user_status.unconfirmed user.sign_in_key = make_sign_in_key(user) user.save() from django.template.loader import render_to_string message = render_to_string("course/sign-in-email.txt", { "user": user, "sign_in_uri": request.build_absolute_uri( reverse( "relate-reset_password_stage2", args=(user.id, user.sign_in_key,)) + "?to_profile=1"), "home_uri": request.build_absolute_uri( reverse("relate-home")) }) from django.core.mail import send_mail send_mail( string_concat("[", _("RELATE"), "] ", _("Verify your email")), message, settings.ROBOT_EMAIL_FROM, recipient_list=[email]) messages.add_message(request, messages.INFO, _("Email sent. Please check your email and click " "the link.")) return redirect("relate-home") else: form = SignUpForm() return render(request, "generic-form.html", { "form_description": _("Sign up"), "form": form })
def add_question(request, id): """ Adds the question to test :param request: :param id: id of the test :return: """ test = Test.objects.get(id=id) if test.test is None or test.test == b'': exam_test = ExamTest() else: exam_test = pickle.loads(test.test) if request.user != test.author: raise SuspiciousOperation("Некорректный id теста") if "type" in request.POST and int(request.POST["type"]) in (1, 2, 3): question_type = TestType(int(request.POST["type"])) if "question" in request.POST: question = Question(request.POST["question"], question_type) else: question = Question(None, question_type) if "image" in request.FILES: image = TestImage.objects.get_or_create( image=request.FILES["image"]) image_id = image[0].id else: image_id = None question.set_image(image_id) if question_type is TestType.CLOSE_TYPE_SEVERAL_CORRECT_ANSWERS: i = 1 while "answer" + str(i) in request.POST: question.add_new_answer( CloseAnswer(answer=request.POST["answer" + str(i)], is_correct=str(i) in request.POST.getlist("trueAnswer"))) i += 1 elif question_type is TestType.CLOSE_TYPE_ONE_CORRECT_ANSWER: i = 1 while "answer" + str(i) in request.POST: question.add_new_answer( CloseAnswer( answer=request.POST["answer" + str(i)], is_correct=str(i) == request.POST["trueAnswer"])) i += 1 elif question_type is TestType.OPEN_TYPE: question.add_new_answer(Answer(request.POST["openAnswer"])) exam_test.add_question(question) test.test = pickle.dumps(exam_test) test.save() request.user.rating += 1 request.user.save() return HttpResponseRedirect(reverse("edit_test", args=[id])) else: return render( request, "exam/add_question.html", { "number_of_question": len(exam_test.get_questions()) + 1, "type_list": TYPE_LIST, "test_id": id })
def edit_question(request, id, number): """ Edits the question in the test :param request: :param id: id of test :param number: number of question :return: """ id = int(id) number = int(number) test = Test.objects.get(id=id) if test.test is None or test.test == b'': raise SuspiciousOperation("Некорректный запрос") exam_test = pickle.loads(test.test) if "type" in request.POST and int(request.POST["type"]) in (1, 2, 3): question_type = TestType(int(request.POST["type"])) if "question" in request.POST: question = Question(request.POST["question"], question_type) else: question = Question(None, question_type) if "image" in request.FILES: image = TestImage.objects.get_or_create( image=request.FILES["image"]) question.set_image(image[0].id) else: question.set_image(exam_test.get_questions()[number - 1].get_image()) if question_type is TestType.CLOSE_TYPE_SEVERAL_CORRECT_ANSWERS: i = 1 while "answer" + str(i) in request.POST: question.add_new_answer( CloseAnswer(answer=request.POST["answer" + str(i)], is_correct=str(i) in request.POST.getlist("trueAnswer"))) i += 1 elif question_type is TestType.CLOSE_TYPE_ONE_CORRECT_ANSWER: i = 1 while "answer" + str(i) in request.POST: question.add_new_answer( CloseAnswer( answer=request.POST["answer" + str(i)], is_correct=str(i) == request.POST["trueAnswer"])) i += 1 elif question_type is TestType.OPEN_TYPE: question.add_new_answer(Answer(request.POST["openAnswer"])) exam_test.get_questions()[number - 1] = question test.test = pickle.dumps(exam_test) test.save() request.user.rating += 1 request.user.save() return HttpResponseRedirect(reverse("edit_test", args=[id])) else: question = exam_test.get_questions()[number - 1] if question.get_image(): image_test = TestImage.objects.get(id=question.get_image()) image = image_test.image.url else: image = None return render( request, "exam/edit_question.html", { "number_of_question": number, "operation": "edit_test_edit_question", "type_list": TYPE_LIST, "test_id": id, "question": question, "image": image })
def revert(request): if not request.is_ajax() or not request.POST: raise Http404 version_id = request.POST['id'] document_url_title = request.POST['url_title'] document = get_object_or_404(Document, url_title=document_url_title) check_permissions(document, request.user, [document.edit_permission_name]) versions = Version.objects.get_for_object(document) if not document.can_be_reverted: raise SuspiciousOperation('This Document can not be reverted!') # find the we want to revert to revert_version = None for version in versions: if version.pk == int(version_id): revert_version = version break if revert_version is None: # user supplied version_id that does not exist raise SuspiciousOperation('Could not find document') revert_version.revision.revert(delete=False) fields = revert_version.field_dict document_class = ContentType.objects.get_for_id( fields.pop('polymorphic_ctype_id')).model_class() # Remove all references to parent objects, rename ForeignKeyFields, extract ManyToManyFields. new_fields = fields.copy() many_to_many_fields = {} for key in fields.keys(): if "_ptr" in key: del new_fields[key] continue try: field = getattr(document_class, key).field except AttributeError: continue if isinstance(field, models.ManyToManyField): many_to_many_fields[key] = fields[key] else: new_fields[field.attname] = fields[key] del new_fields[key] reverted_document = document_class(**new_fields) with transaction.atomic(), revisions.create_revision(): reverted_document.save() # Restore ManyToManyFields for key in many_to_many_fields.keys(): getattr(reverted_document, key).clear() getattr(reverted_document, key).add(*many_to_many_fields[key]) revisions.set_user(request.user) revisions.set_comment( _('reverted to revision \"{revision_comment}\" (at {date})'.format( revision_comment=revert_version.revision.comment, date=datetime.utcnow().strftime("%Y-%m-%d %H:%M"), ))) return HttpResponse(reverse('versions', args=[reverted_document.url_title]))
def folder(request, type, id=""): if type not in FOLDER_FILE_TYPE: raise SuspiciousOperation('Invalid type') if (request.POST.get("action") and request.POST.get("action") == "delete"): folder = get_object_or_404(UserFolder, id=request.POST['id']) if (folder.name == 'home' or (request.user != folder.owner and not request.user.is_superuser)): messages.add_message(request, messages.ERROR, _(u'You cannot delete home folder.')) raise PermissionDenied else: folder.delete() page = request.GET.get('page', 1) full_path = request.get_full_path().replace("?page=%s" % page, "").replace( "&page=%s" % page, "").replace("&infinite=true", "") if page else "" form = UserFolderForm() user_home_folder = get_object_or_404(UserFolder, name="home", owner=request.user) folders = get_folders(request, page) current_session_folder = get_current_session_folder(request) current_folder = get_object_or_404( UserFolder, id=id) if id != "" else (current_session_folder) request.session['current_session_folder'] = current_folder.name if (request.user != current_folder.owner and not request.user.groups.filter(name__in=[ name[0] for name in current_folder.groups.values_list('name') ]).exists() and not request.user.is_superuser): messages.add_message(request, messages.ERROR, _(u'You cannot see this folder.')) raise PermissionDenied if (request.POST.get("name") and request.POST.get("name") != ""): form, current_folder = edit_folder(request, current_folder) folders = get_folders(request, page) if request.GET.get('infinite', False): return render(request, 'podfile/infinite_folders.html', { 'list_folder': folders, "type": type, "full_path": full_path }) list_file = current_folder.customimagemodel_set.all() if ( type == "image") else current_folder.customfilemodel_set.all() return render( request, 'podfile/list_folder.html', { 'list_folder': folders, 'form': form, "current_folder": current_folder, "list_file": list_file, "type": type, "full_path": full_path, "user_home_folder": user_home_folder })
def authenticate_app_ssh(public_keys, signatures, timestamp, body): """Authenticate request signature If the client sends more then 20 key signature pairs, we raise a SuspiciousOperation to prevent DOS. Look up all of the public keys send with this request in our database. Verify the signature send by the client for those public keys we know about. Raise PermissionDenied for invalid signatures. If we find no public key in our database, we raise a PermissionDenied. If we find multiple valid signatures using public keys belonging to different applications, we raise PermissionDenied. The different applications likely have different permissions and we don't want to guess which to enforce. Return the app the user authenticated to """ def verify_signature(public_key, signature): """Verify a single signature Raise PermissionDenied if the signature is invalid Return the public key on success """ expected_message = calc_message(timestamp, body) if not public_key.load().verify_ssh_sig(data=expected_message.encode(), msg=Message( b64decode(signature))): raise PermissionDenied('Invalid signature') return public_key key_signatures = dict(zip(public_keys.split(','), signatures.split(','))) if len(key_signatures) > 20: raise SuspiciousOperation('Over 20 signatures in one request') verified_keys = { verify_signature(public_key, key_signatures[public_key.key_base64]) for public_key in PublicKey.objects.filter( key_base64__in=key_signatures.keys()) } if not verified_keys: raise PermissionDenied('No known public key found') applications = {key.application for key in verified_keys} if len(applications) > 1: raise PermissionDenied( 'Valid signatures for more than one application received: ' + ', '.join([str(key) for key in verified_keys]) + '. It is unclear which ACLs to enforce, giving up.') application = applications.pop() if not application: # This can never happen as the PublicKey.application is not nullable, # this is only a safety net in case this field gets changed. raise SuspiciousOperation('We did not end up with an application') return application
def grade_flow_page(pctx, flow_session_id, page_ordinal): page_ordinal = int(page_ordinal) if pctx.role not in [ participation_role.instructor, participation_role.teaching_assistant]: raise PermissionDenied( _("must be instructor or TA to view grades")) flow_session = get_object_or_404(FlowSession, id=int(flow_session_id)) if flow_session.course.pk != pctx.course.pk: raise SuspiciousOperation( _("Flow session not part of specified course")) if flow_session.participation is None: raise SuspiciousOperation( _("Cannot grade anonymous session")) fpctx = FlowPageContext(pctx.repo, pctx.course, flow_session.flow_id, page_ordinal, participation=flow_session.participation, flow_session=flow_session) if fpctx.page_desc is None: raise http.Http404() # {{{ enable flow session zapping all_flow_sessions = list(FlowSession.objects .filter( course=pctx.course, flow_id=flow_session.flow_id, participation__isnull=False, in_progress=flow_session.in_progress) .order_by( "participation__user__last_name", "start_time")) next_flow_session_id = None prev_flow_session_id = None for i, other_flow_session in enumerate(all_flow_sessions): if other_flow_session.pk == flow_session.pk: if i > 0: prev_flow_session_id = all_flow_sessions[i-1].id if i + 1 < len(all_flow_sessions): next_flow_session_id = all_flow_sessions[i+1].id # }}} # {{{ reproduce student view form = None feedback = None answer_data = None grade_data = None most_recent_grade = None if fpctx.page.expects_answer(): if fpctx.prev_answer_visit is not None: answer_data = fpctx.prev_answer_visit.answer most_recent_grade = fpctx.prev_answer_visit.get_most_recent_grade() if most_recent_grade is not None: feedback = get_feedback_for_grade(most_recent_grade) grade_data = most_recent_grade.grade_data else: feedback = None grade_data = None else: feedback = None from course.page.base import PageBehavior page_behavior = PageBehavior( show_correctness=True, show_answer=False, may_change_answer=False) form = fpctx.page.make_form( fpctx.page_context, fpctx.page_data.data, answer_data, page_behavior) if form is not None: form_html = fpctx.page.form_to_html( pctx.request, fpctx.page_context, form, answer_data) else: form_html = None # }}} # {{{ grading form if (fpctx.page.expects_answer() and fpctx.page.is_answer_gradable() and fpctx.prev_answer_visit is not None and not flow_session.in_progress): request = pctx.request if pctx.request.method == "POST": grading_form = fpctx.page.post_grading_form( fpctx.page_context, fpctx.page_data, grade_data, request.POST, request.FILES) if grading_form.is_valid(): grade_data = fpctx.page.update_grade_data_from_grading_form( fpctx.page_context, fpctx.page_data, grade_data, grading_form, request.FILES) feedback = fpctx.page.grade( fpctx.page_context, fpctx.page_data, answer_data, grade_data) if feedback is not None: correctness = feedback.correctness else: correctness = None if feedback is not None: feedback_json, bulk_feedback_json = feedback.as_json() else: feedback_json = bulk_feedback_json = None most_recent_grade = FlowPageVisitGrade( visit=fpctx.prev_answer_visit, grader=pctx.request.user, graded_at_git_commit_sha=pctx.course_commit_sha, grade_data=grade_data, max_points=fpctx.page.max_points(fpctx.page_data), correctness=correctness, feedback=feedback_json) most_recent_grade.save() update_bulk_feedback( fpctx.prev_answer_visit.page_data, most_recent_grade, bulk_feedback_json) grading_rule = get_session_grading_rule( flow_session, flow_session.participation.role, fpctx.flow_desc, get_now_or_fake_time(request)) from course.flow import grade_flow_session grade_flow_session(fpctx, flow_session, grading_rule) else: grading_form = fpctx.page.make_grading_form( fpctx.page_context, fpctx.page_data, grade_data) else: grading_form = None if grading_form is not None: from crispy_forms.layout import Submit grading_form.helper.add_input( Submit( "submit", _("Submit"), accesskey="s", css_class="col-lg-offset-2 relate-grading-save-button")) grading_form_html = fpctx.page.grading_form_to_html( pctx.request, fpctx.page_context, grading_form, grade_data) else: grading_form_html = None # }}} # {{{ compute points_awarded max_points = None points_awarded = None if (fpctx.page.expects_answer() and fpctx.page.is_answer_gradable()): max_points = fpctx.page.max_points(fpctx.page_data) if feedback is not None and feedback.correctness is not None: points_awarded = max_points * feedback.correctness # }}} grading_rule = get_session_grading_rule( flow_session, flow_session.participation.role, fpctx.flow_desc, get_now_or_fake_time(pctx.request)) if grading_rule.grade_identifier is not None: grading_opportunity = get_flow_grading_opportunity( pctx.course, flow_session.flow_id, fpctx.flow_desc, grading_rule) else: grading_opportunity = None return render_course_page( pctx, "course/grade-flow-page.html", { "flow_identifier": fpctx.flow_id, "flow_session": flow_session, "flow_desc": fpctx.flow_desc, "ordinal": fpctx.ordinal, "page_data": fpctx.page_data, "body": fpctx.page.body( fpctx.page_context, fpctx.page_data.data), "form": form, "form_html": form_html, "feedback": feedback, "max_points": max_points, "points_awarded": points_awarded, "most_recent_grade": most_recent_grade, "grading_opportunity": grading_opportunity, "prev_flow_session_id": prev_flow_session_id, "next_flow_session_id": next_flow_session_id, "grading_form": grading_form, "grading_form_html": grading_form_html, })
def evaluation_edit(request, evaluation_id): evaluation = get_object_or_404(Evaluation, id=evaluation_id) # check rights if not (evaluation.is_user_editor_or_delegate(request.user) and evaluation.state == 'prepared'): raise PermissionDenied post_operation = request.POST.get('operation') if request.POST else None preview = post_operation == 'preview' InlineContributionFormset = inlineformset_factory( Evaluation, Contribution, formset=ContributionFormSet, form=EditorContributionForm, extra=1) evaluation_form = EvaluationForm(request.POST or None, instance=evaluation) formset = InlineContributionFormset(request.POST or None, instance=evaluation, form_kwargs={'evaluation': evaluation}) forms_are_valid = evaluation_form.is_valid() and formset.is_valid() if forms_are_valid and not preview: if post_operation not in ('save', 'approve'): raise SuspiciousOperation("Invalid POST operation") form_has_changed = evaluation_form.has_changed( ) or formset.has_changed() evaluation_form.save() formset.save() if post_operation == 'approve': evaluation.editor_approve() evaluation.save() if form_has_changed: messages.success( request, _("Successfully updated and approved evaluation.")) else: messages.success(request, _("Successfully approved evaluation.")) else: messages.success(request, _("Successfully updated evaluation.")) return redirect('contributor:index') preview_html = None if preview and forms_are_valid: preview_html = render_preview(request, formset, evaluation_form, evaluation) if not forms_are_valid and (evaluation_form.errors or formset.errors): if preview: messages.error( request, _("The preview could not be rendered. Please resolve the errors shown below." )) else: messages.error( request, _("The form was not saved. Please resolve the errors shown below." )) sort_formset(request, formset) template_data = dict(form=evaluation_form, formset=formset, evaluation=evaluation, editable=True, preview_html=preview_html) return render(request, "contributor_evaluation_form.html", template_data)
def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse: if getattr(response, "asynchronous", False): # This special Tornado "asynchronous" response is # discarded after going through this code path as Tornado # intends to block, so we stop here to avoid unnecessary work. return response try: request.get_host() except DisallowedHost: # If we get a DisallowedHost exception trying to access # the host, (1) the request is failed anyway and so the # below code will do nothing, and (2) the below will # trigger a recursive exception, breaking things, so we # just return here. return response if (not request.path.startswith("/static/") and not request.path.startswith("/api/") and not request.path.startswith("/json/")): subdomain = get_subdomain(request) if subdomain != Realm.SUBDOMAIN_FOR_ROOT_DOMAIN: try: get_realm(subdomain) except Realm.DoesNotExist: return render(request, "zerver/invalid_realm.html", status=404) """ If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie or delete the session cookie if the session has been emptied. """ try: accessed = request.session.accessed modified = request.session.modified empty = request.session.is_empty() except AttributeError: pass else: # First check if we need to delete this cookie. # The session should be deleted only if the session is entirely empty if settings.SESSION_COOKIE_NAME in request.COOKIES and empty: response.delete_cookie( settings.SESSION_COOKIE_NAME, path=settings.SESSION_COOKIE_PATH, domain=settings.SESSION_COOKIE_DOMAIN, ) else: if accessed: patch_vary_headers(response, ('Cookie',)) if (modified or settings.SESSION_SAVE_EVERY_REQUEST) and not empty: if request.session.get_expire_at_browser_close(): max_age = None expires = None else: max_age = request.session.get_expiry_age() expires_time = time.time() + max_age expires = http_date(expires_time) # Save the session data and refresh the client cookie. # Skip session save for 500 responses, refs #3881. if response.status_code != 500: try: request.session.save() except UpdateError: raise SuspiciousOperation( "The request's session was deleted before the " "request completed. The user may have logged " "out in a concurrent request, for example." ) host = request.get_host().split(':')[0] # The subdomains feature overrides the # SESSION_COOKIE_DOMAIN setting, since the setting # is a fixed value and with subdomains enabled, # the session cookie domain has to vary with the # subdomain. session_cookie_domain = host response.set_cookie( settings.SESSION_COOKIE_NAME, request.session.session_key, max_age=max_age, expires=expires, domain=session_cookie_domain, path=settings.SESSION_COOKIE_PATH, secure=settings.SESSION_COOKIE_SECURE or None, httponly=settings.SESSION_COOKIE_HTTPONLY or None, samesite=settings.SESSION_COOKIE_SAMESITE, ) return response
def _check_non_existing_trace(name, full_path): qs = models.PendingTrace.objects.filter(name=name, full_path=full_path) if qs.count() != 0: raise SuspiciousOperation("Test with trace already exists")
def get_list_queryset(self, queryset): lookup_params = dict([ (smart_str(k)[len(FILTER_PREFIX):], v) for k, v in self.admin_view.params.items() if smart_str(k).startswith(FILTER_PREFIX) and v != '' ]) for p_key, p_val in iteritems(lookup_params): if p_val == "False": lookup_params[p_key] = False use_distinct = False # for clean filters self.admin_view.has_query_param = bool(lookup_params) self.admin_view.clean_query_url = self.admin_view.get_query_string( remove=[ k for k in self.request.GET.keys() if k.startswith(FILTER_PREFIX) ]) # Normalize the types of keys if not self.free_query_filter: for key, value in lookup_params.items(): if not self.lookup_allowed(key, value): raise SuspiciousOperation("Filtering by %s not allowed" % key) self.filter_specs = [] if self.list_filter: for list_filter in self.list_filter: if callable(list_filter): # This is simply a custom list filter class. spec = list_filter(self.request, lookup_params, self.model, self) else: field_path = None field_parts = [] if isinstance(list_filter, (tuple, list)): # This is a custom FieldListFilter class for a given field. field, field_list_filter_class = list_filter else: # This is simply a field name, so use the default # FieldListFilter class that has been registered for # the type of the given field. field, field_list_filter_class = list_filter, filter_manager.create if not isinstance(field, models.Field): field_path = field field_parts = get_fields_from_path( self.model, field_path) field = field_parts[-1] spec = field_list_filter_class(field, self.request, lookup_params, self.model, self.admin_view, field_path=field_path) if len(field_parts) > 1: # Add related model name to title spec.title = "%s %s" % (field_parts[-2].name, spec.title) # Check if we need to use distinct() use_distinct = (use_distinct or lookup_needs_distinct( self.opts, field_path)) if spec and spec.has_output(): try: new_qs = spec.do_filte(queryset) except ValidationError as e: new_qs = None self.admin_view.message_user( _("<b>Filtering error:</b> %s") % e.messages[0], 'error') if new_qs is not None: queryset = new_qs self.filter_specs.append(spec) self.has_filters = bool(self.filter_specs) self.admin_view.filter_specs = self.filter_specs obj = filter(lambda f: f.is_used, self.filter_specs) if six.PY3: obj = list(obj) self.admin_view.used_filter_num = len(obj) try: for key, value in lookup_params.items(): use_distinct = (use_distinct or lookup_needs_distinct(self.opts, key)) except FieldDoesNotExist as e: raise IncorrectLookupParameters(e) try: # fix a bug by david: In demo, quick filter by IDC Name() cannot be used. if isinstance(queryset, models.query.QuerySet) and lookup_params: new_lookup_parames = dict() for k, v in lookup_params.iteritems(): list_v = v.split(',') if len(list_v) > 0: new_lookup_parames.update({k: list_v}) else: new_lookup_parames.update({k: v}) queryset = queryset.filter(**new_lookup_parames) except (SuspiciousOperation, ImproperlyConfigured): raise except Exception as e: raise IncorrectLookupParameters(e) else: if not isinstance(queryset, models.query.QuerySet): pass query = self.request.GET.get(SEARCH_VAR, '') # Apply keyword searches. def construct_search(field_name): if field_name.startswith('^'): return "%s__istartswith" % field_name[1:] elif field_name.startswith('='): return "%s__iexact" % field_name[1:] elif field_name.startswith('@'): return "%s__search" % field_name[1:] else: return "%s__icontains" % field_name if self.search_fields and query: orm_lookups = [ construct_search(str(search_field)) for search_field in self.search_fields ] for bit in query.split(): or_queries = [ models.Q(**{orm_lookup: bit}) for orm_lookup in orm_lookups ] queryset = queryset.filter(reduce(operator.or_, or_queries)) if not use_distinct: for search_spec in orm_lookups: if lookup_needs_distinct(self.opts, search_spec): use_distinct = True break self.admin_view.search_query = query if use_distinct: return queryset.distinct() else: return queryset
def view_grades_by_opportunity(pctx, opp_id): from course.views import get_now_or_fake_time now_datetime = get_now_or_fake_time(pctx.request) if pctx.role not in [ participation_role.instructor, participation_role.teaching_assistant ]: raise PermissionDenied(_("must be instructor or TA to view grades")) opportunity = get_object_or_404(GradingOpportunity, id=int(opp_id)) if pctx.course != opportunity.course: raise SuspiciousOperation(_("opportunity from wrong course")) # {{{ batch sessions form batch_session_ops_form = None if pctx.role == participation_role.instructor and opportunity.flow_id: cursor = connection.cursor() cursor.execute( "select distinct access_rules_tag from course_flowsession " "where course_id = %s and flow_id = %s " "order by access_rules_tag", (pctx.course.id, opportunity.flow_id)) session_rule_tags = [ mangle_session_access_rule_tag(row[0]) for row in cursor.fetchall() ] request = pctx.request if request.method == "POST": batch_session_ops_form = ModifySessionsForm( session_rule_tags, request.POST, request.FILES) if "expire" in request.POST: op = "expire" elif "end" in request.POST: op = "end" elif "regrade" in request.POST: op = "regrade" elif "recalculate" in request.POST: op = "recalculate" else: raise SuspiciousOperation(_("invalid operation")) if batch_session_ops_form.is_valid(): rule_tag = batch_session_ops_form.cleaned_data["rule_tag"] past_due_only = batch_session_ops_form.cleaned_data[ "past_due_only"] if rule_tag == RULE_TAG_NONE_STRING: rule_tag = None try: if op == "expire": count = expire_in_progress_sessions( pctx.repo, pctx.course, opportunity.flow_id, rule_tag, now_datetime, past_due_only=past_due_only) messages.add_message( pctx.request, messages.SUCCESS, _("%d session(s) expired.") % count) elif op == "end": count = finish_in_progress_sessions( pctx.repo, pctx.course, opportunity.flow_id, rule_tag, now_datetime, past_due_only=past_due_only) messages.add_message(pctx.request, messages.SUCCESS, _("%d session(s) ended.") % count) elif op == "regrade": count = regrade_ended_sessions(pctx.repo, pctx.course, opportunity.flow_id, rule_tag) messages.add_message( pctx.request, messages.SUCCESS, _("%d session(s) regraded.") % count) elif op == "recalculate": count = recalculate_ended_sessions( pctx.repo, pctx.course, opportunity.flow_id, rule_tag) messages.add_message( pctx.request, messages.SUCCESS, _("Grade recalculated for %d session(s).") % count) else: raise SuspiciousOperation("invalid operation") except Exception as e: messages.add_message( pctx.request, messages.ERROR, string_concat( pgettext_lazy("Starting of Error message", "Error"), ": %(err_type)s %(err_str)s") % { "err_type": type(e).__name__, "err_str": str(e) }) raise else: batch_session_ops_form = ModifySessionsForm(session_rule_tags) # }}} # NOTE: It's important that these queries are sorted consistently, # also consistently with the code below. participations = list( Participation.objects.filter( course=pctx.course, status=participation_status.active).order_by( "id").select_related("user")) grade_changes = list( GradeChange.objects.filter(opportunity=opportunity).order_by( "participation__id", "grade_time").select_related("participation").select_related( "participation__user").select_related("opportunity")) idx = 0 finished_sessions = 0 total_sessions = 0 grade_table = [] for participation in participations: while (idx < len(grade_changes) and grade_changes[idx].participation.id < participation.id): idx += 1 my_grade_changes = [] while (idx < len(grade_changes) and grade_changes[idx].participation.pk == participation.pk): my_grade_changes.append(grade_changes[idx]) idx += 1 state_machine = GradeStateMachine() state_machine.consume(my_grade_changes) if opportunity.flow_id: flow_sessions = (FlowSession.objects.filter( participation=participation, flow_id=opportunity.flow_id, ).order_by("start_time")) for fsession in flow_sessions: total_sessions += 1 if not fsession.in_progress: finished_sessions += 1 else: flow_sessions = None grade_table.append( OpportunityGradeInfo(grade_state_machine=state_machine, flow_sessions=flow_sessions)) grade_table = sorted(zip(participations, grade_table), key=lambda (participation, grades): (participation.user.last_name.lower(), participation.user.first_name.lower())) return render_course_page( pctx, "course/gradebook-by-opp.html", { "opportunity": opportunity, "participations": participations, "grade_state_change_types": grade_state_change_types, "grade_table": grade_table, "batch_session_ops_form": batch_session_ops_form, "total_sessions": total_sessions, "finished_sessions": finished_sessions, })
def _normalize_name(self, name): try: return safe_join(self.location, name).lstrip('/') except ValueError: raise SuspiciousOperation("Attempted access to '%s' denied." % name)
def view_single_grade(pctx, participation_id, opportunity_id): now_datetime = get_now_or_fake_time(pctx.request) participation = get_object_or_404(Participation, id=int(participation_id)) if participation.course != pctx.course: raise SuspiciousOperation(_("participation does not match course")) opportunity = get_object_or_404(GradingOpportunity, id=int(opportunity_id)) if pctx.role in [ participation_role.instructor, participation_role.teaching_assistant ]: if not opportunity.shown_in_grade_book: messages.add_message( pctx.request, messages.INFO, _("This grade is not shown in the grade book.")) if not opportunity.shown_in_student_grade_book: messages.add_message( pctx.request, messages.INFO, _("This grade is not shown in the student grade book.")) elif pctx.role == participation_role.student: if participation != pctx.participation: raise PermissionDenied(_("may not view other people's grades")) if not (opportunity.shown_in_grade_book and opportunity.shown_in_student_grade_book): raise PermissionDenied(_("grade has not been released")) else: raise PermissionDenied() # {{{ modify sessions buttons if pctx.role in [ participation_role.instructor, participation_role.teaching_assistant ]: allow_session_actions = True request = pctx.request if pctx.request.method == "POST": action_re = re.compile("^([a-z]+)_([0-9]+)$") for key in request.POST.keys(): action_match = action_re.match(key) if action_match: break if not action_match: raise SuspiciousOperation(_("unknown action")) session = FlowSession.objects.get(id=int(action_match.group(2))) op = action_match.group(1) from course.flow import (regrade_session, recalculate_session_grade, expire_flow_session_standalone, finish_flow_session_standalone) try: if op == "expire": expire_flow_session_standalone(pctx.repo, pctx.course, session, now_datetime) messages.add_message(pctx.request, messages.SUCCESS, _("Session expired.")) elif op == "end": finish_flow_session_standalone(pctx.repo, pctx.course, session, now_datetime=now_datetime) messages.add_message(pctx.request, messages.SUCCESS, _("Session ended.")) elif op == "regrade": regrade_session(pctx.repo, pctx.course, session) messages.add_message(pctx.request, messages.SUCCESS, _("Session regraded.")) elif op == "recalculate": recalculate_session_grade(pctx.repo, pctx.course, session) messages.add_message(pctx.request, messages.SUCCESS, _("Session grade recalculated.")) else: raise SuspiciousOperation(_("invalid session operation")) except Exception as e: messages.add_message( pctx.request, messages.ERROR, string_concat( pgettext_lazy("Starting of Error message", "Error"), ": %(err_type)s %(err_str)s") % { "err_type": type(e).__name__, "err_str": str(e) }) else: allow_session_actions = False # }}} grade_changes = list( GradeChange.objects.filter( opportunity=opportunity, participation=participation).order_by("grade_time").select_related( "participation").select_related("participation__user"). select_related("creator").select_related("opportunity")) state_machine = GradeStateMachine() state_machine.consume(grade_changes, set_is_superseded=True) if opportunity.flow_id: flow_sessions = list( FlowSession.objects.filter( participation=participation, flow_id=opportunity.flow_id, ).order_by("start_time")) from collections import namedtuple SessionProperties = namedtuple( # noqa "SessionProperties", ["due", "grade_description"]) from course.utils import get_session_grading_rule from course.content import get_flow_desc try: flow_desc = get_flow_desc(pctx.repo, pctx.course, opportunity.flow_id, pctx.course_commit_sha) except ObjectDoesNotExist: flow_sessions_and_session_properties = None else: flow_sessions_and_session_properties = [] for session in flow_sessions: grading_rule = get_session_grading_rule( session, pctx.role, flow_desc, now_datetime) session_properties = SessionProperties( due=grading_rule.due, grade_description=grading_rule.description) flow_sessions_and_session_properties.append( (session, session_properties)) else: flow_sessions_and_session_properties = None avg_grade_percentage, avg_grade_population = average_grade(opportunity) return render_course_page( pctx, "course/gradebook-single.html", { "opportunity": opportunity, "avg_grade_percentage": avg_grade_percentage, "avg_grade_population": avg_grade_population, "grade_participation": participation, "grade_state_change_types": grade_state_change_types, "grade_changes": grade_changes, "state_machine": state_machine, "flow_sessions_and_session_properties": flow_sessions_and_session_properties, "allow_session_actions": allow_session_actions, "show_privileged_info": pctx.role in [ participation_role.instructor, participation_role.teaching_assistant ], })
def reset_password(request, field="email"): if not settings.RELATE_REGISTRATION_ENABLED: raise SuspiciousOperation( _("self-registration is not enabled")) # return form class by string of class name ResetPasswordForm = globals()["ResetPasswordFormBy" + field.title()] if request.method == 'POST': form = ResetPasswordForm(request.POST) if form.is_valid(): if field == "instid": inst_id = form.cleaned_data["instid"] try: user = get_user_model().objects.get( institutional_id__iexact=inst_id) except ObjectDoesNotExist: user = None if field == "email": email = form.cleaned_data["email"] try: user = get_user_model().objects.get(email__iexact=email) except ObjectDoesNotExist: user = None if user is None: FIELD_DICT = { "email": _("email address"), "instid": _("institutional ID") } messages.add_message(request, messages.ERROR, _("That %(field)s doesn't have an " "associated user account. Are you " "sure you've registered?") % {"field": FIELD_DICT[field]}) else: if not user.email: # happens when a user have an inst_id but have no email. messages.add_message(request, messages.ERROR, _("The account with that institution ID " "doesn't have an associated email.")) else: email = user.email user.sign_in_key = make_sign_in_key(user) user.save() from django.template.loader import render_to_string message = render_to_string("course/sign-in-email.txt", { "user": user, "sign_in_uri": request.build_absolute_uri( reverse( "relate-reset_password_stage2", args=(user.id, user.sign_in_key,))), "home_uri": request.build_absolute_uri( reverse("relate-home")) }) from django.core.mail import send_mail send_mail( string_concat("[", _("RELATE"), "] ", _("Password reset")), message, settings.ROBOT_EMAIL_FROM, recipient_list=[email]) if field == "instid": messages.add_message(request, messages.INFO, _("The email address associated with that " "account is %s.") % masked_email(email)) messages.add_message(request, messages.INFO, _("Email sent. Please check your email and " "click the link.")) return redirect("relate-home") else: form = ResetPasswordForm() return render(request, "reset-passwd-form.html", { "field": field, "form_description": _("Password reset on %(site_name)s") % {"site_name": _("RELATE")}, "form": form })
def get_list_queryset(self, queryset): lookup_params = dict([(smart_str(k)[len(FILTER_PREFIX):], v) for k, v in self.admin_view.params.items() if smart_str(k).startswith(FILTER_PREFIX) and v != '']) for p_key, p_val in lookup_params.iteritems(): if p_val == "False": lookup_params[p_key] = False use_distinct = False if not hasattr(self.admin_view,'quickfilter'): self.admin_view.quickfilter = {} # for clean filters self.admin_view.quickfilter['has_query_param'] = bool(lookup_params) self.admin_view.quickfilter['clean_query_url'] = self.admin_view.get_query_string(remove=[k for k in self.request.GET.keys() if k.startswith(FILTER_PREFIX)]) # Normalize the types of keys if not self.free_query_filter: for key, value in lookup_params.items(): if not self.lookup_allowed(key, value): raise SuspiciousOperation("Filtering by %s not allowed" % key) self.filter_specs = [] if self.list_quick_filter: for list_quick_filter in self.list_quick_filter: field_path = None field_order_by = None field_limit = None field_parts = [] sort_key = None cache_config = None if type(list_quick_filter)==dict and 'field' in list_quick_filter: field = list_quick_filter['field'] if 'order_by' in list_quick_filter: field_order_by = list_quick_filter['order_by'] if 'limit' in list_quick_filter: field_limit = list_quick_filter['limit'] if 'sort' in list_quick_filter and callable(list_quick_filter['sort']): sort_key = list_quick_filter['sort'] if 'cache' in list_quick_filter and type(list_quick_filter)==dict: cache_config = list_quick_filter['cache'] else: field = list_quick_filter # This plugin only uses MultiselectFieldListFilter if not isinstance(field, models.Field): field_path = field field_parts = get_fields_from_path(self.model, field_path) field = field_parts[-1] spec = QuickFilterMultiSelectFieldListFilter(field, self.request, lookup_params,self.model, self.admin_view, field_path=field_path,field_order_by=field_order_by,field_limit=field_limit,sort_key=sort_key,cache_config=cache_config) if len(field_parts)>1: spec.title = "%s %s"%(field_parts[-2].name,spec.title) # Check if we need to use distinct() use_distinct = True#(use_distinct orlookup_needs_distinct(self.opts, field_path)) if spec and spec.has_output(): try: new_qs = spec.do_filte(queryset) except ValidationError, e: new_qs = None self.admin_view.message_user(u"<b>过滤器错误:</b> %s" % e.messages[0], 'error') if new_qs is not None: queryset = new_qs self.filter_specs.append(spec)
def grade_flow_page(pctx, flow_session_id, page_ordinal): # type: (CoursePageContext, int, int) -> http.HttpResponse now_datetime = get_now_or_fake_time(pctx.request) page_ordinal = int(page_ordinal) viewing_prev_grade = False prev_grade_id = pctx.request.GET.get("grade_id") if prev_grade_id is not None: try: prev_grade_id = int(prev_grade_id) viewing_prev_grade = True except ValueError: raise SuspiciousOperation("non-integer passed for 'grade_id'") if not pctx.has_permission(pperm.view_gradebook): raise PermissionDenied(_("may not view grade book")) flow_session = get_object_or_404(FlowSession, id=int(flow_session_id)) if flow_session.course.pk != pctx.course.pk: raise SuspiciousOperation( _("Flow session not part of specified course")) if flow_session.participation is None: raise SuspiciousOperation(_("Cannot grade anonymous session")) from course.flow import adjust_flow_session_page_data adjust_flow_session_page_data(pctx.repo, flow_session, pctx.course.identifier, respect_preview=False) fpctx = FlowPageContext(pctx.repo, pctx.course, flow_session.flow_id, page_ordinal, participation=flow_session.participation, flow_session=flow_session, request=pctx.request) if fpctx.page_desc is None: raise http.Http404() assert fpctx.page is not None assert fpctx.page_context is not None # {{{ enable flow session zapping all_flow_sessions = list( FlowSession.objects.filter(course=pctx.course, flow_id=flow_session.flow_id, participation__isnull=False, in_progress=flow_session.in_progress). order_by( # Datatables will default to sorting the user list # by the first column, which happens to be the username. # Match that sorting. "participation__user__username", "start_time")) next_flow_session_id = None prev_flow_session_id = None for i, other_flow_session in enumerate(all_flow_sessions): if other_flow_session.pk == flow_session.pk: if i > 0: prev_flow_session_id = all_flow_sessions[i - 1].id if i + 1 < len(all_flow_sessions): next_flow_session_id = all_flow_sessions[i + 1].id # }}} prev_grades = get_prev_visit_grades(flow_session_id, page_ordinal) # {{{ reproduce student view form = None feedback = None answer_data = None grade_data = None shown_grade = None if fpctx.page.expects_answer(): if fpctx.prev_answer_visit is not None and prev_grade_id is None: answer_data = fpctx.prev_answer_visit.answer shown_grade = fpctx.prev_answer_visit.get_most_recent_grade() if shown_grade is not None: feedback = get_feedback_for_grade(shown_grade) grade_data = shown_grade.grade_data else: feedback = None grade_data = None if shown_grade is not None: prev_grade_id = shown_grade.id elif prev_grade_id is not None: try: shown_grade = prev_grades.filter(id=prev_grade_id).get() except ObjectDoesNotExist: raise http.Http404() feedback = get_feedback_for_grade(shown_grade) grade_data = shown_grade.grade_data answer_data = shown_grade.visit.answer else: feedback = None from course.page.base import PageBehavior page_behavior = PageBehavior(show_correctness=True, show_answer=False, may_change_answer=False) try: form = fpctx.page.make_form(fpctx.page_context, fpctx.page_data.data, answer_data, page_behavior) except InvalidPageData as e: messages.add_message( pctx.request, messages.ERROR, _("The page data stored in the database was found " "to be invalid for the page as given in the " "course content. Likely the course content was " "changed in an incompatible way (say, by adding " "an option to a choice question) without changing " "the question ID. The precise error encountered " "was the following: ") + str(e)) return render_course_page(pctx, "course/course-base.html", {}) if form is not None: form_html = fpctx.page.form_to_html(pctx.request, fpctx.page_context, form, answer_data) else: form_html = None # }}} # {{{ grading form if (fpctx.page.expects_answer() and fpctx.page.is_answer_gradable() and fpctx.prev_answer_visit is not None and not flow_session.in_progress and not viewing_prev_grade): request = pctx.request if pctx.request.method == "POST": if not pctx.has_permission(pperm.assign_grade): raise PermissionDenied(_("may not assign grades")) grading_form = fpctx.page.post_grading_form( fpctx.page_context, fpctx.page_data, grade_data, request.POST, request.FILES) if grading_form.is_valid(): grade_data = fpctx.page.update_grade_data_from_grading_form_v2( request, fpctx.page_context, fpctx.page_data, grade_data, grading_form, request.FILES) with translation.override(settings.RELATE_ADMIN_EMAIL_LOCALE): feedback = fpctx.page.grade(fpctx.page_context, fpctx.page_data, answer_data, grade_data) if feedback is not None: correctness = feedback.correctness else: correctness = None feedback_json = None # type: Optional[Dict[Text, Any]] bulk_feedback_json = None # type: Optional[Dict[Text, Any]] if feedback is not None: feedback_json, bulk_feedback_json = feedback.as_json() else: feedback_json = bulk_feedback_json = None most_recent_grade = FlowPageVisitGrade( visit=fpctx.prev_answer_visit, grader=pctx.request.user, graded_at_git_commit_sha=pctx.course_commit_sha, grade_data=grade_data, max_points=fpctx.page.max_points(fpctx.page_data), correctness=correctness, feedback=feedback_json) prev_grade_id = _save_grade(fpctx, flow_session, most_recent_grade, bulk_feedback_json, now_datetime) else: grading_form = fpctx.page.make_grading_form( fpctx.page_context, fpctx.page_data, grade_data) else: grading_form = None if grading_form is not None: from crispy_forms.layout import Submit grading_form.helper.form_class += " relate-grading-form" grading_form.helper.add_input( Submit("submit", _("Submit"), accesskey="s", css_class="relate-grading-save-button")) grading_form_html = fpctx.page.grading_form_to_html( pctx.request, fpctx.page_context, grading_form, grade_data) else: grading_form_html = None # }}} # {{{ compute points_awarded max_points = None points_awarded = None if (fpctx.page.expects_answer() and fpctx.page.is_answer_gradable()): max_points = fpctx.page.max_points(fpctx.page_data) if feedback is not None and feedback.correctness is not None: points_awarded = max_points * feedback.correctness # }}} grading_rule = get_session_grading_rule(flow_session, fpctx.flow_desc, get_now_or_fake_time(pctx.request)) if grading_rule.grade_identifier is not None: grading_opportunity = get_flow_grading_opportunity( pctx.course, flow_session.flow_id, fpctx.flow_desc, grading_rule.grade_identifier, grading_rule. grade_aggregation_strategy) # type: Optional[GradingOpportunity] else: grading_opportunity = None return render_course_page( pctx, "course/grade-flow-page.html", { "flow_identifier": fpctx.flow_id, "flow_session": flow_session, "flow_desc": fpctx.flow_desc, "ordinal": fpctx.ordinal, "page_data": fpctx.page_data, "body": fpctx.page.body(fpctx.page_context, fpctx.page_data.data), "form": form, "form_html": form_html, "feedback": feedback, "max_points": max_points, "points_awarded": points_awarded, "shown_grade": shown_grade, "prev_grade_id": prev_grade_id, "grading_opportunity": grading_opportunity, "prev_flow_session_id": prev_flow_session_id, "next_flow_session_id": next_flow_session_id, "grading_form": grading_form, "grading_form_html": grading_form_html, "correct_answer": fpctx.page.correct_answer(fpctx.page_context, fpctx.page_data.data, answer_data, grade_data), # Wrappers used by JavaScript template (tmpl) so as not to # conflict with Django template's tag wrapper "JQ_OPEN": '{%', 'JQ_CLOSE': '%}', })
def get_list_queryset(self, queryset): lookup_params = dict([ (smart_str(k)[len(FILTER_PREFIX):], v) for k, v in self.admin_view.params.items() if smart_str(k).startswith(FILTER_PREFIX) and v != '' ]) for p_key, p_val in lookup_params.iteritems(): if p_val == "False": lookup_params[p_key] = False use_distinct = False # for clean filters self.admin_view.has_query_param = bool(lookup_params) self.admin_view.clean_query_url = self.admin_view.get_query_string( remove=[ k for k in self.request.GET.keys() if k.startswith(FILTER_PREFIX) ]) # Normalize the types of keys if not self.free_query_filter: for key, value in lookup_params.items(): if not self.lookup_allowed(key, value): raise SuspiciousOperation("Filtering by %s not allowed" % key) self.filter_specs = [] if self.list_filter: for list_filter in self.list_filter: if callable(list_filter): # This is simply a custom list filter class. spec = list_filter(self.request, lookup_params, self.model, self) else: field_path = None field_parts = [] if isinstance(list_filter, (tuple, list)): # This is a custom FieldListFilter class for a given field. field, field_list_filter_class = list_filter else: # This is simply a field name, so use the default # FieldListFilter class that has been registered for # the type of the given field. field, field_list_filter_class = list_filter, filter_manager.create if not isinstance(field, models.Field): field_path = field field_parts = get_fields_from_path( self.model, field_path) field = field_parts[-1] spec = field_list_filter_class(field, self.request, lookup_params, self.model, self.admin_view, field_path=field_path) if len(field_parts) > 1: # Add related model name to title spec.title = "%s %s" % (field_parts[-2].name, spec.title) # Check if we need to use distinct() use_distinct = (use_distinct or lookup_needs_distinct( self.opts, field_path)) if spec and spec.has_output(): try: new_qs = spec.do_filte(queryset) except ValidationError, e: new_qs = None self.admin_view.message_user( _("<b>Filtering error:</b> %s") % e.messages[0], 'error') if new_qs is not None: queryset = new_qs self.filter_specs.append(spec)
def join_team(request): #Option 1: Join an existing team #Option 2 : Register as an individual if request.method != "POST": raise SuspiciousOperation( "Illegal request; This event is reported and you will be blocked from any further access to this website" ) code = request.POST.get('team', None) event = request.POST.get('event', None) email = request.POST.get('email', None) course = request.POST.get('course', None) contact = request.POST.get('contact', None) college = request.POST.get('college', None) year = request.POST.get('year', None) required = { 'email': email, 'course': course, 'college': college, 'year': year, 'contact': contact } for key in required: if not required[key]: data = {'status': '%s Field is required' % key} return JsonResponse(data) user = User.objects.get(username=request.user) name = user.get_full_name() print(code, event, email, course, contact, college, year, name) ##***************************************Individual Registeration*****************************************************## if not code: #This means user wants to register for solo participation event_obj = Event.objects.get( name=event) # store event object in event variable #Test if user is already registered for this event has_registered = Participant.objects.filter( event_name=event_obj).filter(student_name=name).exists() if not has_registered: p_obj = Participant(event_name=event_obj, student_name=name, college=college, year=year, contact_number=contact, email_id=email, course=course) p_obj.save() print "Added" #Now fetch computer generated ID for this record q_obj = Participant.objects.filter(email_id=email).filter( event_name=event_obj).filter(student_name=name) ID = q_obj[0].event_ref # fetch ID # And send it to participant's email ID status = send_confirmation_mail(email, event_obj.name, ID, name) # General email format if status: #if status is true mail has been sent data = { 'status': "Your registeration is confirmed.Please check your email inbox" } print "added and mail sent" return JsonResponse(data) else: data = {'status': "You have already registered for this event"} return JsonResponse(data) ##***************************************Registeration using Team Code**************************************************************## if code: # first of all test whether the team exist or not does_exist = Team.objects.filter( team_pass=code).exists() # returns true if team code exists event_obj = Event.objects.get( name=event) # store event object in event variable status = 0 #default value success = False #default value if does_exist: try: team_obj = Team.objects.get(team_pass=code) except: data = {'status': 'We are Sorry this is not allowed :/.'} return JsonResponse(data) success = registerParticipant(name, college, year, course, contact, email, event_obj, team_obj) #print(success) if success: q_obj = Participant.objects.filter(email_id=email).filter( event_name=event_obj).filter(student_name=name) ID = q_obj[0].event_ref # fetch ID #print(q_obj) status = send_confirmation_mail(email, event_obj.name, ID, name) print "added and mail sent" ##*************************************Confirmation Logic(Team Registeration)*******************************************## if success and status: status = "Registeration Confirmed. Please check your email" print "mail sent" if success and not status: status = "Registeration Confirmed but we were unable to send you confirmation email" if not success: status = "You have already registered for this event.See you soon." if not does_exist: status = "Invalid Team Code" data = {'status': status} return JsonResponse(data)
def create_city(self, geoname_id, lang): web_service_url = self.geonames_url + 'getJSON' values = { 'geonameId': geoname_id, 'username': self.geonames_username, 'style': 'FULL' } data = urlencode(values) data = data.encode('ascii') r = urlopen(web_service_url, data) data = json.loads(r.read().decode(r.info().get_param('charset') or 'utf-8')) if data.get('status', False): raise Exception(data.get('status').get('message')) if data.get('fcode') not in self.geonames_allowed_city_types: raise SuspiciousOperation( _("The geonames feature code is not supported")) try: country = Country.objects.get( geoname_id=int_arg(data.get('countryId'))) except Error: raise SuspiciousOperation( _("The country of this city is not referenced")) lat = float(data.get('lat')) long = float(data.get('lng')) population = int_arg(data.get('population')) try: city, value = City.objects.get_or_create( geoname_id=int_arg(geoname_id), country_id=country.id, defaults={ 'name': data['name'], 'latitude': lat, 'longitude': long, 'population': population, 'feature_code': data['fcode'] }) except Error: raise Exception(_("Unable to create the city")) if value and data.get('alternateNames'): for city_alt_name in data.get('alternateNames'): if city_alt_name.get('lang') not in TRANSLATION_LANGUAGES: continue is_preferred = city_alt_name.get('isPreferredName', False) is 'true' is_short = city_alt_name.get('isShortName', False) is 'true' try: alt_name = AlternateName.objects.create( language=city_alt_name['lang'], alternate_name=city_alt_name.get('name'), is_preferred_name=is_preferred, is_short_name=is_short) city.alt_names.add(alt_name) except Error: continue city = City.objects.get(id=city.id) alt_names = [] preferred = [] short = [] for name in city.alt_names.filter(language=lang): if name.is_preferred_name: preferred.append(name.alternate_name) if name.is_short_name: short.append(name.alternate_name) else: alt_names.append(name.alternate_name) result = { 'cit_id': city.id, 'geoname_id': city.geoname_id, 'name': city.name, 'lat': float(city.latitude), 'long': float(city.longitude), 'alt_name': ','.join(alt_names), 'cou_id': city.country_id, 'preferred_name': ', '.join(preferred), 'short_name': ', '.join(short) } return result
def save(self, *args, **kwargs): if self._state.adding: if self.company.routes.filter(station=self.station): raise SuspiciousOperation("Already exists") super().save(*args, **kwargs)
def get_import_file_content_or_raise(user_id, import_type): filename = generate_import_filename(user_id, import_type) if not os.path.isfile(filename): raise SuspiciousOperation("No test run performed previously.") with open(filename, "rb") as file: return file.read()
def update_from_dnb(model_admin, request, object_id): """ Tool to let admin users update company with a valid `duns_number` by pulling fresh data from D&B. The company record will be versioned after the update from D&B is applied. The `pending_dnb_investigation` field will be set to False. """ if not model_admin.has_change_permission(request): raise PermissionDenied() dh_company = model_admin.get_object(request, object_id) company_change_page = reverse( admin_urlname(model_admin.model._meta, 'change'), kwargs={'object_id': dh_company.pk}, ) if dh_company is None or dh_company.duns_number is None: raise SuspiciousOperation() try: dnb_company = get_company(dh_company.duns_number) except ( DNBServiceError, DNBServiceConnectionError, DNBServiceTimeoutError, DNBServiceInvalidResponse, ): message = 'Something went wrong in an upstream service.' raise AdminException(message, company_change_page) except DNBServiceInvalidRequest: message = 'No matching company found in D&B database.' raise AdminException(message, company_change_page) if request.method == 'GET': return TemplateResponse( request, 'admin/company/company/update-from-dnb.html', { **model_admin.admin_site.each_context(request), 'media': model_admin.media, 'opts': model_admin.model._meta, 'object': dh_company, 'title': gettext_lazy('Confirm update from D&B'), 'diff': _format_company_diff(dh_company, dnb_company), }, ) try: update_company_from_dnb(dh_company, dnb_company, request.user) return HttpResponseRedirect(company_change_page) except serializers.ValidationError: message = 'Data from D&B did not pass the Data Hub validation checks.' raise AdminException(message, company_change_page)
def confirmation(request, category): assertValidTime() context = initialize_context(request) if request.method != 'POST': context['message'] = 'Invalid http method for the resource' return render(request, 'http/405.html', context ,status = 405) user = requireValidUser(request) assertNotVoted(user, category) # legitimacy checks checkBatch(user.batch) if not checkCategory(category): context['message'] = "The page you are trying to access does not exist" return render(request, 'http/404.html', context, status = 404) if not canVoteCategory(user, category): raise PermissionDenied("You are not permitted to vote for this category") # post data checks email = request.POST.get('vote', None) if not email: raise SuspiciousOperation('The request was cancelled') candidate = UserProfile.findByEmail(email) if not candidate: raise SuspiciousOperation('The request was cancelled') # Prevent cross category request forgery # TODO: remove hardcode batch = [category[:-2]] if category[:-2] == "MT2020": batch = ['MT2020', 'DT2020', 'MS2020', 'PH2020'] if candidate.batch not in batch: raise SuspiciousOperation('The request was cancelled due to attempt at request forgery') # if not after confirmation if not request.POST.get('confirm', False): context = {} context['candidate'] = candidate context['category'] = category context['user'] = { 'name': " ".join(user.username.split(" ")[1:]), 'rollno': user.username.split(" ")[0], 'batch_programme': user.batch_programme, 'batch_year': user.batch_year, 'is_authenticated': True, 'role': user.role, } return render(request, 'main/confirm.html', context) else: # create and save the vote voteHash = hashlib.sha256((user.username + candidate.username + user.salt).encode()).hexdigest() vote = Vote.objects.create(candidate = candidate, voter = user, category = category, voteHash = voteHash) # increment candidate's vote_count, easier for dashboard vote.save() # return redirect(reverse('vote', kwargs={'m': "done"})) return redirect('/vote/?m=done')