当前位置: 首页>>代码示例>>Python>>正文


Python SoftwareSecurePhotoVerification.user_has_valid_or_pending方法代码示例

本文整理汇总了Python中verify_student.models.SoftwareSecurePhotoVerification.user_has_valid_or_pending方法的典型用法代码示例。如果您正苦于以下问题:Python SoftwareSecurePhotoVerification.user_has_valid_or_pending方法的具体用法?Python SoftwareSecurePhotoVerification.user_has_valid_or_pending怎么用?Python SoftwareSecurePhotoVerification.user_has_valid_or_pending使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在verify_student.models.SoftwareSecurePhotoVerification的用法示例。


在下文中一共展示了SoftwareSecurePhotoVerification.user_has_valid_or_pending方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_user_has_valid_or_pending

# 需要导入模块: from verify_student.models import SoftwareSecurePhotoVerification [as 别名]
# 或者: from verify_student.models.SoftwareSecurePhotoVerification import user_has_valid_or_pending [as 别名]
    def test_user_has_valid_or_pending(self):
        window = MidcourseReverificationWindowFactory(
            course_id=self.course.id,
            start_date=datetime.now(pytz.UTC) - timedelta(days=15),
            end_date=datetime.now(pytz.UTC) - timedelta(days=13),
        )

        attempt = SoftwareSecurePhotoVerification(status="must_retry", user=self.user, window=window)
        attempt.save()

        assert_false(SoftwareSecurePhotoVerification.user_has_valid_or_pending(user=self.user, window=window))

        attempt.status = "approved"
        attempt.save()
        assert_true(SoftwareSecurePhotoVerification.user_has_valid_or_pending(user=self.user, window=window))
开发者ID:escolaglobal,项目名称:edx-platform,代码行数:17,代码来源:test_models.py

示例2: get

# 需要导入模块: from verify_student.models import SoftwareSecurePhotoVerification [as 别名]
# 或者: from verify_student.models.SoftwareSecurePhotoVerification import user_has_valid_or_pending [as 别名]
    def get(self, request, course_id):
        """
        Displays the main verification view, which contains three separate steps:
            - Taking the standard face photo
            - Taking the id photo
            - Confirming that the photos and payment price are correct
              before proceeding to payment
        """
        upgrade = request.GET.get('upgrade', False)

        course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
        # If the user has already been verified within the given time period,
        # redirect straight to the payment -- no need to verify again.
        if SoftwareSecurePhotoVerification.user_has_valid_or_pending(request.user):
            return redirect(
                reverse('verify_student_verified',
                        kwargs={'course_id': course_id.to_deprecated_string()}) + "?upgrade={}".format(upgrade)
            )
        elif CourseEnrollment.enrollment_mode_for_user(request.user, course_id) == ('verified', True):
            return redirect(reverse('dashboard'))
        else:
            # If they haven't completed a verification attempt, we have to
            # restart with a new one. We can't reuse an older one because we
            # won't be able to show them their encrypted photo_id -- it's easier
            # bookkeeping-wise just to start over.
            progress_state = "start"

        modes_dict = CourseMode.modes_for_course_dict(course_id)
        verify_mode = modes_dict.get('verified', None)
        # if the course doesn't have a verified mode, we want to kick them
        # from the flow
        if not verify_mode:
            return redirect(reverse('dashboard'))
        if course_id.to_deprecated_string() in request.session.get("donation_for_course", {}):
            chosen_price = request.session["donation_for_course"][course_id.to_deprecated_string()]
        else:
            chosen_price = verify_mode.min_price

        course = modulestore().get_course(course_id)
        context = {
            "progress_state": progress_state,
            "user_full_name": request.user.profile.name,
            "course_id": course_id.to_deprecated_string(),
            "course_modes_choose_url": reverse('course_modes_choose', kwargs={'course_id': course_id.to_deprecated_string()}),
            "course_name": course.display_name_with_default,
            "course_org": course.display_org_with_default,
            "course_num": course.display_number_with_default,
            "purchase_endpoint": get_purchase_endpoint(),
            "suggested_prices": [
                decimal.Decimal(price)
                for price in verify_mode.suggested_prices.split(",")
            ],
            "currency": verify_mode.currency.upper(),
            "chosen_price": chosen_price,
            "min_price": verify_mode.min_price,
            "upgrade": upgrade == u'True',
            "can_audit": "audit" in modes_dict,
        }

        return render_to_response('verify_student/photo_verification.html', context)
开发者ID:emilyhdo,项目名称:edx-platform,代码行数:62,代码来源:views.py

示例3: show_requirements

