views.py 52.9 KB
Newer Older
1 2 3
"""
Student Views
"""
4
import datetime
5
import feedparser
6
import json
7
import logging
8
import random
9
import re
10
import string       # pylint: disable=W0402
11
import urllib
12
import uuid
13
import time
14

15
from django.conf import settings
Piotr Mitros committed
16
from django.contrib.auth import logout, authenticate, login
17
from django.contrib.auth.models import User
Calen Pennington committed
18
from django.contrib.auth.decorators import login_required
19
from django.contrib.auth.views import password_reset_confirm
Brian Wilson committed
20
from django.core.cache import cache
Piotr Mitros committed
21
from django.core.context_processors import csrf
22
from django.core.mail import send_mail
23
from django.core.urlresolvers import reverse
24
from django.core.validators import validate_email, validate_slug, ValidationError
25
from django.core.exceptions import ObjectDoesNotExist
26
from django.db import IntegrityError, transaction
27
from django.http import (HttpResponse, HttpResponseBadRequest, HttpResponseForbidden,
28
                         HttpResponseNotAllowed, Http404)
29
from django.shortcuts import redirect
30
from django_future.csrf import ensure_csrf_cookie
31
from django.utils.http import cookie_date
32
from django.utils.http import base36_to_int
David Baumgold committed
33
from django.utils.translation import ugettext as _
34
from django.views.decorators.http import require_POST
35

Diana Huang committed
36 37
from ratelimitbackend.exceptions import RateLimitException

38
from mitxmako.shortcuts import render_to_response, render_to_string
39
from bs4 import BeautifulSoup
Piotr Mitros committed
40

41
from student.models import (Registration, UserProfile, TestCenterUser, TestCenterUserForm,
42
                            TestCenterRegistration, TestCenterRegistrationForm,
43
                            PendingNameChange, PendingEmailChange,
44
                            CourseEnrollment, unique_id_for_user,
45
                            get_testcenter_registration, CourseEnrollmentAllowed)
Victor Shnayder committed
46

47 48
from student.forms import PasswordResetFormNoActive

Victor Shnayder committed
49 50
from certificates.models import CertificateStatuses, certificate_status_for_student

51
from xmodule.course_module import CourseDescriptor
52
from xmodule.modulestore.exceptions import ItemNotFoundError
53
from xmodule.modulestore.django import modulestore
Piotr Mitros committed
54

55
from collections import namedtuple
56

57
from courseware.courses import get_courses, sort_by_announcement
58
from courseware.access import has_access
59

60
from external_auth.models import ExternalAuthMap
61
import external_auth.views
62

63 64 65 66
from bulk_email.models import Optout

import track.views

67
from statsd import statsd
68
from pytz import UTC
69

70
log = logging.getLogger("mitx.student")
71 72
AUDIT_LOG = logging.getLogger("audit")

73
Article = namedtuple('Article', 'title url author image deck publication publish_date')
74

Calen Pennington committed
75

Piotr Mitros committed
76
def csrf_token(context):
77
    """A csrf token that can be included in a form."""
Piotr Mitros committed
78 79 80
    csrf_token = context.get('csrf_token', '')
    if csrf_token == 'NOTPROVIDED':
        return ''
81 82
    return (u'<div style="display:none"><input type="hidden"'
            ' name="csrfmiddlewaretoken" value="%s" /></div>' % (csrf_token))
Piotr Mitros committed
83

84

85 86 87 88
# NOTE: This view is not linked to directly--it is called from
# branding/views.py:index(), which is cached for anonymous users.
# This means that it should always return the same thing for anon
# users. (in particular, no switching based on query params allowed)
89
def index(request, extra_context={}, user=None):
90
    """
ichuang committed
91 92 93 94
    Render the edX main page.

    extra_context is used to allow immediate display of certain modal windows, eg signup,
    as used by external_auth.
95
    """
96

97
    # The course selection work is done in courseware.courses.
98
    domain = settings.MITX_FEATURES.get('FORCE_UNIVERSITY_DOMAIN')  # normally False
Victor Shnayder committed
99
    # do explicit check, because domain=None is valid
100
    if domain is False:
101
        domain = request.META.get('HTTP_HOST')
102

103
    courses = get_courses(None, domain=domain)
104
    courses = sort_by_announcement(courses)
105

106
    context = {'courses': courses}
Chris Dodge committed
107

ichuang committed
108 109
    context.update(extra_context)
    return render_to_response('index.html', context)
110

111

112 113 114
def course_from_id(course_id):
    """Return the CourseDescriptor corresponding to this course_id"""
    course_loc = CourseDescriptor.id_to_location(course_id)
115
    return modulestore().get_instance(course_id, course_loc)
Matthew Mongeau committed
116

117 118
day_pattern = re.compile(r'\s\d+,\s')
multimonth_pattern = re.compile(r'\s?\-\s?\S+\s')
119

Calen Pennington committed
120

121
def _get_date_for_press(publish_date):
122 123 124
    # strip off extra months, and just use the first:
    date = re.sub(multimonth_pattern, ", ", publish_date)
    if re.search(day_pattern, date):
125
        date = datetime.datetime.strptime(date, "%B %d, %Y").replace(tzinfo=UTC)
126
    else:
127
        date = datetime.datetime.strptime(date, "%B, %Y").replace(tzinfo=UTC)
128
    return date
129

Calen Pennington committed
130

131 132
def press(request):
    json_articles = cache.get("student_press_json_articles")
133
    if json_articles is None:
134 135 136 137 138 139 140 141
        if hasattr(settings, 'RSS_URL'):
            content = urllib.urlopen(settings.PRESS_URL).read()
            json_articles = json.loads(content)
        else:
            content = open(settings.PROJECT_ROOT / "templates" / "press.json").read()
            json_articles = json.loads(content)
        cache.set("student_press_json_articles", json_articles)
    articles = [Article(**article) for article in json_articles]
142
    articles.sort(key=lambda item: _get_date_for_press(item.publish_date), reverse=True)
143 144
    return render_to_response('static_templates/press.html', {'articles': articles})

145

146 147 148 149 150
def process_survey_link(survey_link, user):
    """
    If {UNIQUE_ID} appears in the link, replace it with a unique id for the user.
    Currently, this is sha1(user.username).  Otherwise, return survey_link.
    """
151
    return survey_link.format(UNIQUE_ID=unique_id_for_user(user))
152 153 154 155 156 157 158


def cert_info(user, course):
    """
    Get the certificate info needed to render the dashboard section for the given
    student and course.  Returns a dictionary with keys:

159
    'status': one of 'generating', 'ready', 'notpassing', 'processing', 'restricted'
160 161
    'show_download_url': bool
    'download_url': url, only present if show_download_url is True
162
    'show_disabled_download_button': bool -- true if state is 'generating'
163 164 165 166 167 168 169 170 171
    'show_survey_button': bool
    'survey_url': url, only if show_survey_button is True
    'grade': if status is not 'processing'
    """
    if not course.has_ended():
        return {}

    return _cert_info(user, course, certificate_status_for_student(user, course.id))

Calen Pennington committed
172

