views.py 48 KB
Newer Older
1
"""
2
Views for the verification flow
3
"""
4 5 6

import datetime
import decimal
7
import json
8
import logging
9
import urllib
10

11 12
import analytics
import waffle
13
from django.conf import settings
14
from django.contrib.auth.decorators import login_required
15
from django.contrib.staticfiles.storage import staticfiles_storage
16
from django.core.mail import send_mail
17
from django.core.urlresolvers import reverse
18
from django.db import transaction
19
from django.http import Http404, HttpResponse, HttpResponseBadRequest
20
from django.shortcuts import redirect
21
from django.utils.decorators import method_decorator
22 23
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_lazy
24 25
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
Ned Batchelder committed
26
from django.views.generic.base import View
27 28
from edx_rest_api_client.exceptions import SlumberBaseException
from ipware.ip import get_ip
29
from opaque_keys import InvalidKeyError
Eric Fischer committed
30
from opaque_keys.edx.keys import CourseKey
31
from pytz import UTC
32

33
from commerce.utils import EcommerceService, is_account_activation_requirement_disabled
34
from course_modes.models import CourseMode
35
from edxmako.shortcuts import render_to_response, render_to_string
36 37 38 39
from eventtracking import tracker
from lms.djangoapps.verify_student.image import InvalidImageData, decode_image_data
from lms.djangoapps.verify_student.models import SoftwareSecurePhotoVerification, VerificationDeadline
from lms.djangoapps.verify_student.ssencrypt import has_valid_signature
40
from openedx.core.djangoapps.commerce.utils import ecommerce_api_client
41 42
from openedx.core.djangoapps.embargo import api as embargo_api
from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers
43
from openedx.core.djangoapps.user_api.accounts import NAME_MIN_LENGTH
44
from openedx.core.djangoapps.user_api.accounts.api import update_account_settings
45
from openedx.core.djangoapps.user_api.errors import AccountValidationError, UserNotFound
46
from openedx.core.lib.log_utils import audit_log
47 48
from shoppingcart.models import CertificateItem, Order
from shoppingcart.processors import get_purchase_endpoint, get_signed_purchase_params
49
from student.models import CourseEnrollment
50
from util.db import outer_atomic
51
from util.json_request import JsonResponse
52
from xmodule.modulestore.django import modulestore
53

54
log = logging.getLogger(__name__)
55

56

57
class PayAndVerifyView(View):
58 59
    """
    View for the "verify and pay" flow.
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

    This view is somewhat complicated, because the user
    can enter it from a number of different places:

    * From the "choose your track" page.
    * After completing payment.
    * From the dashboard in order to complete verification.
    * From the dashboard in order to upgrade to a verified track.

    The page will display different steps and requirements
    depending on:

    * Whether the user has submitted a photo verification recently.
    * Whether the user has paid for the course.
    * How the user reached the page (mostly affects messaging)

    We are also super-paranoid about how users reach this page.
    If they somehow aren't enrolled, or the course doesn't exist,
    or they've unenrolled, or they've already paid/verified,
    ... then we try to redirect them to the page with the
    most appropriate messaging (including the dashboard).

    Note that this page does NOT handle re-verification
    (photo verification that was denied or had an error);
    that is handled by the "reverify" view.

    """

    # Step definitions
    #
    # These represent the numbered steps a user sees in
    # the verify / payment flow.
    #
    # Steps can either be:
    # - displayed or hidden
    # - complete or incomplete
    #
    # For example, when a user enters the verification/payment
    # flow for the first time, the user will see steps
    # for both payment and verification.  As the user
    # completes these steps (for example, submitting a photo)
    # the steps will be marked "complete".
    #
    # If a user has already verified for another course,
    # then the verification steps will be hidden,
    # since the user has already completed them.
    #
    # If a user re-enters the flow from another application
    # (for example, after completing payment through
    # a third-party payment processor), then the user
    # will resume the flow at an intermediate step.
    #
    INTRO_STEP = 'intro-step'
    MAKE_PAYMENT_STEP = 'make-payment-step'
    PAYMENT_CONFIRMATION_STEP = 'payment-confirmation-step'
    FACE_PHOTO_STEP = 'face-photo-step'
    ID_PHOTO_STEP = 'id-photo-step'
    REVIEW_PHOTOS_STEP = 'review-photos-step'
    ENROLLMENT_CONFIRMATION_STEP = 'enrollment-confirmation-step'

    ALL_STEPS = [
        INTRO_STEP,
        MAKE_PAYMENT_STEP,
        PAYMENT_CONFIRMATION_STEP,
        FACE_PHOTO_STEP,
        ID_PHOTO_STEP,
        REVIEW_PHOTOS_STEP,
        ENROLLMENT_CONFIRMATION_STEP
    ]

    PAYMENT_STEPS = [
        MAKE_PAYMENT_STEP,
        PAYMENT_CONFIRMATION_STEP
    ]

    VERIFICATION_STEPS = [
        FACE_PHOTO_STEP,
        ID_PHOTO_STEP,
        REVIEW_PHOTOS_STEP,
        ENROLLMENT_CONFIRMATION_STEP
    ]

142
    # These steps can be skipped using the ?skip-first-step GET param
143 144 145 146
    SKIP_STEPS = [
        INTRO_STEP,
    ]