# 需要导入模块: from verify_student.models import SoftwareSecurePhotoVerification [as 别名]
# 或者: from verify_student.models.SoftwareSecurePhotoVerification import user_has_valid_or_pending [as 别名]
def show_requirements(request, course_id):
    """
    Show the requirements necessary for the verification flow.
    """
    # TODO: seems borked for professional; we're told we need to take photos even if there's a pending verification
    course_id = CourseKey.from_string(course_id)
    upgrade = request.GET.get('upgrade', False)
    if CourseEnrollment.enrollment_mode_for_user(request.user, course_id) == ('verified', True):
        return redirect(reverse('dashboard'))
    if SoftwareSecurePhotoVerification.user_has_valid_or_pending(request.user):
        return redirect(
            reverse(
                'verify_student_verified',
                kwargs={'course_id': course_id.to_deprecated_string()}
            ) + "?upgrade={}".format(upgrade)
        )

    upgrade = request.GET.get('upgrade', False)
    course = modulestore().get_course(course_id)
    modes_dict = CourseMode.modes_for_course_dict(course_id)
    context = {
        "course_id": course_id.to_deprecated_string(),
        "course_modes_choose_url": reverse("course_modes_choose", kwargs={'course_id': course_id.to_deprecated_string()}),
        "verify_student_url": reverse('verify_student_verify', kwargs={'course_id': course_id.to_deprecated_string()}),
        "course_name": course.display_name_with_default,
        "course_org": course.display_org_with_default,
        "course_num": course.display_number_with_default,
        "is_not_active": not request.user.is_active,
        "upgrade": upgrade == u'True',
        "modes_dict": modes_dict,
    }
    return render_to_response("verify_student/show_requirements.html", context)
开发者ID:OmarIthawi,项目名称:edx-platform,代码行数:34,代码来源:views.py

示例4: create_order

# 需要导入模块: from verify_student.models import SoftwareSecurePhotoVerification [as 别名]
# 或者: from verify_student.models.SoftwareSecurePhotoVerification import user_has_valid_or_pending [as 别名]
def create_order(request):
    """
    Submit PhotoVerification and create a new Order for this verified cert
    """
    if not SoftwareSecurePhotoVerification.user_has_valid_or_pending(request.user):
        attempt = SoftwareSecurePhotoVerification(user=request.user)
        b64_face_image = request.POST['face_image'].split(",")[1]
        b64_photo_id_image = request.POST['photo_id_image'].split(",")[1]

        attempt.upload_face_image(b64_face_image.decode('base64'))
        attempt.upload_photo_id_image(b64_photo_id_image.decode('base64'))
        attempt.mark_ready()

        attempt.save()

    course_id = request.POST['course_id']
    course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    donation_for_course = request.session.get('donation_for_course', {})
    current_donation = donation_for_course.get(course_id, decimal.Decimal(0))
    contribution = request.POST.get("contribution", donation_for_course.get(course_id, 0))
    try:
        amount = decimal.Decimal(contribution).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)
    except decimal.InvalidOperation:
        return HttpResponseBadRequest(_("Selected price is not valid number."))

    if amount != current_donation:
        donation_for_course[course_id] = amount
        request.session['donation_for_course'] = donation_for_course

    # prefer professional mode over verified_mode
    current_mode = CourseMode.verified_mode_for_course(course_id)

    if current_mode.slug == 'professional':
        amount = current_mode.min_price

    # make sure this course has a verified mode
    if not current_mode:
        return HttpResponseBadRequest(_("This course doesn't support verified certificates"))

    if amount < current_mode.min_price:
        return HttpResponseBadRequest(_("No selected price or selected price is below minimum."))

    # I know, we should check this is valid. All kinds of stuff missing here
    cart = Order.get_cart_for_user(request.user)
    cart.clear()
    enrollment_mode = current_mode.slug
    CertificateItem.add_to_order(cart, course_id, amount, enrollment_mode)

    callback_url = request.build_absolute_uri(
        reverse("shoppingcart.views.postpay_callback")
    )
    params = get_signed_purchase_params(
        cart, callback_url=callback_url
    )

    return HttpResponse(json.dumps(params), content_type="text/json")
开发者ID:VeritasU,项目名称:edx-platform,代码行数:58,代码来源:views.py

示例5: post

# 需要导入模块: from verify_student.models import SoftwareSecurePhotoVerification [as 别名]
# 或者: from verify_student.models.SoftwareSecurePhotoVerification import user_has_valid_or_pending [as 别名]
    def post(self, request, course_id):
        """ Takes the form submission from the page and parses it """
        course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
        user = request.user

        # This is a bit redundant with logic in student.views.change_enrollment,
        # but I don't really have the time to refactor it more nicely and test.
        course = modulestore().get_course(course_key)
        if not has_access(user, 'enroll', course):
            # error_msg = _("Enrollment is closed")
            error_msg = u"La période d'inscription est terminée."
            return self.get(request, course_id, error=error_msg)

        upgrade = request.GET.get('upgrade', False)

        requested_mode = self.get_requested_mode(request.POST)

        allowed_modes = CourseMode.modes_for_course_dict(course_key)
        if requested_mode not in allowed_modes:
            return HttpResponseBadRequest(_("Enrollment mode not supported"))

        if requested_mode in ("audit", "honor"):
            CourseEnrollment.enroll(user, course_key, requested_mode)
            return redirect('dashboard')

        mode_info = allowed_modes[requested_mode]

        if requested_mode == "verified":
            amount = request.POST.get("contribution") or \
                request.POST.get("contribution-other-amt") or 0

            try:
                # validate the amount passed in and force it into two digits
                amount_value = decimal.Decimal(amount).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)
            except decimal.InvalidOperation:
                error_msg = _("Invalid amount selected.")
                return self.get(request, course_id, error=error_msg)

            # Check for minimum pricing
            if amount_value < mode_info.min_price:
                error_msg = _("No selected price or selected price is too low.")
                return self.get(request, course_id, error=error_msg)

            donation_for_course = request.session.get("donation_for_course", {})
            donation_for_course[course_key] = amount_value
            request.session["donation_for_course"] = donation_for_course
            if SoftwareSecurePhotoVerification.user_has_valid_or_pending(request.user):
                return redirect(
                    reverse('verify_student_verified',
                            kwargs={'course_id': course_key.to_deprecated_string()}) + "?upgrade={}".format(upgrade)
                )

            return redirect(
                reverse('verify_student_show_requirements',
                        kwargs={'course_id': course_key.to_deprecated_string()}) + "?upgrade={}".format(upgrade))