173 174 175 176 177
def _cert_info(user, course, cert_status):
    """
    Implements the logic for cert_info -- split out for testing.
    """
    default_status = 'processing'
178 179 180 181 182 183

    default_info = {'status': default_status,
                    'show_disabled_download_button': False,
                    'show_download_url': False,
                    'show_survey_button': False}

184
    if cert_status is None:
185
        return default_info
186 187 188 189 190 191 192

    # simplify the status for the template using this lookup table
    template_state = {
        CertificateStatuses.generating: 'generating',
        CertificateStatuses.regenerating: 'generating',
        CertificateStatuses.downloadable: 'ready',
        CertificateStatuses.notpassing: 'notpassing',
193
        CertificateStatuses.restricted: 'restricted',
194
    }
195 196 197 198

    status = template_state.get(cert_status['status'], default_status)

    d = {'status': status,
199
         'show_download_url': status == 'ready',
Calen Pennington committed
200
         'show_disabled_download_button': status == 'generating', }
201

202
    if (status in ('generating', 'ready', 'notpassing', 'restricted') and
203
            course.end_of_course_survey_url is not None):
204
        d.update({
205 206
            'show_survey_button': True,
            'survey_url': process_survey_link(course.end_of_course_survey_url, user)})
207 208 209
    else:
        d['show_survey_button'] = False

210
    if status == 'ready':
211 212 213
        if 'download_url' not in cert_status:
            log.warning("User %s has a downloadable cert for %s, but no download url",
                        user.username, course.id)
214
            return default_info
215 216
        else:
            d['download_url'] = cert_status['download_url']
217

218
    if status in ('generating', 'ready', 'notpassing', 'restricted'):
219 220 221 222
        if 'grade' not in cert_status:
            # Note: as of 11/20/2012, we know there are students in this state-- cs169.1x,
            # who need to be regraded (we weren't tracking 'notpassing' at first).
            # We can add a log.warning here once we think it shouldn't happen.
223
            return default_info
224 225
        else:
            d['grade'] = cert_status['grade']
226 227 228

    return d

Calen Pennington committed
229

230
@ensure_csrf_cookie
231
def signin_user(request):
John Jarvis committed
232 233 234
    """
    This view will display the non-modal login form
    """
235 236 237
    if request.user.is_authenticated():
        return redirect(reverse('dashboard'))

238 239 240 241
    context = {
        'course_id': request.GET.get('course_id'),
        'enrollment_action': request.GET.get('enrollment_action')
    }
John Jarvis committed
242
    return render_to_response('login.html', context)
John Jarvis committed
243

244

245
@ensure_csrf_cookie
246
def register_user(request, extra_context=None):
John Jarvis committed
247 248 249
    """
    This view will display the non-modal registration form
    """
250 251 252
    if request.user.is_authenticated():
        return redirect(reverse('dashboard'))

253 254 255 256
    context = {
        'course_id': request.GET.get('course_id'),
        'enrollment_action': request.GET.get('enrollment_action')
    }
257 258
    if extra_context is not None:
        context.update(extra_context)
259

260
    if context.get("extauth_domain", '').startswith(external_auth.views.SHIBBOLETH_DOMAIN_PREFIX):
261
        return render_to_response('register-shib.html', context)
John Jarvis committed
262 263 264
    return render_to_response('register.html', context)


265
@login_required
Matthew Mongeau committed
266 267
@ensure_csrf_cookie
def dashboard(request):
268 269
    user = request.user

270 271 272 273
    # Build our courses list for the user, but ignore any courses that no longer
    # exist (because the course IDs have changed). Still, we don't delete those
    # enrollments, because it could have been a data push snafu.
    courses = []
274
    for enrollment in CourseEnrollment.enrollments_for_user(user):
275 276 277
        try:
            courses.append(course_from_id(enrollment.course_id))
        except ItemNotFoundError:
278
            log.error("User {0} enrolled in non-existent course {1}"
279
                      .format(user.username, enrollment.course_id))
280

281
    course_optouts = Optout.objects.filter(user=user).values_list('course_id', flat=True)
282

283 284 285
    message = ""
    if not user.is_active:
        message = render_to_string('registration/activate_account_notice.html', {'email': user.email})
286

287 288
    # Global staff can see what courses errored on their dashboard
    staff_access = False
Victor Shnayder committed
289
    errored_courses = {}
290 291 292 293 294
    if has_access(user, 'global', 'staff'):
        # Show any courses that errored on load
        staff_access = True
        errored_courses = modulestore().get_errored_courses()

295 296 297
    show_courseware_links_for = frozenset(course.id for course in courses
                                          if has_access(request.user, course, 'load'))

Calen Pennington committed
298
    cert_statuses = {course.id: cert_info(request.user, course) for course in courses}
Victor Shnayder committed
299

Calen Pennington committed
300
    exam_registrations = {course.id: exam_registration_info(request.user, course) for course in courses}
301

302 303
    # get info w.r.t ExternalAuthMap
    external_auth_map = None
304 305 306 307
    try:
        external_auth_map = ExternalAuthMap.objects.get(user=user)
    except ExternalAuthMap.DoesNotExist:
        pass
Victor Shnayder committed
308

309
    context = {'courses': courses,
310
               'course_optouts': course_optouts,
311
               'message': message,
312
               'external_auth_map': external_auth_map,
313
               'staff_access': staff_access,
314
               'errored_courses': errored_courses,
Calen Pennington committed
315
               'show_courseware_links_for': show_courseware_links_for,
Victor Shnayder committed
316
               'cert_statuses': cert_statuses,
317
               'exam_registrations': exam_registrations,
Victor Shnayder committed
318
               }
319

320
    return render_to_response('dashboard.html', context)
321 322


323 324
def try_change_enrollment(request):
    """
325
    This method calls change_enrollment if the necessary POST
326 327 328 329 330 331 332
    parameters are present, but does not return anything. It
    simply logs the result or exception. This is usually
    called after a registration or login, as secondary action.
    It should not interrupt a successful registration or login.
    """
    if 'enrollment_action' in request.POST:
        try:
333
            enrollment_response = change_enrollment(request)
334 335
            # There isn't really a way to display the results to the user, so we just log it
            # We expect the enrollment to be a success, and will show up on the dashboard anyway
336 337 338 339 340 341
            log.info(
                "Attempted to automatically enroll after login. Response code: {0}; response body: {1}".format(
                    enrollment_response.status_code,
                    enrollment_response.content
                )
            )
342
        except Exception, e:
343
            log.exception("Exception automatically enrolling after login: {0}".format(str(e)))
344

345

346
def change_enrollment(request):
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
    """
    Modify the enrollment status for the logged-in user.

    The request parameter must be a POST request (other methods return 405)
    that specifies course_id and enrollment_action parameters. If course_id or
    enrollment_action is not specified, if course_id is not valid, if
    enrollment_action is something other than "enroll" or "unenroll", if
    enrollment_action is "enroll" and enrollment is closed for the course, or
    if enrollment_action is "unenroll" and the user is not enrolled in the
    course, a 400 error will be returned. If the user is not logged in, 403
    will be returned; it is important that only this case return 403 so the
    front end can redirect the user to a registration or login page when this
    happens. This function should only be called from an AJAX request or
    as a post-login/registration helper, so the error messages in the responses
    should never actually be user-visible.
    """