147 148 149 150 151 152 153 154
    STEP_TITLES = {
        INTRO_STEP: ugettext_lazy("Intro"),
        MAKE_PAYMENT_STEP: ugettext_lazy("Make payment"),
        PAYMENT_CONFIRMATION_STEP: ugettext_lazy("Payment confirmation"),
        FACE_PHOTO_STEP: ugettext_lazy("Take photo"),
        ID_PHOTO_STEP: ugettext_lazy("Take a photo of your ID"),
        REVIEW_PHOTOS_STEP: ugettext_lazy("Review your info"),
        ENROLLMENT_CONFIRMATION_STEP: ugettext_lazy("Enrollment confirmation"),
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
    }

    # Messages
    #
    # Depending on how the user entered reached the page,
    # we will display different text messaging.
    # For example, we show users who are upgrading
    # slightly different copy than users who are verifying
    # for the first time.
    #
    FIRST_TIME_VERIFY_MSG = 'first-time-verify'
    VERIFY_NOW_MSG = 'verify-now'
    VERIFY_LATER_MSG = 'verify-later'
    UPGRADE_MSG = 'upgrade'
    PAYMENT_CONFIRMATION_MSG = 'payment-confirmation'

    # Requirements
    #
    # These explain to the user what he or she
    # will need to successfully pay and/or verify.
    #
    # These are determined by the steps displayed
    # to the user; for example, if the user does not
    # need to complete the verification steps,
    # then the photo ID and webcam requirements are hidden.
    #
181
    ACCOUNT_ACTIVATION_REQ = "account-activation-required"
182 183 184 185 186 187 188 189
    PHOTO_ID_REQ = "photo-id-required"
    WEBCAM_REQ = "webcam-required"

    STEP_REQUIREMENTS = {
        ID_PHOTO_STEP: [PHOTO_ID_REQ, WEBCAM_REQ],
        FACE_PHOTO_STEP: [WEBCAM_REQ],
    }

190 191 192 193
    # Deadline types
    VERIFICATION_DEADLINE = "verification"
    UPGRADE_DEADLINE = "upgrade"

194 195 196 197 198 199 200 201
    def _get_user_active_status(self, user):
        """
        Returns the user's active status to the caller
        Overrides the actual value if account activation has been disabled via waffle switch

        Arguments:
            user (User): Current user involved in the onboarding/verification flow
        """
202
        return user.is_active or is_account_activation_requirement_disabled()
203

204 205 206 207
    @method_decorator(login_required)
    def get(
        self, request, course_id,
        always_show_payment=False,
208
        current_step=None,
209 210
        message=FIRST_TIME_VERIFY_MSG
    ):
211 212
        """
        Render the payment and verification flow.
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238

        Arguments:
            request (HttpRequest): The request object.
            course_id (unicode): The ID of the course the user is trying
                to enroll in.

        Keyword Arguments:
            always_show_payment (bool): If True, show the payment steps
                even if the user has already paid.  This is useful
                for users returning to the flow after paying.
            current_step (string): The current step in the flow.
            message (string): The messaging to display.

        Returns:
            HttpResponse

        Raises:
            Http404: The course does not exist or does not
                have a verified mode.

        """
        # Parse the course key
        # The URL regex should guarantee that the key format is valid.
        course_key = CourseKey.from_string(course_id)
        course = modulestore().get_course(course_key)

239
        # Verify that the course exists
240
        if course is None:
241
            log.warn(u"Could not find course with ID %s.", course_id)
242 243
            raise Http404

244 245 246 247 248 249 250 251 252 253 254
        # Check whether the user has access to this course
        # based on country access rules.
        redirect_url = embargo_api.redirect_if_blocked(
            course_key,
            user=request.user,
            ip_address=get_ip(request),
            url=request.path
        )
        if redirect_url:
            return redirect(redirect_url)

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
        # If the verification deadline has passed
        # then show the user a message that he/she can't verify.
        #
        # We're making the assumptions (enforced in Django admin) that:
        #
        # 1) Only verified modes have verification deadlines.
        #
        # 2) If set, verification deadlines are always AFTER upgrade deadlines, because why would you
        #   let someone upgrade into a verified track if they can't complete verification?
        #
        verification_deadline = VerificationDeadline.deadline_for_course(course.id)
        response = self._response_if_deadline_passed(course, self.VERIFICATION_DEADLINE, verification_deadline)
        if response is not None:
            log.info(u"Verification deadline for '%s' has passed.", course.id)
            return response

        # Retrieve the relevant course mode for the payment/verification flow.
        #
        # WARNING: this is technical debt!  A much better way to do this would be to
        # separate out the payment flow and use the product SKU to figure out what
        # the user is trying to purchase.
        #
277
        # Nonetheless, for the time being we continue to make the really ugly assumption
278 279 280 281 282 283 284
        # that at some point there was a paid course mode we can query for the price.
        relevant_course_mode = self._get_paid_mode(course_key)

        # If we can find a relevant course mode, then log that we're entering the flow
        # Otherwise, this course does not support payment/verification, so respond with a 404.
        if relevant_course_mode is not None:
            if CourseMode.is_verified_mode(relevant_course_mode):
285
                log.info(
286
                    u"Entering payment and verification flow for user '%s', course '%s', with current step '%s'.",
287 288
                    request.user.id, course_id, current_step
                )
289 290 291 292
            else:
                log.info(
                    u"Entering payment flow for user '%s', course '%s', with current step '%s'",
                    request.user.id, course_id, current_step
293 294
                )
        else:
295
            # Otherwise, there has never been a verified/paid mode,