开发者ID:LICEF,项目名称:edx-platform,代码行数:57,代码来源:views.py

示例6: _check_already_verified

# 需要导入模块: from verify_student.models import SoftwareSecurePhotoVerification [as 别名]
# 或者: from verify_student.models.SoftwareSecurePhotoVerification import user_has_valid_or_pending [as 别名]
    def _check_already_verified(self, user):
        """Check whether the user has a valid or pending verification.

        Note that this includes cases in which the user's verification
        has not been accepted (either because it hasn't been processed,
        or there was an error).

        This should return True if the user has done their part:
        submitted photos within the expiration period.

        """
        return SoftwareSecurePhotoVerification.user_has_valid_or_pending(user)
开发者ID:Cgruppo,项目名称:edx-platform,代码行数:14,代码来源:views.py

示例7: post

# 需要导入模块: from verify_student.models import SoftwareSecurePhotoVerification [as 别名]
# 或者: from verify_student.models.SoftwareSecurePhotoVerification import user_has_valid_or_pending [as 别名]
    def post(self, request, course_id):
        user = request.user

        # This is a bit redundant with logic in student.views.change_enrollement,
        # but I don't really have the time to refactor it more nicely and test.
        course = course_from_id(course_id)
        if not has_access(user, course, 'enroll'):
            error_msg = _("Enrollment is closed")
            return self.get(request, course_id, error=error_msg)

        requested_mode = self.get_requested_mode(request.POST.get("mode"))
        if requested_mode == "verified" and request.POST.get("honor-code"):
            requested_mode = "honor"

        allowed_modes = CourseMode.modes_for_course_dict(course_id)
        if requested_mode not in allowed_modes:
            return HttpResponseBadRequest(_("Enrollment mode not supported"))

        if requested_mode in ("audit", "honor"):
            CourseEnrollment.enroll(user, course_id, requested_mode)
            return redirect('dashboard')

        mode_info = allowed_modes[requested_mode]

        if requested_mode == "verified":
            amount = request.POST.get("contribution") or \
                request.POST.get("contribution-other-amt") or 0

            try:
                # validate the amount passed in and force it into two digits
                amount_value = decimal.Decimal(amount).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)
            except decimal.InvalidOperation:
                error_msg = _("Invalid amount selected.")
                return self.get(request, course_id, error=error_msg)

            # Check for minimum pricing
            if amount_value < mode_info.min_price:
                error_msg = _("No selected price or selected price is too low.")
                return self.get(request, course_id, error=error_msg)

            donation_for_course = request.session.get("donation_for_course", {})
            donation_for_course[course_id] = amount_value
            request.session["donation_for_course"] = donation_for_course
            if SoftwareSecurePhotoVerification.user_has_valid_or_pending(request.user):
                return redirect(
                    reverse('verify_student_verified',
                            kwargs={'course_id': course_id})
                )

            return redirect(
                reverse('verify_student_show_requirements',
                        kwargs={'course_id': course_id}),
            )
开发者ID:calistoristow,项目名称:edx-platform,代码行数:55,代码来源:views.py

示例8: get

# 需要导入模块: from verify_student.models import SoftwareSecurePhotoVerification [as 别名]
# 或者: from verify_student.models.SoftwareSecurePhotoVerification import user_has_valid_or_pending [as 别名]
    def get(self, request, course_id):
        """
        """
        # If the user has already been verified within the given time period,
        # redirect straight to the payment -- no need to verify again.
        if SoftwareSecurePhotoVerification.user_has_valid_or_pending(request.user):
            return redirect(
                reverse('verify_student_verified',
                        kwargs={'course_id': course_id}))
        elif CourseEnrollment.enrollment_mode_for_user(request.user, course_id) == 'verified':
            return redirect(reverse('dashboard'))
        else:
            # If they haven't completed a verification attempt, we have to
            # restart with a new one. We can't reuse an older one because we
            # won't be able to show them their encrypted photo_id -- it's easier
            # bookkeeping-wise just to start over.
            progress_state = "start"

        verify_mode = CourseMode.mode_for_course(course_id, "verified")
        # if the course doesn't have a verified mode, we want to kick them
        # from the flow
        if not verify_mode:
            return redirect(reverse('dashboard'))
        if course_id in request.session.get("donation_for_course", {}):
            chosen_price = request.session["donation_for_course"][course_id]
        else:
            chosen_price = verify_mode.min_price

        course = course_from_id(course_id)
        context = {
            "progress_state": progress_state,
            "user_full_name": request.user.profile.name,
            "course_id": course_id,
            "course_name": course.display_name_with_default,
            "course_org" : course.display_org_with_default,
            "course_num" : course.display_number_with_default,
            "purchase_endpoint": get_purchase_endpoint(),
            "suggested_prices": [
                decimal.Decimal(price)
                for price in verify_mode.suggested_prices.split(",")
            ],
            "currency": verify_mode.currency.upper(),
            "chosen_price": chosen_price,
            "min_price": verify_mode.min_price,
        }

        return render_to_response('verify_student/photo_verification.html', context)