363
    if request.method != "POST":
364
        return HttpResponseNotAllowed(["POST"])
365

366
    user = request.user
367
    if not user.is_authenticated():
368
        return HttpResponseForbidden()
369

370 371
    action = request.POST.get("enrollment_action")
    course_id = request.POST.get("course_id")
372
    if course_id is None:
David Baumgold committed
373
        return HttpResponseBadRequest(_("Course id not specified"))
374

375 376 377 378 379 380
    if action == "enroll":
        # Make sure the course exists
        # We don't do this check on unenroll, or a bad course id can't be unenrolled from
        try:
            course = course_from_id(course_id)
        except ItemNotFoundError:
381
            log.warning("User {0} tried to enroll in non-existent course {1}"
382
                        .format(user.username, course_id))
David Baumgold committed
383
            return HttpResponseBadRequest(_("Course id is invalid"))
384

385
        if not has_access(user, course, 'enroll'):
David Baumgold committed
386
            return HttpResponseBadRequest(_("Enrollment is closed"))
Victor Shnayder committed
387

Calen Pennington committed
388
        org, course_num, run = course_id.split("/")
389
        statsd.increment("common.student.enrollment",
390 391 392
                         tags=["org:{0}".format(org),
                               "course:{0}".format(course_num),
                               "run:{0}".format(run)])
Victor Shnayder committed
393

394 395
        CourseEnrollment.enroll(user, course.id)

396
        return HttpResponse()
397

398 399
    elif action == "unenroll":
        try:
400
            CourseEnrollment.unenroll(user, course_id)
Victor Shnayder committed
401

Calen Pennington committed
402
            org, course_num, run = course_id.split("/")
403
            statsd.increment("common.student.unenrollment",
404 405 406
                             tags=["org:{0}".format(org),
                                   "course:{0}".format(course_num),
                                   "run:{0}".format(run)])
Victor Shnayder committed
407

408
            return HttpResponse()
409
        except CourseEnrollment.DoesNotExist:
David Baumgold committed
410
            return HttpResponseBadRequest(_("You are not enrolled in this course"))
411
    else:
David Baumgold committed
412
        return HttpResponseBadRequest(_("Enrollment action is invalid"))
413

414

415 416 417 418 419 420
def _parse_course_id_from_string(input_str):
    """
    Helper function to determine if input_str (typically the queryparam 'next') contains a course_id.
    @param input_str:
    @return: the course_id if found, None if not
    """
421 422 423 424 425 426
    m_obj = re.match(r'^/courses/(?P<course_id>[^/]+/[^/]+/[^/]+)', input_str)
    if m_obj:
        return m_obj.group('course_id')
    return None


427 428 429 430 431 432
def _get_course_enrollment_domain(course_id):
    """
    Helper function to get the enrollment domain set for a course with id course_id
    @param course_id:
    @return:
    """
433 434 435 436 437 438 439
    try:
        course = course_from_id(course_id)
        return course.enrollment_domain
    except ItemNotFoundError:
        return None


440
@ensure_csrf_cookie
441
def accounts_login(request):
442 443 444 445
    """
    This view is mainly used as the redirect from the @login_required decorator.  I don't believe that
    the login path linked from the homepage uses it.
    """
446 447
    if settings.MITX_FEATURES.get('AUTH_USE_CAS'):
        return redirect(reverse('cas-login'))
448 449
    # see if the "next" parameter has been set, whether it has a course context, and if so, whether
    # there is a course-specific place to redirect
450 451 452 453
    redirect_to = request.GET.get('next')
    if redirect_to:
        course_id = _parse_course_id_from_string(redirect_to)
        if course_id and _get_course_enrollment_domain(course_id):
454 455 456
            return external_auth.views.course_specific_login(request, course_id)
    return render_to_response('login.html')

457

458
# Need different levels of logging
459
@ensure_csrf_cookie
Piotr Mitros committed
460
def login_user(request, error=""):
461
    """AJAX request to log in the user."""
Piotr Mitros committed
462
    if 'email' not in request.POST or 'password' not in request.POST:
463
        return HttpResponse(json.dumps({'success': False,
David Baumgold committed
464
                                        'value': _('There was an error receiving your login information. Please email us.')}))  # TODO: User error message
465

Piotr Mitros committed
466 467
    email = request.POST['email']
    password = request.POST['password']
Piotr Mitros committed
468
    try:
469
        user = User.objects.get(email=email)
Piotr Mitros committed
470
    except User.DoesNotExist:
471
        AUDIT_LOG.warning(u"Login failed - Unknown user email: {0}".format(email))
Diana Huang committed
472
        user = None
Piotr Mitros committed
473

474 475 476 477 478 479
    # check if the user has a linked shibboleth account, if so, redirect the user to shib-login
    # This behavior is pretty much like what gmail does for shibboleth.  Try entering some @stanford.edu
    # address into the Gmail login.
    if settings.MITX_FEATURES.get('AUTH_USE_SHIB') and user:
        try:
            eamap = ExternalAuthMap.objects.get(user=user)
480
            if eamap.external_domain.startswith(external_auth.views.SHIBBOLETH_DOMAIN_PREFIX):
481
                return HttpResponse(json.dumps({'success': False, 'redirect': reverse('shib-login')}))
482 483
        except ExternalAuthMap.DoesNotExist:
            # This is actually the common case, logging in user without external linked login
484
            AUDIT_LOG.info("User %s w/o external auth attempting login", user)
485

Diana Huang committed
486 487 488 489 490 491 492 493 494 495
    # if the user doesn't exist, we want to set the username to an invalid
    # username so that authentication is guaranteed to fail and we can take
    # advantage of the ratelimited backend
    username = user.username if user else ""
    try:
        user = authenticate(username=username, password=password, request=request)
    # this occurs when there are too many attempts from the same IP address
    except RateLimitException:
        return HttpResponse(json.dumps({'success': False,
                                        'value': _('Too many failed login attempts. Try again later.')}))
Piotr Mitros committed
496
    if user is None:
Diana Huang committed
497 498 499 500
        # if we didn't find this username earlier, the account for this email
        # doesn't exist, and doesn't have a corresponding password
        if username != "":
            AUDIT_LOG.warning(u"Login failed - password for {0} is invalid".format(email))
501
        return HttpResponse(json.dumps({'success': False,
David Baumgold committed
502
                                        'value': _('Email or password is incorrect.')}))
503

Piotr Mitros committed
504
    if user is not None and user.is_active:
505
        try:
506 507
            # We do not log here, because we have a handler registered
            # to perform logging on successful logins.
508
            login(request, user)
509
            if request.POST.get('remember') == 'true':
510
                request.session.set_expiry(604800)
511 512 513 514
                log.debug("Setting user session to never expire")
            else:
                request.session.set_expiry(0)
        except Exception as e:
515
            AUDIT_LOG.critical("Login failed - Could not create session. Is memcached running?")
516 517
            log.critical("Login failed - Could not create session. Is memcached running?")
            log.exception(e)
518
            raise
519

520
        try_change_enrollment(request)