296
            # so return a page not found response.
297
            log.warn(
298
                u"No paid/verified course mode found for course '%s' for verification/payment flow request",
299
                course_id
300
            )
301 302
            raise Http404

303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
        # If the user is trying to *pay* and the upgrade deadline has passed,
        # then they shouldn't be able to enter the flow.
        #
        # NOTE: This should match the availability dates used by the E-Commerce service
        # to determine whether a user can purchase a product.  The idea is that if the service
        # won't fulfill the order, we shouldn't even let the user get into the payment flow.
        #
        user_is_trying_to_pay = message in [self.FIRST_TIME_VERIFY_MSG, self.UPGRADE_MSG]
        if user_is_trying_to_pay:
            upgrade_deadline = relevant_course_mode.expiration_datetime
            response = self._response_if_deadline_passed(course, self.UPGRADE_DEADLINE, upgrade_deadline)
            if response is not None:
                log.info(u"Upgrade deadline for '%s' has passed.", course.id)
                return response

318 319 320 321 322
        # Check whether the user has verified, paid, and enrolled.
        # A user is considered "paid" if he or she has an enrollment
        # with a paid course mode (such as "verified").
        # For this reason, every paid user is enrolled, but not
        # every enrolled user is paid.
323
        # If the course mode is not verified(i.e only paid) then already_verified is always True
324 325 326 327 328
        already_verified = (
            self._check_already_verified(request.user)
            if CourseMode.is_verified_mode(relevant_course_mode)
            else True
        )
329 330 331 332 333
        already_paid, is_enrolled = self._check_enrollment(request.user, course_key)

        # Redirect the user to a more appropriate page if the
        # messaging won't make sense based on the user's
        # enrollment / payment / verification status.
334 335 336 337
        sku_to_use = relevant_course_mode.sku
        purchase_workflow = request.GET.get('purchase_workflow', 'single')
        if purchase_workflow == 'bulk' and relevant_course_mode.bulk_sku:
            sku_to_use = relevant_course_mode.bulk_sku
338 339 340 341 342
        redirect_response = self._redirect_if_necessary(
            message,
            already_verified,
            already_paid,
            is_enrolled,
343 344 345
            course_key,
            user_is_trying_to_pay,
            request.user,
346
            sku_to_use
347 348 349 350 351 352 353
        )
        if redirect_response is not None:
            return redirect_response

        display_steps = self._display_steps(
            always_show_payment,
            already_verified,
354
            already_paid,
355
            relevant_course_mode
356
        )
357 358 359 360 361

        # Override the actual value if account activation has been disabled
        # Also see the reference to this parameter in context dictionary further down
        user_is_active = self._get_user_active_status(request.user)
        requirements = self._requirements(display_steps, user_is_active)
362

363 364 365
        if current_step is None:
            current_step = display_steps[0]['name']

366 367 368
        # Allow the caller to skip the first page
        # This is useful if we want the user to be able to
        # use the "back" button to return to the previous step.
369 370
        # This parameter should only work for known skip-able steps
        if request.GET.get('skip-first-step') and current_step in self.SKIP_STEPS:
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
            display_step_names = [step['name'] for step in display_steps]
            current_step_idx = display_step_names.index(current_step)
            if (current_step_idx + 1) < len(display_steps):
                current_step = display_steps[current_step_idx + 1]['name']

        courseware_url = ""
        if not course.start or course.start < datetime.datetime.today().replace(tzinfo=UTC):
            courseware_url = reverse(
                'course_root',
                kwargs={'course_id': unicode(course_key)}
            )

        full_name = (
            request.user.profile.name
            if request.user.profile.name
            else ""
        )

389 390 391 392 393 394
        # If the user set a contribution amount on another page,
        # use that amount to pre-fill the price selection form.
        contribution_amount = request.session.get(
            'donation_for_course', {}
        ).get(unicode(course_key), '')

395 396 397 398
        # Remember whether the user is upgrading
        # so we can fire an analytics event upon payment.
        request.session['attempting_upgrade'] = (message == self.UPGRADE_MSG)

399 400 401
        # Determine the photo verification status
        verification_good_until = self._verification_valid_until(request.user)

jsa committed
402
        # get available payment processors
403
        if relevant_course_mode.sku:
jsa committed
404
            # transaction will be conducted via ecommerce service
405
            processors = ecommerce_api_client(request.user).payment.processors.get()
jsa committed
406 407 408 409
        else:
            # transaction will be conducted using legacy shopping cart
            processors = [settings.CC_PROCESSOR_NAME]

410 411
        # Render the top-level page
        context = {
412
            'contribution_amount': contribution_amount,
413
            'course': course,
414
            'course_key': unicode(course_key),
415
            'checkpoint_location': request.GET.get('checkpoint'),
416
            'course_mode': relevant_course_mode,
417
            'courseware_url': courseware_url,
418
            'current_step': current_step,
419 420
            'disable_courseware_js': True,
            'display_steps': display_steps,
421
            'is_active': json.dumps(user_is_active),
422
            'user_email': request.user.email,
423
            'message_key': message,
424
            'platform_name': configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME),
jsa committed
425
            'processors': processors,
426
            'requirements': requirements,
427
            'user_full_name': full_name,
428
            'verification_deadline': verification_deadline or "",
429 430
            'already_verified': already_verified,
            'verification_good_until': verification_good_until,
431
            'capture_sound': staticfiles_storage.url("audio/camera_capture.wav"),