开发者ID:sebschu,项目名称:edx-platform,代码行数:49,代码来源:views.py

示例9: create_order

# 需要导入模块: from verify_student.models import SoftwareSecurePhotoVerification [as 别名]
# 或者: from verify_student.models.SoftwareSecurePhotoVerification import user_has_valid_or_pending [as 别名]
def create_order(request):
    """
    Submit PhotoVerification and create a new Order for this verified cert
    """
    if not SoftwareSecurePhotoVerification.user_has_valid_or_pending(request.user):
        attempt = SoftwareSecurePhotoVerification(user=request.user)
        b64_face_image = request.POST['face_image'].split(",")[1]
        b64_photo_id_image = request.POST['photo_id_image'].split(",")[1]

        attempt.upload_face_image(b64_face_image.decode('base64'))
        attempt.upload_photo_id_image(b64_photo_id_image.decode('base64'))
        attempt.mark_ready()

        attempt.save()

    course_id = request.POST['course_id']
    donation_for_course = request.session.get('donation_for_course', {})
    current_donation = donation_for_course.get(course_id, decimal.Decimal(0))
    contribution = request.POST.get("contribution", donation_for_course.get(course_id, 0))
    try:
        amount = decimal.Decimal(contribution).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)
    except decimal.InvalidOperation:
        return HttpResponseBadRequest(_("Selected price is not valid number."))

    if amount != current_donation:
        donation_for_course[course_id] = amount
        request.session['donation_for_course'] = donation_for_course

    verified_mode = CourseMode.modes_for_course_dict(course_id).get('verified', None)

    # make sure this course has a verified mode
    if not verified_mode:
        return HttpResponseBadRequest(_("This course doesn't support verified certificates"))

    if amount < verified_mode.min_price:
        return HttpResponseBadRequest(_("No selected price or selected price is below minimum."))

    # I know, we should check this is valid. All kinds of stuff missing here
    cart = Order.get_cart_for_user(request.user)
    cart.clear()
    CertificateItem.add_to_order(cart, course_id, amount, 'verified')

    params = get_signed_purchase_params(cart)

    return HttpResponse(json.dumps(params), content_type="text/json")
开发者ID:DazzaGreenwood,项目名称:edx-platform,代码行数:47,代码来源:views.py

示例10: create_order

# 需要导入模块: from verify_student.models import SoftwareSecurePhotoVerification [as 别名]
# 或者: from verify_student.models.SoftwareSecurePhotoVerification import user_has_valid_or_pending [as 别名]
def create_order(request):
    """
    Submit PhotoVerification and create a new Order for this verified cert
    """
    if not SoftwareSecurePhotoVerification.user_has_valid_or_pending(request.user):
        attempt = SoftwareSecurePhotoVerification(user=request.user)
        try:
            b64_face_image = request.POST['face_image'].split(",")[1]
            b64_photo_id_image = request.POST['photo_id_image'].split(",")[1]
        except IndexError:
            context = {
                'success': False,
            }
            return JsonResponse(context)
        attempt.upload_face_image(b64_face_image.decode('base64'))
        attempt.upload_photo_id_image(b64_photo_id_image.decode('base64'))
        attempt.mark_ready()

        attempt.save()

    course_id = request.POST['course_id']
    course_id = CourseKey.from_string(course_id)
    donation_for_course = request.session.get('donation_for_course', {})
    current_donation = donation_for_course.get(unicode(course_id), decimal.Decimal(0))
    contribution = request.POST.get("contribution", donation_for_course.get(unicode(course_id), 0))
    try:
        amount = decimal.Decimal(contribution).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)
    except decimal.InvalidOperation:
        return HttpResponseBadRequest(_("Selected price is not valid number."))

    if amount != current_donation:
        donation_for_course[unicode(course_id)] = amount
        request.session['donation_for_course'] = donation_for_course

    # prefer professional mode over verified_mode
    current_mode = CourseMode.verified_mode_for_course(course_id)

    # make sure this course has a verified mode
    if not current_mode:
        return HttpResponseBadRequest(_("This course doesn't support verified certificates"))

    if current_mode.slug == 'professional':
        amount = current_mode.min_price

    if amount < current_mode.min_price:
        return HttpResponseBadRequest(_("No selected price or selected price is below minimum."))

    # I know, we should check this is valid. All kinds of stuff missing here
    cart = Order.get_cart_for_user(request.user)
    cart.clear()
    enrollment_mode = current_mode.slug
    CertificateItem.add_to_order(cart, course_id, amount, enrollment_mode)

    # Change the order's status so that we don't accidentally modify it later.
    # We need to do this to ensure that the parameters we send to the payment system
    # match what we store in the database.
    # (Ordinarily we would do this client-side when the user submits the form, but since
    # the JavaScript on this page does that immediately, we make the change here instead.
    # This avoids a second AJAX call and some additional complication of the JavaScript.)
    # If a user later re-enters the verification / payment flow, she will create a new order.
    cart.start_purchase()

    callback_url = request.build_absolute_uri(
        reverse("shoppingcart.views.postpay_callback")
    )

    params = get_signed_purchase_params(
        cart,
        callback_url=callback_url,
        extra_data=[unicode(course_id), current_mode.slug]
    )

    params['success'] = True
    return HttpResponse(json.dumps(params), content_type="text/json")