Victor Shnayder committed
521

522
        statsd.increment("common.student.successful_login")
523 524 525
        response = HttpResponse(json.dumps({'success': True}))

        # set the login cookie for the edx marketing site
526 527 528
        # we want this cookie to be accessed via javascript
        # so httponly is set to None

529 530 531 532 533 534 535
        if request.session.get_expire_at_browser_close():
            max_age = None
            expires = None
        else:
            max_age = request.session.get_expiry_age()
            expires_time = time.time() + max_age
            expires = cookie_date(expires_time)
Victor Shnayder committed
536

537
        response.set_cookie(settings.EDXMKTG_COOKIE_NAME,
538
                            'true', max_age=max_age,
539
                            expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
540 541 542
                            path='/',
                            secure=None,
                            httponly=None)
Victor Shnayder committed
543

544
        return response
Victor Shnayder committed
545

546
    AUDIT_LOG.warning(u"Login failed - Account not active for user {0}, resending activation".format(username))
Victor Shnayder committed
547

548
    reactivation_email_for_user(user)
David Baumgold committed
549
    not_activated_msg = _("This account has not been activated. We have sent another activation message. Please check your e-mail for the activation instructions.")
550
    return HttpResponse(json.dumps({'success': False,
551
                                    'value': not_activated_msg}))
Piotr Mitros committed
552

553

554
@ensure_csrf_cookie
Piotr Mitros committed
555
def logout_user(request):
556
    """
557 558 559
    HTTP request to log out the user. Redirects to marketing page.
    Deletes both the CSRF and sessionid cookies so the marketing
    site can determine the logged in state of the user
560
    """
561 562
    # We do not log here, because we have a handler registered
    # to perform logging on successful logouts.
Piotr Mitros committed
563
    logout(request)
564 565 566 567 568
    if settings.MITX_FEATURES.get('AUTH_USE_CAS'):
        target = reverse('cas-logout')
    else:
        target = '/'
    response = redirect(target)
569
    response.delete_cookie(settings.EDXMKTG_COOKIE_NAME,
570 571
                           path='/',
                           domain=settings.SESSION_COOKIE_DOMAIN)
572
    return response
Piotr Mitros committed
573

574

575
@login_required
576
@ensure_csrf_cookie
577
def change_setting(request):
578
    """JSON call to change a profile setting: Right now, location"""
579
    # TODO (vshnayder): location is no longer used
580
    up = UserProfile.objects.get(user=request.user)  # request.user.profile_cache
Piotr Mitros committed
581
    if 'location' in request.POST:
582
        up.location = request.POST['location']
583 584
    up.save()

585 586 587
    return HttpResponse(json.dumps({'success': True,
                                    'location': up.location, }))

Calen Pennington committed
588

589 590 591 592 593 594 595 596 597
def _do_create_account(post_vars):
    """
    Given cleaned post variables, create the User and UserProfile objects, as well as the
    registration for this user.

    Returns a tuple (User, UserProfile, Registration).

    Note: this function is also used for creating test users.
    """
598
    user = User(username=post_vars['username'],
599 600
                email=post_vars['email'],
                is_active=False)
601 602
    user.set_password(post_vars['password'])
    registration = Registration()
603 604 605
    # TODO: Rearrange so that if part of the process fails, the whole process fails.
    # Right now, we can have e.g. no registration e-mail sent out and a zombie account
    try:
606
        user.save()
607
    except IntegrityError:
608
        js = {'success': False}
609 610
        # Figure out the cause of the integrity error
        if len(User.objects.filter(username=post_vars['username'])) > 0:
David Baumgold committed
611
            js['value'] = _("An account with the Public Username '{username}' already exists.").format(username=post_vars['username'])
612 613 614 615
            js['field'] = 'username'
            return HttpResponse(json.dumps(js))

        if len(User.objects.filter(email=post_vars['email'])) > 0:
David Baumgold committed
616
            js['value'] = _("An account with the Email '{email}' already exists.").format(email=post_vars['email'])
617 618 619 620 621
            js['field'] = 'email'
            return HttpResponse(json.dumps(js))

        raise

622
    registration.register(user)
623

624 625 626 627 628 629
    profile = UserProfile(user=user)
    profile.name = post_vars['name']
    profile.level_of_education = post_vars.get('level_of_education')
    profile.gender = post_vars.get('gender')
    profile.mailing_address = post_vars.get('mailing_address')
    profile.goals = post_vars.get('goals')
630 631

    try:
632
        profile.year_of_birth = int(post_vars['year_of_birth'])
633
    except (ValueError, KeyError):
634 635
        # If they give us garbage, just ignore it instead
        # of asking them to put an integer.
636
        profile.year_of_birth = None
637
    try:
638
        profile.save()
639
    except Exception:
David Baumgold committed
640
        log.exception("UserProfile creation failed for user {id}.".format(id=user.id))
641
    return (user, profile, registration)
642

643

644
@ensure_csrf_cookie
645
def create_account(request, post_override=None):
646
    """
ichuang committed
647 648
    JSON call to create new edX account.
    Used by form in signup_modal.html, which is included into navigation.html
649
    """
650
    js = {'success': False}
Matthew Mongeau committed
651

652
    post_vars = post_override if post_override else request.POST
Matthew Mongeau committed
653

ichuang committed
654 655
    # if doing signup for an external authorization, then get email, password, name from the eamap
    # don't use the ones from the form, since the user could have hacked those
656
    # unless originally we didn't get a valid email or name from the external auth
657 658
    DoExternalAuth = 'ExternalAuthMap' in request.session
    if DoExternalAuth:
ichuang committed
659
        eamap = request.session['ExternalAuthMap']
660 661 662 663 664 665 666 667
        try:
            validate_email(eamap.external_email)
            email = eamap.external_email
        except ValidationError:
            email = post_vars.get('email', '')
        if eamap.external_name.strip() == '':
            name = post_vars.get('name', '')
        else:
David Baumgold committed
668
            name = eamap.external_name
ichuang committed
669 670
        password = eamap.internal_password
        post_vars = dict(post_vars.items())
671
        post_vars.update(dict(email=email, name=name, password=password))
672
        log.debug(u'In create_account with external_auth: user = %s, email=%s', name, email)
ichuang committed
673

Piotr Mitros committed
674
    # Confirm we have a properly formed request
Matthew Mongeau committed
675
    for a in ['username', 'email', 'password', 'name']:
676
        if a not in post_vars:
David Baumgold committed
677
            js['value'] = _("Error (401 {field}). E-mail us.").format(field=a)
678
            js['field'] = a
Piotr Mitros committed
679 680
            return HttpResponse(json.dumps(js))

681
    if post_vars.get('honor_code', 'false') != u'true':
David Baumgold committed
682
        js['value'] = _("To enroll, you must follow the honor code.").format(field=a)
683
        js['field'] = 'honor_code'
Piotr Mitros committed
684 685
        return HttpResponse(json.dumps(js))

686
    # Can't have terms of service for certain SHIB users, like at Stanford