432
            'nav_hidden': True,
433
            'is_ab_testing': 'begin-flow' in request.path,
434
        }
435

436 437
        return render_to_response("verify_student/pay_and_verify.html", context)

438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
    def add_utm_params_to_url(self, url):
        # utm_params is [(u'utm_content', u'course-v1:IDBx IDB20.1x 1T2017'),...
        utm_params = [item for item in self.request.GET.items() if 'utm_' in item[0]]
        # utm_params is utm_content=course-v1%3AIDBx+IDB20.1x+1T2017&...
        utm_params = urllib.urlencode(utm_params, True)
        # utm_params is utm_content=course-v1:IDBx+IDB20.1x+1T2017&...
        # (course-keys do not have url encoding)
        utm_params = urllib.unquote(utm_params)
        if utm_params:
            if '?' in url:
                url = url + '&' + utm_params
            else:
                url = url + '?' + utm_params
        return url

453
    def _redirect_if_necessary(
454 455
            self, message, already_verified, already_paid, is_enrolled, course_key,  # pylint: disable=bad-continuation
            user_is_trying_to_pay, user, sku  # pylint: disable=bad-continuation
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
    ):
        """Redirect the user to a more appropriate page if necessary.

        In some cases, a user may visit this page with
        verification / enrollment / payment state that
        we don't anticipate.  For example, a user may unenroll
        from the course after paying for it, then visit the
        "verify now" page to complete verification.

        When this happens, we try to redirect the user to
        the most appropriate page.

        Arguments:

            message (string): The messaging of the page.  Should be a key
                in `MESSAGES`.

            already_verified (bool): Whether the user has submitted
                a verification request recently.

            already_paid (bool): Whether the user is enrolled in a paid
                course mode.

            is_enrolled (bool): Whether the user has an active enrollment
                in the course.

            course_key (CourseKey): The key for the course.

        Returns:
            HttpResponse or None

        """
        url = None
        course_kwargs = {'course_id': unicode(course_key)}

        if already_verified and already_paid:
            # If they've already paid and verified, there's nothing else to do,
            # so redirect them to the dashboard.
            if message != self.PAYMENT_CONFIRMATION_MSG:
                url = reverse('dashboard')
        elif message in [self.VERIFY_NOW_MSG, self.VERIFY_LATER_MSG, self.PAYMENT_CONFIRMATION_MSG]:
            if is_enrolled:
                # If the user is already enrolled but hasn't yet paid,
                # then the "upgrade" messaging is more appropriate.
                if not already_paid:
                    url = reverse('verify_student_upgrade_and_verify', kwargs=course_kwargs)
            else:
                # If the user is NOT enrolled, then send him/her
                # to the first time verification page.
                url = reverse('verify_student_start_flow', kwargs=course_kwargs)
        elif message == self.UPGRADE_MSG:
            if is_enrolled:
                if already_paid:
509 510
                    # If the student has paid, but not verified, redirect to the verification flow.
                    url = reverse('verify_student_verify_now', kwargs=course_kwargs)
511 512 513
            else:
                url = reverse('verify_student_start_flow', kwargs=course_kwargs)

514
        if user_is_trying_to_pay and self._get_user_active_status(user) and not already_paid:
515
            # If the user is trying to pay, has activated their account, and the ecommerce service
516 517 518
            # is enabled redirect him to the ecommerce checkout page.
            ecommerce_service = EcommerceService()
            if ecommerce_service.is_enabled(user):
519
                url = ecommerce_service.get_checkout_page_url(sku)
520

521 522
        # Redirect if necessary, otherwise implicitly return None
        if url is not None:
523
            url = self.add_utm_params_to_url(url)
524 525
            return redirect(url)

526 527 528 529 530 531
    def _get_paid_mode(self, course_key):
        """
        Retrieve the paid course mode for a course.

        The returned course mode may or may not be expired.
        Unexpired modes are preferred to expired modes.
532 533 534 535 536

        Arguments:
            course_key (CourseKey): The location of the course.

        Returns:
537
            CourseMode tuple
538 539 540 541 542

        """
        # Retrieve all the modes at once to reduce the number of database queries
        all_modes, unexpired_modes = CourseMode.all_and_unexpired_modes_for_courses([course_key])

543 544 545 546
        # Retrieve the first mode that matches the following criteria:
        #  * Unexpired
        #  * Price > 0
        #  * Not credit
547
        for mode in unexpired_modes[course_key]:
548
            if mode.min_price > 0 and not CourseMode.is_credit_mode(mode):
549
                return mode
550

551
        # Otherwise, find the first non credit expired paid mode
552
        for mode in all_modes[course_key]:
553
            if mode.min_price > 0 and not CourseMode.is_credit_mode(mode):
554
                return mode
555

556 557
        # Otherwise, return None and so the view knows to respond with a 404.
        return None
558

559
    def _display_steps(self, always_show_payment, already_verified, already_paid, course_mode):
560 561 562 563 564 565
        """Determine which steps to display to the user.

        Includes all steps by default, but removes steps
        if the user has already completed them.

        Arguments:
566

567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
            always_show_payment (bool): If True, display the payment steps
                even if the user has already paid.

            already_verified (bool): Whether the user has submitted
                a verification request recently.

            already_paid (bool): Whether the user is enrolled in a paid
                course mode.

        Returns:
            list

        """
        display_steps = self.ALL_STEPS
        remove_steps = set()