开发者ID:OmarIthawi,项目名称:edx-platform,代码行数:76,代码来源:views.py

示例11: check_verify_status_by_course

# 需要导入模块: from verify_student.models import SoftwareSecurePhotoVerification [as 别名]
# 或者: from verify_student.models.SoftwareSecurePhotoVerification import user_has_valid_or_pending [as 别名]
def check_verify_status_by_course(user, course_enrollments, all_course_modes):
    """
    Determine the per-course verification statuses for a given user.

    The possible statuses are:
        * VERIFY_STATUS_NEED_TO_VERIFY: The student has not yet submitted photos for verification.
        * VERIFY_STATUS_SUBMITTED: The student has submitted photos for verification,
          but has have not yet been approved.
        * VERIFY_STATUS_APPROVED: The student has been successfully verified.
        * VERIFY_STATUS_MISSED_DEADLINE: The student did not submit photos within the course's deadline.
        * VERIFY_STATUS_NEED_TO_REVERIFY: The student has an active verification, but it is
            set to expire before the verification deadline for the course.

    It is is also possible that a course does NOT have a verification status if:
        * The user is not enrolled in a verified mode, meaning that the user didn't pay.
        * The course does not offer a verified mode.
        * The user submitted photos but an error occurred while verifying them.
        * The user submitted photos but the verification was denied.

    In the last two cases, we rely on messages in the sidebar rather than displaying
    messages for each course.

    Arguments:
        user (User): The currently logged-in user.
        course_enrollments (list[CourseEnrollment]): The courses the user is enrolled in.
        all_course_modes (list): List of all course modes for the student's enrolled courses,
            including modes that have expired.

    Returns:
        dict: Mapping of course keys verification status dictionaries.
            If no verification status is applicable to a course, it will not
            be included in the dictionary.
            The dictionaries have these keys:
                * status (str): One of the enumerated status codes.
                * days_until_deadline (int): Number of days until the verification deadline.
                * verification_good_until (str): Date string for the verification expiration date.

    """
    status_by_course = {}

    # Retrieve all verifications for the user, sorted in descending
    # order by submission datetime
    verifications = SoftwareSecurePhotoVerification.objects.filter(user=user)

    # Check whether the user has an active or pending verification attempt
    # To avoid another database hit, we re-use the queryset we have already retrieved.
    has_active_or_pending = SoftwareSecurePhotoVerification.user_has_valid_or_pending(
        user, queryset=verifications
    )

    recent_verification_datetime = None

    for enrollment in course_enrollments:

        # Get the verified mode (if any) for this course
        # We pass in the course modes we have already loaded to avoid
        # another database hit, as well as to ensure that expired
        # course modes are included in the search.
        verified_mode = CourseMode.verified_mode_for_course(
            enrollment.course_id,
            modes=all_course_modes[enrollment.course_id]
        )

        # If no verified mode has ever been offered, or the user hasn't enrolled
        # as verified, then the course won't display state related to its
        # verification status.
        if verified_mode is not None and enrollment.mode in CourseMode.VERIFIED_MODES:
            deadline = verified_mode.expiration_datetime

            relevant_verification = SoftwareSecurePhotoVerification.verification_for_datetime(deadline, verifications)

            # Picking the max verification datetime on each iteration only with approved status
            if relevant_verification is not None and relevant_verification.status == "approved":
                recent_verification_datetime = max(
                    recent_verification_datetime if recent_verification_datetime is not None
                    else relevant_verification.expiration_datetime,
                    relevant_verification.expiration_datetime
                )

            # By default, don't show any status related to verification
            status = None

            # Check whether the user was approved or is awaiting approval
            if relevant_verification is not None:
                if relevant_verification.status == "approved":
                    status = VERIFY_STATUS_APPROVED
                elif relevant_verification.status == "submitted":
                    status = VERIFY_STATUS_SUBMITTED

            # If the user didn't submit at all, then tell them they need to verify
            # If the deadline has already passed, then tell them they missed it.
            # If they submitted but something went wrong (error or denied),
            # then don't show any messaging next to the course, since we already
            # show messages related to this on the left sidebar.
            submitted = (
                relevant_verification is not None and
                relevant_verification.status not in ["created", "ready"]
            )
            if status is None and not submitted:
                if deadline is None or deadline > datetime.now(UTC):
#.........这里部分代码省略.........
开发者ID:Geekathon,项目名称:edx-platform,代码行数:103,代码来源:helpers.py

示例12: check_verify_status_by_course