687 688
    tos_not_required = (settings.MITX_FEATURES.get("AUTH_USE_SHIB") and
                        settings.MITX_FEATURES.get('SHIB_DISABLE_TOS') and
689 690
                        DoExternalAuth and
                        eamap.external_domain.startswith(external_auth.views.SHIBBOLETH_DOMAIN_PREFIX))
691 692

    if not tos_not_required:
693
        if post_vars.get('terms_of_service', 'false') != u'true':
David Baumgold committed
694
            js['value'] = _("You must accept the terms of service.").format(field=a)
695 696
            js['field'] = 'terms_of_service'
            return HttpResponse(json.dumps(js))
Piotr Mitros committed
697

Matthew Mongeau committed
698 699 700
    # Confirm appropriate fields are there.
    # TODO: Check e-mail format is correct.
    # TODO: Confirm e-mail is not from a generic domain (mailinator, etc.)? Not sure if
Piotr Mitros committed
701 702
    # this is a good idea
    # TODO: Check password is sane
703 704

    required_post_vars = ['username', 'email', 'name', 'password', 'terms_of_service', 'honor_code']
705
    if tos_not_required:
706
        required_post_vars = ['username', 'email', 'name', 'password', 'honor_code']
707 708

    for a in required_post_vars:
709
        if len(post_vars[a]) < 2:
710 711 712
            error_str = {'username': 'Username must be minimum of two characters long.',
                         'email': 'A properly formatted e-mail is required.',
                         'name': 'Your legal name must be a minimum of two characters long.',
713 714 715
                         'password': 'A valid password is required.',
                         'terms_of_service': 'Accepting Terms of Service is required.',
                         'honor_code': 'Agreeing to the Honor Code is required.'}
716
            js['value'] = error_str[a]
717
            js['field'] = a
Piotr Mitros committed
718 719 720
            return HttpResponse(json.dumps(js))

    try:
721
        validate_email(post_vars['email'])
722
    except ValidationError:
David Baumgold committed
723
        js['value'] = _("Valid e-mail is required.").format(field=a)
724
        js['field'] = 'email'
Piotr Mitros committed
725 726 727
        return HttpResponse(json.dumps(js))

    try:
728
        validate_slug(post_vars['username'])
729
    except ValidationError:
David Baumgold committed
730
        js['value'] = _("Username should only consist of A-Z and 0-9, with no spaces.").format(field=a)
731
        js['field'] = 'username'
Piotr Mitros committed
732
        return HttpResponse(json.dumps(js))
Matthew Mongeau committed
733

734
    # Ok, looks like everything is legit.  Create the account.
735
    ret = _do_create_account(post_vars)
736
    if isinstance(ret, HttpResponse):  # if there was an error then return that
737 738
        return ret
    (user, profile, registration) = ret
739

740
    d = {'name': post_vars['name'],
741
         'key': registration.activation_key,
742
         }
Piotr Mitros committed
743

ichuang committed
744
    # composes activation email
745
    subject = render_to_string('emails/activation_email_subject.txt', d)
ichuang committed
746
    # Email subject *must not* contain newlines
Piotr Mitros committed
747
    subject = ''.join(subject.splitlines())
748
    message = render_to_string('emails/activation_email.txt', d)
Piotr Mitros committed
749

750
    # dont send email if we are doing load testing or random user generation for some reason
751
    if not (settings.MITX_FEATURES.get('AUTOMATIC_AUTH_FOR_TESTING')):
752 753 754 755 756 757 758
        try:
            if settings.MITX_FEATURES.get('REROUTE_ACTIVATION_EMAIL'):
                dest_addr = settings.MITX_FEATURES['REROUTE_ACTIVATION_EMAIL']
                message = ("Activation for %s (%s): %s\n" % (user, user.email, profile.name) +
                           '-' * 80 + '\n\n' + message)
                send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [dest_addr], fail_silently=False)
            else:
759
                _res = user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
760 761 762 763
        except:
            log.warning('Unable to send activation email to user', exc_info=True)
            js['value'] = _('Could not send activation e-mail.')
            return HttpResponse(json.dumps(js))
764

765 766 767
    # Immediately after a user creates an account, we log them in. They are only
    # logged in until they close the browser. They can't log in again until they click
    # the activation link from the email.
768
    login_user = authenticate(username=post_vars['username'], password=post_vars['password'])
769
    login(request, login_user)
770 771
    request.session.set_expiry(0)

772 773 774 775 776
    # TODO: there is no error checking here to see that the user actually logged in successfully,
    # and is not yet an active user.
    if login_user is not None:
        AUDIT_LOG.info(u"Login success on new account creation - {0}".format(login_user.username))

777
    if DoExternalAuth:
ichuang committed
778
        eamap.user = login_user
779
        eamap.dtsignup = datetime.datetime.now(UTC)
ichuang committed
780
        eamap.save()
781 782
        AUDIT_LOG.info("User registered with external_auth %s", post_vars['username'])
        AUDIT_LOG.info('Updated ExternalAuthMap for %s to be %s', post_vars['username'], eamap)
ichuang committed
783 784

        if settings.MITX_FEATURES.get('BYPASS_ACTIVATION_EMAIL_FOR_EXTAUTH'):
785
            log.info('bypassing activation email')
ichuang committed
786 787
            login_user.is_active = True
            login_user.save()
788
            AUDIT_LOG.info(u"Login activated on extauth account - {0} ({1})".format(login_user.username, login_user.email))
Victor Shnayder committed
789

790 791
    try_change_enrollment(request)

792
    statsd.increment("common.student.account_created")
Victor Shnayder committed
793

794
    js = {'success': True}
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
    HttpResponse(json.dumps(js), mimetype="application/json")

    response = HttpResponse(json.dumps({'success': True}))

    # set the login cookie for the edx marketing site
    # we want this cookie to be accessed via javascript
    # so httponly is set to None

    if request.session.get_expire_at_browser_close():
        max_age = None
        expires = None
    else:
        max_age = request.session.get_expiry_age()
        expires_time = time.time() + max_age
        expires = cookie_date(expires_time)

    response.set_cookie(settings.EDXMKTG_COOKIE_NAME,
                        'true', max_age=max_age,
                        expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
                        path='/',
                        secure=None,
                        httponly=None)
    return response

Matthew Mongeau committed
819

820 821 822 823 824 825 826 827
def exam_registration_info(user, course):
    """ Returns a Registration object if the user is currently registered for a current
    exam of the course.  Returns None if the user is not registered, or if there is no
    current exam for the course.
    """
    exam_info = course.current_test_center_exam
    if exam_info is None:
        return None
828

829 830
    exam_code = exam_info.exam_series_code
    registrations = get_testcenter_registration(user, course.id, exam_code)
831
    if registrations:
832 833 834 835
        registration = registrations[0]
    else:
        registration = None
    return registration
836

Calen Pennington committed
837

838 839
@login_required
@ensure_csrf_cookie
840
def begin_exam_registration(request, course_id):
841 842 843 844
    """ Handles request to register the user for the current
    test center exam of the specified course.  Called by form
    in dashboard.html.
    """
845 846 847
    user = request.user

    try:
848
        course = course_from_id(course_id)
849
    except ItemNotFoundError:
850 851
        log.error("User {0} enrolled in non-existent course {1}".format(user.username, course_id))
        raise Http404