583
        if already_verified or not CourseMode.is_verified_mode(course_mode):
584 585 586 587
            remove_steps |= set(self.VERIFICATION_STEPS)

        if already_paid and not always_show_payment:
            remove_steps |= set(self.PAYMENT_STEPS)
588 589 590 591
        else:
            # The "make payment" step doubles as an intro step,
            # so if we're showing the payment step, hide the intro step.
            remove_steps |= set([self.INTRO_STEP])
592 593 594
        return [
            {
                'name': step,
595
                'title': unicode(self.STEP_TITLES[step]),
596 597 598 599 600
            }
            for step in display_steps
            if step not in remove_steps
        ]

601
    def _requirements(self, display_steps, is_active):
602 603 604 605 606 607 608 609
        """Determine which requirements to show the user.

        For example, if the user needs to submit a photo
        verification, tell the user that she will need
        a photo ID and a webcam.

        Arguments:
            display_steps (list): The steps to display to the user.
610
            is_active (bool): If False, adds a requirement to activate the user account.
611 612 613 614 615 616 617

        Returns:
            dict: Keys are requirement names, values are booleans
                indicating whether to show the requirement.

        """
        all_requirements = {
618
            self.ACCOUNT_ACTIVATION_REQ: not is_active,
619 620 621 622
            self.PHOTO_ID_REQ: False,
            self.WEBCAM_REQ: False,
        }

623
        # Remove the account activation requirement if disabled via waffle
624
        if is_account_activation_requirement_disabled():
625 626
            all_requirements.pop(self.ACCOUNT_ACTIVATION_REQ)

627 628 629 630 631 632 633 634 635
        display_steps = set(step['name'] for step in display_steps)

        for step, step_requirements in self.STEP_REQUIREMENTS.iteritems():
            if step in display_steps:
                for requirement in step_requirements:
                    all_requirements[requirement] = True

        return all_requirements

636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
    def _verification_valid_until(self, user, date_format="%m/%d/%Y"):
        """
        Check whether the user has a valid or pending verification.

        Arguments:
            user:
            date_format: optional parameter for formatting datetime
                object to string in response

        Returns:
            datetime object in string format
        """
        photo_verifications = SoftwareSecurePhotoVerification.verification_valid_or_pending(user)
        # return 'expiration_datetime' of latest photo verification if found,
        # otherwise implicitly return ''
        if photo_verifications:
            return photo_verifications[0].expiration_datetime.strftime(date_format)

        return ''

656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
    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)

    def _check_enrollment(self, user, course_key):
        """Check whether the user has an active enrollment and has paid.

        If a user is enrolled in a paid course mode, we assume
        that the user has paid.

        Arguments:
            user (User): The user to check.
            course_key (CourseKey): The key of the course to check.

        Returns:
            Tuple `(has_paid, is_active)` indicating whether the user
            has paid and whether the user has an active account.

        """
        enrollment_mode, is_active = CourseEnrollment.enrollment_mode_for_user(user, course_key)
        has_paid = False

        if enrollment_mode is not None and is_active:
688
            all_modes = CourseMode.modes_for_course_dict(course_key, include_expired=True)
689 690 691 692 693
            course_mode = all_modes.get(enrollment_mode)
            has_paid = (course_mode and course_mode.min_price > 0)

        return (has_paid, bool(is_active))

694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
    def _response_if_deadline_passed(self, course, deadline_name, deadline_datetime):
        """
        Respond with some error messaging if the deadline has passed.

        Arguments:
            course (Course): The course the user is trying to enroll in.
            deadline_name (str): One of the deadline constants.
            deadline_datetime (datetime): The deadline.

        Returns: HttpResponse or None

        """
        if deadline_name not in [self.VERIFICATION_DEADLINE, self.UPGRADE_DEADLINE]:
            log.error("Invalid deadline name %s.  Skipping check for whether the deadline passed.", deadline_name)
            return None

        deadline_passed = (
            deadline_datetime is not None and
            deadline_datetime < datetime.datetime.now(UTC)
        )
        if deadline_passed:
            context = {
                'course': course,
                'deadline_name': deadline_name,
718
                'deadline': deadline_datetime
719 720 721
            }
            return render_to_response("verify_student/missed_deadline.html", context)

722

723
def checkout_with_ecommerce_service(user, course_key, course_mode, processor):
jsa committed
724
    """ Create a new basket and trigger immediate checkout, using the E-Commerce API. """
725
    course_id = unicode(course_key)
726
    try:
727
        api = ecommerce_api_client(user)
728
        # Make an API call to create the order and retrieve the results
729 730 731 732 733
        result = api.baskets.post({
            'products': [{'sku': course_mode.sku}],
            'checkout': True,
            'payment_processor_name': processor
        })
734

735
        # Pass the payment parameters directly from the API response.
736
        return result.get('payment_data')
737
    except SlumberBaseException:
738
        params = {'username': user.username, 'mode': course_mode.slug, 'course_id': course_id}
739
        log.exception('Failed to create order for %(username)s %(mode)s mode of %(course_id)s', params)
740
        raise
741 742 743 744 745 746 747 748
    finally:
        audit_log(
            'checkout_requested',
            course_id=course_id,
            mode=course_mode.slug,
            processor_name=processor,
            user_id=user.id
        )
749 750