# 需要导入模块: from verify_student.models import SoftwareSecurePhotoVerification [as 别名]
# 或者: from verify_student.models.SoftwareSecurePhotoVerification import user_has_valid_or_pending [as 别名]
def check_verify_status_by_course(user, course_enrollment_pairs, all_course_modes):
    """Determine the per-course verification statuses for a given user.

    The possible statuses are:
        * VERIFY_STATUS_NEED_TO_VERIFY: The student has not yet submitted photos for verification.
        * VERIFY_STATUS_SUBMITTED: The student has submitted photos for verification,
          but has have not yet been approved.
        * VERIFY_STATUS_APPROVED: The student has been successfully verified.
        * VERIFY_STATUS_MISSED_DEADLINE: The student did not submit photos within the course's deadline.

    It is is also possible that a course does NOT have a verification status if:
        * The user is not enrolled in a verified mode, meaning that the user didn't pay.
        * The course does not offer a verified mode.
        * The user submitted photos but an error occurred while verifying them.
        * The user submitted photos but the verification was denied.

    In the last two cases, we rely on messages in the sidebar rather than displaying
    messages for each course.

    Arguments:
        user (User): The currently logged-in user.
        course_enrollment_pairs (list): The courses the user is enrolled in.
            The list should contain tuples of `(Course, CourseEnrollment)`.
        all_course_modes (list): List of all course modes for the student's enrolled courses,
            including modes that have expired.

    Returns:
        dict: Mapping of course keys verification status dictionaries.
            If no verification status is applicable to a course, it will not
            be included in the dictionary.
            The dictionaries have these keys:
                * status (str): One of the enumerated status codes.
                * days_until_deadline (int): Number of days until the verification deadline.
                * verification_good_until (str): Date string for the verification expiration date.

    """
    status_by_course = {}

    # Retrieve all verifications for the user, sorted in descending
    # order by submission datetime
    verifications = SoftwareSecurePhotoVerification.objects.filter(user=user)

    # Check whether the user has an active or pending verification attempt
    # To avoid another database hit, we re-use the queryset we have already retrieved.
    has_active_or_pending = SoftwareSecurePhotoVerification.user_has_valid_or_pending(user, queryset=verifications)

    for course, enrollment in course_enrollment_pairs:

        # Get the verified mode (if any) for this course
        # We pass in the course modes we have already loaded to avoid
        # another database hit, as well as to ensure that expired
        # course modes are included in the search.
        verified_mode = CourseMode.verified_mode_for_course(course.id, modes=all_course_modes[course.id])

        # If no verified mode has ever been offered, or the user hasn't enrolled
        # as verified, then the course won't display state related to its
        # verification status.
        if verified_mode is not None and enrollment.mode in CourseMode.VERIFIED_MODES:
            deadline = verified_mode.expiration_datetime
            relevant_verification = SoftwareSecurePhotoVerification.verification_for_datetime(deadline, verifications)

            # By default, don't show any status related to verification
            status = None

            # Check whether the user was approved or is awaiting approval
            if relevant_verification is not None:
                if relevant_verification.status == "approved":
                    status = VERIFY_STATUS_APPROVED
                elif relevant_verification.status == "submitted":
                    status = VERIFY_STATUS_SUBMITTED

            # If the user didn't submit at all, then tell them they need to verify
            # If the deadline has already passed, then tell them they missed it.
            # If they submitted but something went wrong (error or denied),
            # then don't show any messaging next to the course, since we already
            # show messages related to this on the left sidebar.
            submitted = relevant_verification is not None and relevant_verification.status not in ["created", "ready"]
            if status is None and not submitted:
                if deadline is None or deadline > datetime.now(UTC):
                    # If a user already has an active or pending verification,
                    # but it will expire by the deadline, the we do NOT show the
                    # verification message.  This is because we don't currently
                    # allow users to resubmit an attempt before their current
                    # attempt expires.
                    if not has_active_or_pending:
                        status = VERIFY_STATUS_NEED_TO_VERIFY
                else:
                    status = VERIFY_STATUS_MISSED_DEADLINE

            # Set the status for the course only if we're displaying some kind of message
            # Otherwise, leave the course out of the dictionary.
            if status is not None:
                days_until_deadline = None
                verification_good_until = None

                now = datetime.now(UTC)
                if deadline is not None and deadline > now:
                    days_until_deadline = (deadline - now).days

                if relevant_verification is not None:
#.........这里部分代码省略.........
开发者ID:akbargumbira,项目名称:Labster.EdX,代码行数:103,代码来源:helpers.py

示例13: create_order