852 853 854

    # get the exam to be registered for:
    # (For now, we just assume there is one at most.)
855 856
    # if there is no exam now (because someone bookmarked this stupid page),
    # then return a 404:
857
    exam_info = course.current_test_center_exam
858 859
    if exam_info is None:
        raise Http404
860

861 862
    # determine if the user is registered for this course:
    registration = exam_registration_info(user, course)
863

864 865 866 867 868 869 870
    # we want to populate the registration page with the relevant information,
    # if it already exists.  Create an empty object otherwise.
    try:
        testcenteruser = TestCenterUser.objects.get(user=user)
    except TestCenterUser.DoesNotExist:
        testcenteruser = TestCenterUser()
        testcenteruser.user = user
871

872 873 874
    context = {'course': course,
               'user': user,
               'testcenteruser': testcenteruser,
875 876
               'registration': registration,
               'exam_info': exam_info,
877 878 879 880
               }

    return render_to_response('test_center_register.html', context)

Calen Pennington committed
881

882
@ensure_csrf_cookie
883
def create_exam_registration(request, post_override=None):
884
    """
885 886
    JSON call to create a test center exam registration.
    Called by form in test_center_register.html
887
    """
888
    post_vars = post_override if post_override else request.POST
889 890

    # first determine if we need to create a new TestCenterUser, or if we are making any update
891
    # to an existing TestCenterUser.
892
    username = post_vars['username']
893
    user = User.objects.get(username=username)
894
    course_id = post_vars['course_id']
895 896 897 898 899 900 901 902
    course = course_from_id(course_id)  # assume it will be found....

    # make sure that any demographic data values received from the page have been stripped.
    # Whitespace is not an acceptable response for any of these values
    demographic_data = {}
    for fieldname in TestCenterUser.user_provided_fields():
        if fieldname in post_vars:
            demographic_data[fieldname] = (post_vars[fieldname]).strip()
903 904
    try:
        testcenter_user = TestCenterUser.objects.get(user=user)
905
        needs_updating = testcenter_user.needs_update(demographic_data)
906
        log.info("User {0} enrolled in course {1} {2}updating demographic info for exam registration".format(user.username, course_id, "" if needs_updating else "not "))
907
    except TestCenterUser.DoesNotExist:
908 909
        # do additional initialization here:
        testcenter_user = TestCenterUser.create(user)
910
        needs_updating = True
911
        log.info("User {0} enrolled in course {1} creating demographic info for exam registration".format(user.username, course_id))
912 913 914

    # perform validation:
    if needs_updating:
915
        # first perform validation on the user information
916
        # using a Django Form.
917
        form = TestCenterUserForm(instance=testcenter_user, data=demographic_data)
918
        if form.is_valid():
919
            form.update_and_save()
920 921 922 923 924 925
        else:
            response_data = {'success': False}
            # return a list of errors...
            response_data['field_errors'] = form.errors
            response_data['non_field_errors'] = form.non_field_errors()
            return HttpResponse(json.dumps(response_data), mimetype="application/json")
926

927
    # create and save the registration:
928
    needs_saving = False
929 930 931
    exam = course.current_test_center_exam
    exam_code = exam.exam_series_code
    registrations = get_testcenter_registration(user, course_id, exam_code)
932
    if registrations:
933
        registration = registrations[0]
934 935
        # NOTE: we do not bother to check here to see if the registration has changed,
        # because at the moment there is no way for a user to change anything about their
936
        # registration.  They only provide an optional accommodation request once, and
937 938 939
        # cannot make changes to it thereafter.
        # It is possible that the exam_info content has been changed, such as the
        # scheduled exam dates, but those kinds of changes should not be handled through
940 941
        # this registration screen.

942
    else:
Calen Pennington committed
943
        accommodation_request = post_vars.get('accommodation_request', '')
944
        registration = TestCenterRegistration.create(testcenter_user, exam, accommodation_request)
945
        needs_saving = True
946
        log.info("User {0} enrolled in course {1} creating new exam registration".format(user.username, course_id))
947

948
    if needs_saving:
949
        # do validation of registration.  (Mainly whether an accommodation request is too long.)
950 951 952 953 954 955 956 957 958
        form = TestCenterRegistrationForm(instance=registration, data=post_vars)
        if form.is_valid():
            form.update_and_save()
        else:
            response_data = {'success': False}
            # return a list of errors...
            response_data['field_errors'] = form.errors
            response_data['non_field_errors'] = form.non_field_errors()
            return HttpResponse(json.dumps(response_data), mimetype="application/json")
959

960
    # only do the following if there is accommodation text to send,
961 962
    # and a destination to which to send it.
    # TODO: still need to create the accommodation email templates
963 964
#    if 'accommodation_request' in post_vars and 'TESTCENTER_ACCOMMODATION_REQUEST_EMAIL' in settings:
#        d = {'accommodation_request': post_vars['accommodation_request'] }
965
#
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
#        # composes accommodation email
#        subject = render_to_string('emails/accommodation_email_subject.txt', d)
#        # Email subject *must not* contain newlines
#        subject = ''.join(subject.splitlines())
#        message = render_to_string('emails/accommodation_email.txt', d)
#
#        try:
#            dest_addr = settings['TESTCENTER_ACCOMMODATION_REQUEST_EMAIL']
#            from_addr = user.email
#            send_mail(subject, message, from_addr, [dest_addr], fail_silently=False)
#        except:
#            log.exception(sys.exc_info())
#            response_data = {'success': False}
#            response_data['non_field_errors'] =  [ 'Could not send accommodation e-mail.', ]
#            return HttpResponse(json.dumps(response_data), mimetype="application/json")
981

982 983
    js = {'success': True}
    return HttpResponse(json.dumps(js), mimetype="application/json")
984

985

986
def auto_auth(request):
987
    """
988 989
    Automatically logs the user in with a generated random credentials
    This view is only accessible when
990
    settings.MITX_SETTINGS['AUTOMATIC_AUTH_FOR_TESTING'] is true.
991
    """
Matthew Mongeau committed
992

993
    def get_dummy_post_data(username, password, email, name):
994 995
        """
        Return a dictionary suitable for passing to post_vars of _do_create_account or post_override
996
        of create_account, with specified values.
997 998
        """
        return {'username': username,
999
                'email': email,
1000
                'password': password,
1001
                'name': name,
1002 1003
                'honor_code': u'true',
                'terms_of_service': u'true', }
1004

1005
    # generate random user credentials from a small name space (determined by settings)
1006 1007
    name_base = 'USER_'
    pass_base = 'PASS_'
Matthew Mongeau committed
1008

1009
    max_users = settings.MITX_FEATURES.get('MAX_AUTO_AUTH_USERS', 200)
1010
    number = random.randint(1, max_users)
Matthew Mongeau committed
1011

1012 1013 1014 1015 1016 1017 1018 1019
    # Get the params from the request to override default user attributes if specified
    qdict = request.GET

    # Use the params from the request, otherwise use these defaults
    username = qdict.get('username', name_base + str(number))
    password = qdict.get('password', pass_base + str(number))
    email = qdict.get('email', '%s_dummy_test@mitx.mit.edu' % username)
    name = qdict.get('name', '%s Test' % username)