jsa committed
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
def checkout_with_shoppingcart(request, user, course_key, course_mode, amount):
    """ Create an order and trigger checkout using shoppingcart."""
    cart = Order.get_cart_for_user(user)
    cart.clear()
    enrollment_mode = course_mode.slug
    CertificateItem.add_to_order(cart, course_key, 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")
    )

    payment_data = {
        'payment_processor_name': settings.CC_PROCESSOR_NAME,
        'payment_page_url': get_purchase_endpoint(),
        'payment_form_data': get_signed_purchase_params(
            cart,
            callback_url=callback_url,
            extra_data=[unicode(course_key), course_mode.slug]
        ),
    }
    return payment_data


783
@require_POST
784
@login_required
785
def create_order(request):
786
    """
jsa committed
787 788 789
    This endpoint is named 'create_order' for backward compatibility, but its
    actual use is to add a single product to the user's cart and request
    immediate checkout.
790
    """
791
    course_id = request.POST['course_id']
792
    course_id = CourseKey.from_string(course_id)
793
    donation_for_course = request.session.get('donation_for_course', {})
794
    contribution = request.POST.get("contribution", donation_for_course.get(unicode(course_id), 0))
795 796 797 798
    try:
        amount = decimal.Decimal(contribution).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)
    except decimal.InvalidOperation:
        return HttpResponseBadRequest(_("Selected price is not valid number."))
799

800
    current_mode = None
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
    sku = request.POST.get('sku', None)

    if sku:
        try:
            current_mode = CourseMode.objects.get(sku=sku)
        except CourseMode.DoesNotExist:
            log.exception(u'Failed to find CourseMode with SKU [%s].', sku)

    if not current_mode:
        # 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
        paid_modes = CourseMode.paid_modes_for_course(course_id)
        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]
817

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

823
    if CourseMode.is_professional_mode(current_mode):
824 825
        amount = current_mode.min_price

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

829
    if current_mode.sku:
jsa committed
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
        # if request.POST doesn't contain 'processor' then the service's default payment processor will be used.
        payment_data = checkout_with_ecommerce_service(
            request.user,
            course_id,
            current_mode,
            request.POST.get('processor')
        )
    else:
        payment_data = checkout_with_shoppingcart(request, request.user, course_id, current_mode, amount)

    if 'processor' not in request.POST:
        # (XCOM-214) To be removed after release.
        # the absence of this key in the POST payload indicates that the request was initiated from
        # a stale js client, which expects a response containing only the 'payment_form_data' part of
        # the payment data result.
        payment_data = payment_data['payment_form_data']
    return HttpResponse(json.dumps(payment_data), content_type="application/json")
847

848

849 850 851 852
class SubmitPhotosView(View):
    """
    End-point for submitting photos for verification.
    """
853

854 855 856 857
    @method_decorator(transaction.non_atomic_requests)
    def dispatch(self, *args, **kwargs):    # pylint: disable=missing-docstring
        return super(SubmitPhotosView, self).dispatch(*args, **kwargs)

858
    @method_decorator(login_required)
859
    @method_decorator(outer_atomic(read_committed=True))
860 861 862
    def post(self, request):
        """
        Submit photos for verification.
863

864
        This end-point is used for the following cases:
865

866 867 868 869 870 871 872 873 874 875 876 877 878 879
        * Initial verification through the pay-and-verify flow.
        * Initial verification initiated from a checkpoint within a course.
        * Re-verification initiated from a checkpoint within a course.

        POST Parameters:

            face_image (str): base64-encoded image data of the user's face.
            photo_id_image (str): base64-encoded image data of the user's photo ID.
            full_name (str): The user's full name, if the user is requesting a name change as well.
            course_key (str): Identifier for the course, if initiated from a checkpoint.
            checkpoint (str): Location of the checkpoint in the course.

        """
        # If the user already has an initial verification attempt, we can re-use the photo ID
Eric Fischer committed
880
        # the user submitted with the initial attempt.
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
        initial_verification = SoftwareSecurePhotoVerification.get_initial_verification(request.user)

        # Validate the POST parameters
        params, response = self._validate_parameters(request, bool(initial_verification))
        if response is not None:
            return response

        # If necessary, update the user's full name
        if "full_name" in params:
            response = self._update_full_name(request.user, params["full_name"])
            if response is not None:
                return response

        # Retrieve the image data
        # Validation ensures that we'll have a face image, but we may not have
        # a photo ID image if this is a reverification.
        face_image, photo_id_image, response = self._decode_image_data(
            params["face_image"], params.get("photo_id_image")
        )
900 901 902 903 904

        # If we have a photo_id we do not want use the initial verification image.
        if photo_id_image is not None:
            initial_verification = None

905 906 907 908 909 910
        if response is not None:
            return response

        # Submit the attempt
        attempt = self._submit_attempt(request.user, face_image, photo_id_image, initial_verification)