# 需要导入模块: from verify_student.models import SoftwareSecurePhotoVerification [as 别名]
# 或者: from verify_student.models.SoftwareSecurePhotoVerification import user_has_valid_or_pending [as 别名]
def create_order(request):
    """
    Submit PhotoVerification and create a new Order for this verified cert
    """
    # Only submit photos if photo data is provided by the client.
    # TODO (ECOM-188): Once the A/B test of decoupling verified / payment
    # completes, we may be able to remove photo submission from this step
    # entirely.
    submit_photo = (
        'face_image' in request.POST and
        'photo_id_image' in request.POST
    )

    if (
        submit_photo and not
        SoftwareSecurePhotoVerification.user_has_valid_or_pending(request.user)
    ):
        attempt = SoftwareSecurePhotoVerification(user=request.user)
        try:
            b64_face_image = request.POST['face_image'].split(",")[1]
            b64_photo_id_image = request.POST['photo_id_image'].split(",")[1]
        except IndexError:
            log.error(u"Invalid image data during photo verification.")
            context = {
                'success': False,
            }
            return JsonResponse(context)
        attempt.upload_face_image(b64_face_image.decode('base64'))
        attempt.upload_photo_id_image(b64_photo_id_image.decode('base64'))
        attempt.mark_ready()

        attempt.save()

    course_id = request.POST['course_id']
    course_id = CourseKey.from_string(course_id)
    donation_for_course = request.session.get('donation_for_course', {})
    contribution = request.POST.get("contribution", donation_for_course.get(unicode(course_id), 0))
    try:
        amount = decimal.Decimal(contribution).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)
    except decimal.InvalidOperation:
        return HttpResponseBadRequest(_("Selected price is not valid number."))

    current_mode = None
    paid_modes = CourseMode.paid_modes_for_course(course_id)
    # Check if there are more than 1 paid(mode with min_price>0 e.g verified/professional/no-id-professional) modes
    # for course exist then choose the first one
    if paid_modes:
        if len(paid_modes) > 1:
            log.warn(u"Multiple paid course modes found for course '%s' for create order request", course_id)
        current_mode = paid_modes[0]

    # Make sure this course has a paid mode
    if not current_mode:
        log.warn(u"Create order requested for course '%s' without a paid mode.", course_id)
        return HttpResponseBadRequest(_("This course doesn't support paid certificates"))

    if CourseMode.is_professional_mode(current_mode):
        amount = current_mode.min_price

    if amount < current_mode.min_price:
        return HttpResponseBadRequest(_("No selected price or selected price is below minimum."))

    if current_mode.sku:
        return create_order_with_ecommerce_service(request.user, course_id, current_mode)

    # I know, we should check this is valid. All kinds of stuff missing here
    cart = Order.get_cart_for_user(request.user)
    cart.clear()
    enrollment_mode = current_mode.slug
    CertificateItem.add_to_order(cart, course_id, amount, enrollment_mode)

    # Change the order's status so that we don't accidentally modify it later.
    # We need to do this to ensure that the parameters we send to the payment system
    # match what we store in the database.
    # (Ordinarily we would do this client-side when the user submits the form, but since
    # the JavaScript on this page does that immediately, we make the change here instead.
    # This avoids a second AJAX call and some additional complication of the JavaScript.)
    # If a user later re-enters the verification / payment flow, she will create a new order.
    cart.start_purchase()

    callback_url = request.build_absolute_uri(
        reverse("shoppingcart.views.postpay_callback")
    )

    params = get_signed_purchase_params(
        cart,
        callback_url=callback_url,
        extra_data=[unicode(course_id), current_mode.slug]
    )

    params['success'] = True
    return HttpResponse(json.dumps(params), content_type="text/json")
开发者ID:Cgruppo,项目名称:edx-platform,代码行数:94,代码来源:views.py

示例14: submit_photos_for_verification

# 需要导入模块: from verify_student.models import SoftwareSecurePhotoVerification [as 别名]
# 或者: from verify_student.models.SoftwareSecurePhotoVerification import user_has_valid_or_pending [as 别名]
def submit_photos_for_verification(request):
    """Submit a photo verification attempt.

    Arguments:
        request (HttpRequest): The request to submit photos.

    Returns:
        HttpResponse: 200 on success, 400 if there are errors.

    """
    # Check the required parameters
    missing_params = set(['face_image', 'photo_id_image']) - set(request.POST.keys())
    if len(missing_params) > 0:
        msg = _("Missing required parameters: {missing}").format(missing=", ".join(missing_params))
        return HttpResponseBadRequest(msg)

    # If the user already has valid or pending request, the UI will hide
    # the verification steps.  For this reason, we reject any requests
    # for users that already have a valid or pending verification.
    if SoftwareSecurePhotoVerification.user_has_valid_or_pending(request.user):
        return HttpResponseBadRequest(_("You already have a valid or pending verification."))

    # If the user wants to change his/her full name,
    # then try to do that before creating the attempt.
    if request.POST.get('full_name'):
        try:
            update_account_settings(request.user, {"name": request.POST.get('full_name')})
        except UserNotFound:
            return HttpResponseBadRequest(_("No profile found for user"))
        except AccountValidationError:
            msg = _(
                "Name must be at least {min_length} characters long."
            ).format(min_length=NAME_MIN_LENGTH)
            return HttpResponseBadRequest(msg)

    # Create the attempt
    attempt = SoftwareSecurePhotoVerification(user=request.user)
    try:
        b64_face_image = request.POST['face_image'].split(",")[1]
        b64_photo_id_image = request.POST['photo_id_image'].split(",")[1]
    except IndexError:
        msg = _("Image data is not valid.")
        return HttpResponseBadRequest(msg)

    attempt.upload_face_image(b64_face_image.decode('base64'))
    attempt.upload_photo_id_image(b64_photo_id_image.decode('base64'))
    attempt.mark_ready()
    attempt.submit()

    account_settings = get_account_settings(request.user)

    # Send a confirmation email to the user
    context = {
        'full_name': account_settings['name'],
        'platform_name': settings.PLATFORM_NAME
    }

    subject = _("Verification photos received")
    message = render_to_string('emails/photo_submission_confirmation.txt', context)
    from_address = microsite.get_value('default_from_email', settings.DEFAULT_FROM_EMAIL)
    to_address = account_settings['email']

    send_mail(subject, message, from_address, [to_address], fail_silently=False)

    return HttpResponse(200)