1020

1021 1022 1023
    # if they already are a user, log in
    try:
        user = User.objects.get(username=username)
Diana Huang committed
1024
        user = authenticate(username=username, password=password, request=request)
1025 1026 1027 1028
        login(request, user)

    # else create and activate account info
    except ObjectDoesNotExist:
1029
        post_override = get_dummy_post_data(username, password, email, name)
1030 1031 1032 1033 1034 1035
        create_account(request, post_override=post_override)
        request.user.is_active = True
        request.user.save()

    # return empty success
    return HttpResponse('')
1036

1037

1038
@ensure_csrf_cookie
Piotr Mitros committed
1039
def activate_account(request, key):
1040
    """When link in activation e-mail is clicked"""
1041 1042
    r = Registration.objects.filter(activation_key=key)
    if len(r) == 1:
1043 1044
        user_logged_in = request.user.is_authenticated()
        already_active = True
1045 1046
        if not r[0].user.is_active:
            r[0].activate()
1047
            already_active = False
1048

1049
        # Enroll student in any pending courses he/she may have if auto_enroll flag is set
1050 1051 1052 1053 1054
        student = User.objects.filter(id=r[0].user_id)
        if student:
            ceas = CourseEnrollmentAllowed.objects.filter(email=student[0].email)
            for cea in ceas:
                if cea.auto_enroll:
1055 1056 1057 1058 1059 1060 1061 1062 1063
                    CourseEnrollment.enroll(student[0], cea.course_id)

        resp = render_to_response(
            "registration/activation_complete.html",
            {
                'user_logged_in': user_logged_in,
                'already_active': already_active
            }
        )
1064
        return resp
1065
    if len(r) == 0:
1066 1067 1068 1069
        return render_to_response(
            "registration/activation_invalid.html",
            {'csrf': csrf(request)['csrf_token']}
        )
David Baumgold committed
1070
    return HttpResponse(_("Unknown error. Please e-mail us to let us know how it happened."))
Piotr Mitros committed
1071

1072

1073
@ensure_csrf_cookie
Piotr Mitros committed
1074
def password_reset(request):
1075
    """ Attempts to send a password reset e-mail. """
Piotr Mitros committed
1076 1077
    if request.method != "POST":
        raise Http404
Victor Shnayder committed
1078

1079
    form = PasswordResetFormNoActive(request.POST)
Piotr Mitros committed
1080
    if form.is_valid():
Calen Pennington committed
1081 1082 1083 1084 1085
        form.save(use_https=request.is_secure(),
                  from_email=settings.DEFAULT_FROM_EMAIL,
                  request=request,
                  domain_override=request.get_host())
        return HttpResponse(json.dumps({'success': True,
1086 1087
                                        'value': render_to_string('registration/password_reset_done.html', {})}))
    else:
1088
        return HttpResponse(json.dumps({'success': False,
David Baumgold committed
1089 1090
                                        'error': _('Invalid e-mail or user')}))

1091

1092 1093 1094 1095 1096
def password_reset_confirm_wrapper(
    request,
    uidb36=None,
    token=None,
):
1097
    """ A wrapper around django.contrib.auth.views.password_reset_confirm.
1098
        Needed because we want to set the user as active at this step.
1099
    """
1100
    # cribbed from django.contrib.auth.views.password_reset_confirm
1101 1102 1103 1104 1105 1106 1107
    try:
        uid_int = base36_to_int(uidb36)
        user = User.objects.get(id=uid_int)
        user.is_active = True
        user.save()
    except (ValueError, User.DoesNotExist):
        pass
1108 1109 1110 1111 1112 1113
    # we also want to pass settings.PLATFORM_NAME in as extra_context

    extra_context = {"platform_name": settings.PLATFORM_NAME}
    return password_reset_confirm(
        request, uidb36=uidb36, token=token, extra_context=extra_context
    )
1114

Calen Pennington committed
1115

1116
def reactivation_email_for_user(user):
1117 1118 1119 1120
    try:
        reg = Registration.objects.get(user=user)
    except Registration.DoesNotExist:
        return HttpResponse(json.dumps({'success': False,
David Baumgold committed
1121
                                        'error': _('No inactive user with this e-mail exists')}))
1122

1123 1124
    d = {'name': user.profile.name,
         'key': reg.activation_key}
Matthew Mongeau committed
1125

1126
    subject = render_to_string('emails/activation_email_subject.txt', d)
1127
    subject = ''.join(subject.splitlines())
1128
    message = render_to_string('emails/activation_email.txt', d)
1129

1130
    try:
1131
        _res = user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
1132 1133
    except:
        log.warning('Unable to send reactivation email', exc_info=True)
David Baumgold committed
1134
        return HttpResponse(json.dumps({'success': False, 'error': _('Unable to send reactivation email')}))
Matthew Mongeau committed
1135

1136
    return HttpResponse(json.dumps({'success': True}))
Victor Shnayder committed
1137

1138 1139 1140

@ensure_csrf_cookie
def change_email_request(request):
1141 1142
    """ AJAX call from the profile page. User wants a new e-mail.
    """
1143
    ## Make sure it checks for existing e-mail conflicts
1144 1145
    if not request.user.is_authenticated:
        raise Http404
Matthew Mongeau committed
1146

1147 1148 1149
    user = request.user

    if not user.check_password(request.POST['password']):
1150
        return HttpResponse(json.dumps({'success': False,
David Baumgold committed
1151
                                        'error': _('Invalid password')}))
Matthew Mongeau committed
1152

1153
    new_email = request.POST['new_email']
1154 1155 1156
    try:
        validate_email(new_email)
    except ValidationError:
1157
        return HttpResponse(json.dumps({'success': False,
David Baumgold committed
1158
                                        'error': _('Valid e-mail address required.')}))
1159

1160
    if User.objects.filter(email=new_email).count() != 0:
1161
        ## CRITICAL TODO: Handle case sensitivity for e-mails
1162
        return HttpResponse(json.dumps({'success': False,
David Baumgold committed
1163
                                        'error': _('An account with this e-mail already exists.')}))
1164

1165
    pec_list = PendingEmailChange.objects.filter(user=request.user)
Matthew Mongeau committed
1166
    if len(pec_list) == 0:
1167 1168
        pec = PendingEmailChange()
        pec.user = user
1169
    else:
1170 1171 1172 1173 1174 1175
        pec = pec_list[0]

    pec.new_email = request.POST['new_email']
    pec.activation_key = uuid.uuid4().hex
    pec.save()

Matthew Mongeau committed
1176
    if pec.new_email == user.email:
1177
        pec.delete()
1178
        return HttpResponse(json.dumps({'success': False,
David Baumgold committed
1179
                                        'error': _('Old email is the same as the new email.')}))
1180

1181 1182 1183
    d = {'key': pec.activation_key,
         'old_email': user.email,
         'new_email': pec.new_email}
1184

1185
    subject = render_to_string('emails/email_change_subject.txt', d)
1186
    subject = ''.join(subject.splitlines())
1187 1188
    message = render_to_string('emails/email_change.txt', d)