Eric Fischer committed
911 912 913
        self._fire_event(request.user, "edx.bi.verify.submitted", {"category": "verification"})
        self._send_confirmation_email(request.user)
        return JsonResponse({})
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982

    def _validate_parameters(self, request, has_initial_verification):
        """
        Check that the POST parameters are valid.

        Arguments:
            request (HttpRequest): The request object.
            has_initial_verification (bool): Whether the user has an initial verification attempt.

        Returns:
            HttpResponse or None

        """
        # Pull out the parameters we care about.
        params = {
            param_name: request.POST[param_name]
            for param_name in [
                "face_image",
                "photo_id_image",
                "course_key",
                "full_name"
            ]
            if param_name in request.POST
        }

        # If the user already has an initial verification attempt, then we don't
        # require the user to submit a photo ID image, since we can re-use the photo ID
        # image from the initial attempt.
        # If we don't have an initial verification OR a photo ID image, something has gone
        # terribly wrong in the JavaScript.  Log this as an error so we can track it down.
        if "photo_id_image" not in params and not has_initial_verification:
            log.error(
                (
                    "User %s does not have an initial verification attempt "
                    "and no photo ID image data was provided. "
                    "This most likely means that the JavaScript client is not "
                    "correctly constructing the request to submit photos."
                ), request.user.id
            )
            return None, HttpResponseBadRequest(
                _("Photo ID image is required if the user does not have an initial verification attempt.")
            )

        # The face image is always required.
        if "face_image" not in params:
            msg = _("Missing required parameter face_image")
            return None, HttpResponseBadRequest(msg)

        # If provided, parse the course key and checkpoint location
        if "course_key" in params:
            try:
                params["course_key"] = CourseKey.from_string(params["course_key"])
            except InvalidKeyError:
                return None, HttpResponseBadRequest(_("Invalid course key"))

        return params, None

    def _update_full_name(self, user, full_name):
        """
        Update the user's full name.

        Arguments:
            user (User): The user to update.
            full_name (unicode): The user's updated full name.

        Returns:
            HttpResponse or None

        """
983
        try:
984
            update_account_settings(user, {"name": full_name})
985
        except UserNotFound:
986
            return HttpResponseBadRequest(_("No profile found for user"))
987
        except AccountValidationError:
988 989
            msg = _(
                "Name must be at least {min_length} characters long."
990
            ).format(min_length=NAME_MIN_LENGTH)
991 992
            return HttpResponseBadRequest(msg)

993 994 995
    def _decode_image_data(self, face_data, photo_id_data=None):
        """
        Decode image data sent with the request.
996

997 998
        Arguments:
            face_data (str): base64-encoded face image data.
999

1000 1001
        Keyword Arguments:
            photo_id_data (str): base64-encoded photo ID image data.
1002

1003 1004
        Returns:
            tuple of (str, str, HttpResponse)
Andy Armstrong committed
1005

1006 1007 1008 1009
        """
        try:
            # Decode face image data (used for both an initial and re-verification)
            face_image = decode_image_data(face_data)
1010

1011 1012 1013 1014 1015
            # Decode the photo ID image data if it's provided
            photo_id_image = (
                decode_image_data(photo_id_data)
                if photo_id_data is not None else None
            )
1016

1017
            return face_image, photo_id_image, None
1018

1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
        except InvalidImageData:
            msg = _("Image data is not valid.")
            return None, None, HttpResponseBadRequest(msg)

    def _submit_attempt(self, user, face_image, photo_id_image=None, initial_verification=None):
        """
        Submit a verification attempt.

        Arguments:
            user (User): The user making the attempt.
            face_image (str): Decoded face image data.

        Keyword Arguments:
            photo_id_image (str or None): Decoded photo ID image data.
            initial_verification (SoftwareSecurePhotoVerification): The initial verification attempt.
        """
        attempt = SoftwareSecurePhotoVerification(user=user)

        # We will always have face image data, so upload the face image
        attempt.upload_face_image(face_image)

        # If an ID photo wasn't submitted, re-use the ID photo from the initial attempt.
        # Earlier validation rules ensure that at least one of these is available.
        if photo_id_image is not None:
            attempt.upload_photo_id_image(photo_id_image)
        elif initial_verification is None:
            # Earlier validation should ensure that we never get here.
            log.error(
                "Neither a photo ID image or initial verification attempt provided. "
                "Parameter validation in the view should prevent this from happening!"
            )

        # Submit the attempt
        attempt.mark_ready()
        attempt.submit(copy_id_photo_from=initial_verification)

        return attempt

    def _send_confirmation_email(self, user):
        """
        Send an email confirming that the user submitted photos
        for initial verification.
        """
        context = {
            'full_name': user.profile.name,
1064
            'platform_name': configuration_helpers.get_value("PLATFORM_NAME", settings.PLATFORM_NAME)
1065 1066 1067 1068
        }

        subject = _("Verification photos received")
        message = render_to_string('emails/photo_submission_confirmation.txt', context)
1069
        from_address = configuration_helpers.get_value('email_from_address', settings.DEFAULT_FROM_EMAIL)
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
        to_address = user.email

        try:
            send_mail(subject, message, from_address, [to_address], fail_silently=False)
        except:  # pylint: disable=bare-except
            # We catch all exceptions and log them.
            # It would be much, much worse to roll back the transaction due to an uncaught
            # exception than to skip sending the notification email.
            log.exception("Could not send notification email for initial verification for user %s", user.id)

    def _fire_event(self, user, event_name, parameters):
        """
        Fire an analytics event.

        Arguments:
            user (User): The user who submitted photos.
            event_name (str): Name of the analytics event.
            parameters (dict): Event parameters.

        Returns: None

        """
1092
        if settings.LMS_SEGMENT_KEY:
1093 1094
            tracking_context = tracker.get_tracker().resolve_context()
            context = {
1095
                'ip': tracking_context.get('ip'),
1096 1097 1098 1099 1100
                'Google Analytics': {
                    'clientId': tracking_context.get('client_id')
                }
            }
            analytics.track(user.id, event_name, parameters, context=context)