开发者ID:Cgruppo,项目名称:edx-platform,代码行数:67,代码来源:views.py

示例15: create_order

# 需要导入模块: from verify_student.models import SoftwareSecurePhotoVerification [as 别名]
# 或者: from verify_student.models.SoftwareSecurePhotoVerification import user_has_valid_or_pending [as 别名]
def create_order(request):
    """
    Submit PhotoVerification and create a new Order for this verified cert
    """
    # Only submit photos if photo data is provided by the client.
    # TODO (ECOM-188): Once the A/B test of decoupling verified / payment
    # completes, we may be able to remove photo submission from this step
    # entirely.
    submit_photo = "face_image" in request.POST and "photo_id_image" in request.POST

    if submit_photo and not SoftwareSecurePhotoVerification.user_has_valid_or_pending(request.user):
        attempt = SoftwareSecurePhotoVerification(user=request.user)
        try:
            b64_face_image = request.POST["face_image"].split(",")[1]
            b64_photo_id_image = request.POST["photo_id_image"].split(",")[1]
        except IndexError:
            log.error(u"Invalid image data during photo verification.")
            context = {"success": False}
            return JsonResponse(context)
        attempt.upload_face_image(b64_face_image.decode("base64"))
        attempt.upload_photo_id_image(b64_photo_id_image.decode("base64"))
        attempt.mark_ready()

        attempt.save()

    course_id = request.POST["course_id"]
    course_id = CourseKey.from_string(course_id)
    donation_for_course = request.session.get("donation_for_course", {})
    current_donation = donation_for_course.get(unicode(course_id), decimal.Decimal(0))
    contribution = request.POST.get("contribution", donation_for_course.get(unicode(course_id), 0))
    try:
        amount = decimal.Decimal(contribution).quantize(decimal.Decimal(".01"), rounding=decimal.ROUND_DOWN)
    except decimal.InvalidOperation:
        return HttpResponseBadRequest(_("Selected price is not valid number."))

    if amount != current_donation:
        donation_for_course[unicode(course_id)] = amount
        request.session["donation_for_course"] = donation_for_course

    # prefer professional mode over verified_mode
    current_mode = CourseMode.verified_mode_for_course(course_id)

    # make sure this course has a verified mode
    if not current_mode:
        log.warn(u"Verification requested for course {course_id} without a verified mode.".format(course_id=course_id))
        return HttpResponseBadRequest(_("This course doesn't support verified certificates"))

    if current_mode.slug == "professional":
        amount = current_mode.min_price

    if amount < current_mode.min_price:
        return HttpResponseBadRequest(_("No selected price or selected price is below minimum."))

    # I know, we should check this is valid. All kinds of stuff missing here
    cart = Order.get_cart_for_user(request.user)
    cart.clear()
    enrollment_mode = current_mode.slug
    CertificateItem.add_to_order(cart, course_id, amount, enrollment_mode, currency=current_mode.currency)

    # Change the order's status so that we don't accidentally modify it later.
    # We need to do this to ensure that the parameters we send to the payment system
    # match what we store in the database.
    # (Ordinarily we would do this client-side when the user submits the form, but since
    # the JavaScript on this page does that immediately, we make the change here instead.
    # This avoids a second AJAX call and some additional complication of the JavaScript.)
    # If a user later re-enters the verification / payment flow, she will create a new order.
    cart.start_purchase()

    callback_url = request.build_absolute_uri(reverse("shoppingcart.views.postpay_callback"))

    params = get_signed_purchase_params(
        cart, callback_url=callback_url, extra_data=[unicode(course_id), current_mode.slug]
    )

    # params['success'] = True
    # return HttpResponse(json.dumps(params), content_type="text/json")

    processor = settings.CC_PROCESSOR.get(settings.CC_PROCESSOR_NAME, {})

    callback_data = {
        "description": "Верифікований сертифікат",
        "order_id": cart.id,
        "server_url": processor.get("SERVER_URL", ""),
        "currency": processor.get("CURRENCY", ""),
        "result_url": processor.get("RESULT_URL", ""),
        "public_key": processor.get("PUBLIC_KEY", ""),
        "language": processor.get("LANGUAGE", "en"),
        "pay_way": processor.get("PAY_WAY", ""),
        "amount": current_mode.min_price,
        "sandbox": processor.get("SANDBOX", 0),
        "version": processor.get("VERSION", 3),
        "type": "buy",
    }
    log.warn(json.dumps(callback_data))

    #    callback_data = {
    #        "description": "Верифікований сертифікат",
    #        "order_id": cart.id,
    #        "server_url": "http://courses.prometheus.org.ua/shoppingcart/postpay_callback/",
    #        "currency": "UAH",
#.........这里部分代码省略.........
开发者ID:olexiim,项目名称:edx-platform,代码行数:103,代码来源:views.py


注:本文中的verify_student.models.SoftwareSecurePhotoVerification.user_has_valid_or_pending方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。