1189
    _res = send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [pec.new_email])
1190

1191
    return HttpResponse(json.dumps({'success': True}))
1192

1193 1194

@ensure_csrf_cookie
1195
@transaction.commit_manually
1196
def confirm_email_change(request, key):
1197
    """ User requested a new e-mail. This is called when the activation
1198
    link is clicked. We confirm with the old e-mail, and update
1199
    """
1200
    try:
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
        try:
            pec = PendingEmailChange.objects.get(activation_key=key)
        except PendingEmailChange.DoesNotExist:
            transaction.rollback()
            return render_to_response("invalid_email_key.html", {})

        user = pec.user
        address_context = {
            'old_email': user.email,
            'new_email': pec.new_email
        }
1212

1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
        if len(User.objects.filter(email=pec.new_email)) != 0:
            transaction.rollback()
            return render_to_response("email_exists.html", {})

        subject = render_to_string('emails/email_change_subject.txt', address_context)
        subject = ''.join(subject.splitlines())
        message = render_to_string('emails/confirm_email_change.txt', address_context)
        up = UserProfile.objects.get(user=user)
        meta = up.get_meta()
        if 'old_emails' not in meta:
            meta['old_emails'] = []
1224
        meta['old_emails'].append([user.email, datetime.datetime.now(UTC).isoformat()])
1225 1226 1227 1228 1229 1230 1231 1232 1233
        up.set_meta(meta)
        up.save()
        # Send it to the old email...
        try:
            user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
        except Exception:
            transaction.rollback()
            log.warning('Unable to send confirmation email to old address', exc_info=True)
            return render_to_response("email_change_failed.html", {'email': user.email})
1234

1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
        user.email = pec.new_email
        user.save()
        pec.delete()
        # And send it to the new email...
        try:
            user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
        except Exception:
            transaction.rollback()
            log.warning('Unable to send confirmation email to new address', exc_info=True)
            return render_to_response("email_change_failed.html", {'email': pec.new_email})

        transaction.commit()
        return render_to_response("email_change_successful.html", address_context)
    except Exception:
        # If we get an unexpected exception, be sure to rollback the transaction
        transaction.rollback()
        raise
1252

1253

1254 1255
@ensure_csrf_cookie
def change_name_request(request):
1256
    """ Log a request for a new name. """
1257 1258
    if not request.user.is_authenticated:
        raise Http404
Matthew Mongeau committed
1259 1260

    try:
1261
        pnc = PendingNameChange.objects.get(user=request.user)
1262
    except PendingNameChange.DoesNotExist:
1263 1264
        pnc = PendingNameChange()
    pnc.user = request.user
1265 1266
    pnc.new_name = request.POST['new_name']
    pnc.rationale = request.POST['rationale']
1267
    if len(pnc.new_name) < 2:
David Baumgold committed
1268
        return HttpResponse(json.dumps({'success': False, 'error': _('Name required')}))
1269
    pnc.save()
1270 1271 1272 1273 1274

    # The following automatically accepts name change requests. Remove this to
    # go back to the old system where it gets queued up for admin approval.
    accept_name_change_by_id(pnc.id)

1275
    return HttpResponse(json.dumps({'success': True}))
1276

1277

1278
@ensure_csrf_cookie
1279
def pending_name_changes(request):
1280
    """ Web page which allows staff to approve or reject name changes. """
1281 1282 1283 1284
    if not request.user.is_staff:
        raise Http404

    changes = list(PendingNameChange.objects.all())
1285
    js = {'students': [{'new_name': c.new_name,
Calen Pennington committed
1286 1287 1288 1289 1290
                        'rationale': c.rationale,
                        'old_name': UserProfile.objects.get(user=c.user).name,
                        'email': c.user.email,
                        'uid': c.user.id,
                        'cid': c.id} for c in changes]}
Matthew Mongeau committed
1291
    return render_to_response('name_changes.html', js)
1292

1293

1294
@ensure_csrf_cookie
1295
def reject_name_change(request):
1296
    """ JSON: Name change process. Course staff clicks 'reject' on a given name change """
1297 1298 1299
    if not request.user.is_staff:
        raise Http404

Matthew Mongeau committed
1300
    try:
1301
        pnc = PendingNameChange.objects.get(id=int(request.POST['id']))
Matthew Mongeau committed
1302
    except PendingNameChange.DoesNotExist:
David Baumgold committed
1303
        return HttpResponse(json.dumps({'success': False, 'error': _('Invalid ID')}))
1304

1305
    pnc.delete()
1306 1307
    return HttpResponse(json.dumps({'success': True}))

1308

1309
def accept_name_change_by_id(id):
Matthew Mongeau committed
1310
    try:
1311
        pnc = PendingNameChange.objects.get(id=id)
Matthew Mongeau committed
1312
    except PendingNameChange.DoesNotExist:
David Baumgold committed
1313
        return HttpResponse(json.dumps({'success': False, 'error': _('Invalid ID')}))
1314 1315 1316

    u = pnc.user
    up = UserProfile.objects.get(user=u)
1317 1318 1319 1320 1321

    # Save old name
    meta = up.get_meta()
    if 'old_names' not in meta:
        meta['old_names'] = []
1322
    meta['old_names'].append([up.name, pnc.rationale, datetime.datetime.now(UTC).isoformat()])
1323 1324 1325
    up.set_meta(meta)

    up.name = pnc.new_name
1326 1327 1328
    up.save()
    pnc.delete()

1329
    return HttpResponse(json.dumps({'success': True}))
1330 1331 1332 1333


@ensure_csrf_cookie
def accept_name_change(request):
1334
    """ JSON: Name change process. Course staff clicks 'accept' on a given name change
Victor Shnayder committed
1335

1336 1337 1338
    We used this during the prototype but now we simply record name changes instead
    of manually approving them. Still keeping this around in case we want to go
    back to this approval method.
1339
    """
1340 1341 1342 1343
    if not request.user.is_staff:
        raise Http404

    return accept_name_change_by_id(int(request.POST['id']))
1344 1345


1346 1347
@require_POST
@login_required
1348 1349 1350 1351 1352 1353 1354 1355
@ensure_csrf_cookie
def change_email_settings(request):
    """Modify logged-in user's setting for receiving emails from a course."""
    user = request.user

    course_id = request.POST.get("course_id")
    receive_emails = request.POST.get("receive_emails")
    if receive_emails:
1356
        optout_object = Optout.objects.filter(user=user, course_id=course_id)
1357 1358
        if optout_object:
            optout_object.delete()
1359
        log.info(u"User {0} ({1}) opted in to receive emails from course {2}".format(user.username, user.email, course_id))
1360 1361
        track.views.server_track(request, "change-email-settings", {"receive_emails": "yes", "course": course_id}, page='dashboard')
    else:
1362
        Optout.objects.get_or_create(user=user, course_id=course_id)
1363 1364 1365 1366
        log.info(u"User {0} ({1}) opted out of receiving emails from course {2}".format(user.username, user.email, course_id))
        track.views.server_track(request, "change-email-settings", {"receive_emails": "no", "course": course_id}, page='dashboard')

    return HttpResponse(json.dumps({'success': True}))