1101 1102 1103


@require_POST
1104
@csrf_exempt  # SS does its own message signing, and their API won't have a cookie value
1105 1106 1107 1108 1109 1110
def results_callback(request):
    """
    Software Secure will call this callback to tell us whether a user is
    verified to be who they said they are.
    """
    body = request.body
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121

    try:
        body_dict = json.loads(body)
    except ValueError:
        log.exception("Invalid JSON received from Software Secure:\n\n{}\n".format(body))
        return HttpResponseBadRequest("Invalid JSON. Received:\n\n{}".format(body))

    if not isinstance(body_dict, dict):
        log.error("Reply from Software Secure is not a dict:\n\n{}\n".format(body))
        return HttpResponseBadRequest("JSON should be dict. Received:\n\n{}".format(body))

1122 1123 1124 1125 1126
    headers = {
        "Authorization": request.META.get("HTTP_AUTHORIZATION", ""),
        "Date": request.META.get("HTTP_DATE", "")
    }

1127
    has_valid_signature(
1128 1129
        "POST",
        headers,
1130
        body_dict,
1131 1132 1133 1134
        settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["API_ACCESS_KEY"],
        settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["API_SECRET_KEY"]
    )

1135
    _response, access_key_and_sig = headers["Authorization"].split(" ")
1136 1137 1138 1139 1140 1141 1142 1143 1144
    access_key = access_key_and_sig.split(":")[0]

    # This is what we should be doing...
    #if not sig_valid:
    #    return HttpResponseBadRequest("Signature is invalid")

    # This is what we're doing until we can figure out why we disagree on sigs
    if access_key != settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["API_ACCESS_KEY"]:
        return HttpResponseBadRequest("Access key invalid")
1145 1146 1147 1148 1149 1150

    receipt_id = body_dict.get("EdX-ID")
    result = body_dict.get("Result")
    reason = body_dict.get("Reason", "")
    error_code = body_dict.get("MessageType", "")

1151 1152 1153
    try:
        attempt = SoftwareSecurePhotoVerification.objects.get(receipt_id=receipt_id)
    except SoftwareSecurePhotoVerification.DoesNotExist:
1154
        log.error("Software Secure posted back for receipt_id %s, but not found", receipt_id)
1155 1156
        return HttpResponseBadRequest("edX ID {} not found".format(receipt_id))
    if result == "PASS":
1157
        log.debug("Approving verification for %s", receipt_id)
1158
        attempt.approve()
1159
        status = "approved"
1160

1161
    elif result == "FAIL":
1162
        log.debug("Denying verification for %s", receipt_id)
1163
        attempt.deny(json.dumps(reason), error_code=error_code)
1164
        status = "denied"
1165
    elif result == "SYSTEM FAIL":
1166
        log.debug("System failure for %s -- resetting to must_retry", receipt_id)
1167
        attempt.system_error(json.dumps(reason), error_code=error_code)
1168
        status = "error"
1169
        log.error("Software Secure callback attempt for %s failed: %s", receipt_id, reason)
1170
    else:
1171
        log.error("Software Secure returned unknown result %s", result)
1172 1173 1174
        return HttpResponseBadRequest(
            "Result {} not understood. Known results: PASS, FAIL, SYSTEM FAIL".format(result)
        )
1175

1176
    return HttpResponse("OK!")
1177

1178

1179 1180
class ReverifyView(View):
    """
1181 1182 1183 1184 1185 1186 1187 1188 1189
    Reverification occurs when a user's initial verification is denied
    or expires.  When this happens, users can re-submit photos through
    the re-verification flow.

    Unlike in-course reverification, this flow requires users to submit
    *both* face and ID photos.  In contrast, during in-course reverification,
    students submit only face photos, which are matched against the ID photo
    the user submitted during initial verification.

1190 1191 1192 1193
    """
    @method_decorator(login_required)
    def get(self, request):
        """
1194
        Render the reverification flow.
1195

1196 1197
        Most of the work is done client-side by composing the same
        Backbone views used in the initial verification flow.
1198
        """
1199
        status, __ = SoftwareSecurePhotoVerification.user_status(request.user)
1200

1201 1202 1203 1204 1205 1206 1207 1208 1209
        expiration_datetime = SoftwareSecurePhotoVerification.get_expiration_datetime(request.user)
        can_reverify = False
        if expiration_datetime:
            if SoftwareSecurePhotoVerification.is_verification_expiring_soon(expiration_datetime):
                # The user has an active verification, but the verification
                # is set to expire within "EXPIRING_SOON_WINDOW" days (default is 4 weeks).
                # In this case user can resubmit photos for reverification.
                can_reverify = True

1210 1211 1212 1213 1214
        # If the user has no initial verification or if the verification
        # process is still ongoing 'pending' or expired then allow the user to
        # submit the photo verification.
        # A photo verification is marked as 'pending' if its status is either
        # 'submitted' or 'must_retry'.
1215 1216

        if status in ["none", "must_reverify", "expired", "pending"] or can_reverify:
1217 1218
            context = {
                "user_full_name": request.user.profile.name,
1219
                "platform_name": configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME),
1220
                "capture_sound": staticfiles_storage.url("audio/camera_capture.wav"),
1221
            }
1222 1223 1224 1225 1226 1227
            return render_to_response("verify_student/reverify.html", context)
        else:
            context = {
                "status": status
            }
            return render_to_response("verify_student/reverify_not_allowed.html", context)