Newer
Older
Piotr Mitros
committed
import json
Piotr Mitros
committed
import random
import string
Piotr Mitros
committed
from django.conf import settings
from django.contrib.auth import logout, authenticate, login
from django.contrib.auth.forms import PasswordResetForm
Piotr Mitros
committed
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.core.validators import validate_email, validate_slug, ValidationError
Calen Pennington
committed
from django.db import IntegrityError
David Ormsbee
committed
from django.http import HttpResponse, HttpResponseForbidden, Http404
Piotr Mitros
committed
from django.shortcuts import redirect
Piotr Mitros
committed
from mitxmako.shortcuts import render_to_response, render_to_string
from bs4 import BeautifulSoup
from django.core.cache import cache
from django_future.csrf import ensure_csrf_cookie, csrf_exempt
from student.models import (Registration, UserProfile, TestCenterUser, TestCenterRegistration,
CourseEnrollment, unique_id_for_user)
from certificates.models import CertificateStatuses, certificate_status_for_student
from xmodule.course_module import CourseDescriptor
from xmodule.modulestore.exceptions import ItemNotFoundError
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.exceptions import ItemNotFoundError
from courseware.courses import get_courses_by_university
from courseware.access import has_access
Vik Paruchuri
committed
from statsd import statsd
log = logging.getLogger("mitx.student")
Article = namedtuple('Article', 'title url author image deck publication publish_date')
csrf_token = context.get('csrf_token', '')
if csrf_token == 'NOTPROVIDED':
return ''
return (u'<div style="display:none"><input type="hidden"'
' name="csrfmiddlewaretoken" value="%s" /></div>' % (csrf_token))
# 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)
Calen Pennington
committed
def index(request, extra_context={}, user=None):
'''
Render the edX main page.
extra_context is used to allow immediate display of certain modal windows, eg signup,
as used by external_auth.
'''
# The course selection work is done in courseware.courses.
ichuang
committed
domain = settings.MITX_FEATURES.get('FORCE_UNIVERSITY_DOMAIN') # normally False
if domain==False: # do explicit check, because domain=None is valid
ichuang
committed
domain = request.META.get('HTTP_HOST')
universities = get_courses_by_university(None,
ichuang
committed
domain=domain)
# Get the 3 most recent news
top_news = _get_news(top=3)
context = {'universities': universities, 'news': top_news}
context.update(extra_context)
return render_to_response('index.html', context)
def course_from_id(course_id):
"""Return the CourseDescriptor corresponding to this course_id"""
course_loc = CourseDescriptor.id_to_location(course_id)
return modulestore().get_instance(course_id, course_loc)
import re
day_pattern = re.compile('\s\d+,\s')
multimonth_pattern = re.compile('\s?\-\s?\S+\s')
def get_date_for_press(publish_date):
import datetime
# strip off extra months, and just use the first:
date = re.sub(multimonth_pattern, ", ", publish_date)
if re.search(day_pattern, date):
date = datetime.datetime.strptime(date, "%B %d, %Y")
else:
date = datetime.datetime.strptime(date, "%B, %Y")
return date
def press(request):
json_articles = cache.get("student_press_json_articles")
if json_articles == None:
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]
articles.sort(key=lambda item: get_date_for_press(item.publish_date), reverse=True)
return render_to_response('static_templates/press.html', {'articles': articles})
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.
"""
return survey_link.format(UNIQUE_ID=unique_id_for_user(user))
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:
'status': one of 'generating', 'ready', 'notpassing', 'processing'
'show_download_url': bool
'download_url': url, only present if show_download_url is True
'show_disabled_download_button': bool -- true if state is 'generating'
'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))
def _cert_info(user, course, cert_status):
"""
Implements the logic for cert_info -- split out for testing.
"""
default_status = 'processing'
default_info = {'status': default_status,
'show_disabled_download_button': False,
'show_download_url': False,
'show_survey_button': False}
if cert_status is None:
return default_info
# simplify the status for the template using this lookup table
template_state = {
CertificateStatuses.generating: 'generating',
CertificateStatuses.regenerating: 'generating',
CertificateStatuses.downloadable: 'ready',
CertificateStatuses.notpassing: 'notpassing',
}
status = template_state.get(cert_status['status'], default_status)
d = {'status': status,
'show_download_url': status == 'ready',
'show_disabled_download_button': status == 'generating',}
if (status in ('generating', 'ready', 'notpassing') and
course.end_of_course_survey_url is not None):
d.update({
'show_survey_button': True,
'survey_url': process_survey_link(course.end_of_course_survey_url, user)})
else:
d['show_survey_button'] = False
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)
else:
d['download_url'] = cert_status['download_url']
if status in ('generating', 'ready', 'notpassing'):
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.
else:
d['grade'] = cert_status['grade']
return d
Matthew Mongeau
committed
user = request.user
enrollments = CourseEnrollment.objects.filter(user=user)
# 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
# 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 = []
for enrollment in enrollments:
try:
courses.append(course_from_id(enrollment.course_id))
except ItemNotFoundError:
log.error("User {0} enrolled in non-existent course {1}"
.format(user.username, enrollment.course_id))
message = ""
if not user.is_active:
message = render_to_string('registration/activate_account_notice.html', {'email': user.email})
# Global staff can see what courses errored on their dashboard
staff_access = False
if has_access(user, 'global', 'staff'):
# Show any courses that errored on load
staff_access = True
errored_courses = modulestore().get_errored_courses()
David Ormsbee
committed
show_courseware_links_for = frozenset(course.id for course in courses
if has_access(request.user, course, 'load'))
cert_statuses = { course.id: cert_info(request.user, course) for course in courses}
# Get the 3 most recent news
top_news = _get_news(top=3)
context = {'courses': courses,
'message': message,
'staff_access': staff_access,
David Ormsbee
committed
'errored_courses': errored_courses,
'show_courseware_links_for' : show_courseware_links_for,
'cert_statuses': cert_statuses,
'news': top_news,
'testcenteruser': testcenteruser,
Matthew Mongeau
committed
return render_to_response('dashboard.html', context)
Bridger Maxwell
committed
def try_change_enrollment(request):
"""
This method calls change_enrollment if the necessary POST
Bridger Maxwell
committed
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:
enrollment_output = change_enrollment(request)
# 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
log.info("Attempted to automatically enroll after login. Results: {0}".format(enrollment_output))
except Exception, e:
log.exception("Exception automatically enrolling after login: {0}".format(str(e)))
Bridger Maxwell
committed
@login_required
def change_enrollment_view(request):
"""Delegate to change_enrollment to actually do the work."""
return HttpResponse(json.dumps(change_enrollment(request)))
def change_enrollment(request):
if request.method != "POST":
raise Http404
user = request.user
if not user.is_authenticated():
raise Http404
action = request.POST.get("enrollment_action", "")
course_id = request.POST.get("course_id", None)
if course_id == None:
return HttpResponse(json.dumps({'success': False,
'error': 'There was an error receiving the course id.'}))
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:
Brian Wilson
committed
log.warning("User {0} tried to enroll in non-existent course {1}"
.format(user.username, enrollment.course_id))
return {'success': False, 'error': 'The course requested does not exist.'}
if not has_access(user, course, 'enroll'):
return {'success': False,
'error': 'enrollment in {} not allowed at this time'
.format(course.display_name)}
statsd.increment("common.student.enrollment",
tags=["org:{0}".format(org),
"course:{0}".format(course_num),
"run:{0}".format(run)])
enrollment, created = CourseEnrollment.objects.get_or_create(user=user, course_id=course.id)
return {'success': True}
elif action == "unenroll":
try:
enrollment = CourseEnrollment.objects.get(user=user, course_id=course_id)
enrollment.delete()
statsd.increment("common.student.unenrollment",
tags=["org:{0}".format(org),
"course:{0}".format(course_num),
"run:{0}".format(run)])
return {'success': True}
except CourseEnrollment.DoesNotExist:
return {'success': False, 'error': 'You are not enrolled for this course.'}
else:
return {'success': False, 'error': 'Invalid enrollment_action.'}
return {'success': False, 'error': 'We weren\'t able to unenroll you. Please try again.'}
# Need different levels of logging
@ensure_csrf_cookie
''' AJAX request to log in the user. '''
if 'email' not in request.POST or 'password' not in request.POST:
return HttpResponse(json.dumps({'success': False,
'value': 'There was an error receiving your login information. Please email us.'})) # TODO: User error message
email = request.POST['email']
password = request.POST['password']
user = User.objects.get(email=email)
log.warning("Login failed - Unknown user email: {0}".format(email))
return HttpResponse(json.dumps({'success': False,
'value': 'Email or password is incorrect.'})) # TODO: User error message
username = user.username
user = authenticate(username=username, password=password)
log.warning("Login failed - password for {0} is invalid".format(email))
return HttpResponse(json.dumps({'success': False,
'value': 'Email or password is incorrect.'}))
try:
login(request, user)
if request.POST.get('remember') == 'true':
request.session.set_expiry(None) # or change to 604800 for 7 days
log.debug("Setting user session to never expire")
else:
request.session.set_expiry(0)
except Exception as e:
log.critical("Login failed - Could not create session. Is memcached running?")
log.exception(e)
log.info("Login success - {0} ({1})".format(username, email))
Bridger Maxwell
committed
try_change_enrollment(request)
statsd.increment("common.student.successful_login")
return HttpResponse(json.dumps({'success': True}))
log.warning("Login failed - Account not active for user {0}, resending activation".format(username))
reactivation_email_for_user(user)
not_activated_msg = "This account has not been activated. We have " + \
"sent another activation message. Please check your " + \
"e-mail for the activation instructions."
return HttpResponse(json.dumps({'success': False,
'value': not_activated_msg}))
@ensure_csrf_cookie
''' HTTP request to log out the user. Redirects to marketing page'''
Calen Pennington
committed
@login_required
@ensure_csrf_cookie
def change_setting(request):
# TODO (vshnayder): location is no longer used
up = UserProfile.objects.get(user=request.user) # request.user.profile_cache
up.save()
return HttpResponse(json.dumps({'success': True,
'location': up.location, }))
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.
"""
user = User(username=post_vars['username'],
email=post_vars['email'],
is_active=False)
user.set_password(post_vars['password'])
registration = Registration()
# 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:
js = {'success': False}
# Figure out the cause of the integrity error
if len(User.objects.filter(username=post_vars['username'])) > 0:
js['value'] = "An account with this username already exists."
js['field'] = 'username'
return HttpResponse(json.dumps(js))
if len(User.objects.filter(email=post_vars['email'])) > 0:
js['value'] = "An account with this e-mail already exists."
js['field'] = 'email'
return HttpResponse(json.dumps(js))
raise
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')
profile.year_of_birth = int(post_vars['year_of_birth'])
except (ValueError, KeyError):
profile.year_of_birth = None # If they give us garbage, just ignore it instead
# of asking them to put an integer.
try:
log.exception("UserProfile creation failed for user {0}.".format(user.id))
return (user, profile, registration)
@ensure_csrf_cookie
Bridger Maxwell
committed
def create_account(request, post_override=None):
'''
JSON call to create new edX account.
Used by form in signup_modal.html, which is included into navigation.html
'''
Bridger Maxwell
committed
post_vars = post_override if post_override else request.POST
# 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
DoExternalAuth = 'ExternalAuthMap' in request.session
if DoExternalAuth:
eamap = request.session['ExternalAuthMap']
email = eamap.external_email
name = eamap.external_name
password = eamap.internal_password
post_vars = dict(post_vars.items())
post_vars.update(dict(email=email, name=name, password=password))
log.debug('extauth test: post_vars = %s' % post_vars)
Bridger Maxwell
committed
if a not in post_vars:
js['value'] = "Error (401 {field}). E-mail us.".format(field=a)
if post_vars.get('honor_code', 'false') != u'true':
js['value'] = "To enroll, you must follow the honor code.".format(field=a)
js['field'] = 'honor_code'
if post_vars.get('terms_of_service', 'false') != u'true':
js['value'] = "You must accept the terms of service.".format(field=a)
js['field'] = 'terms_of_service'
# 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
for a in ['username', 'email', 'name', 'password', 'terms_of_service', 'honor_code']:
if len(post_vars[a]) < 2:
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.',
'password': 'A valid password is required.',
'terms_of_service': 'Accepting Terms of Service is required.',
'honor_code': 'Agreeing to the Honor Code is required.'}
Bridger Maxwell
committed
validate_email(post_vars['email'])
js['value'] = "Valid e-mail is required.".format(field=a)
Bridger Maxwell
committed
validate_slug(post_vars['username'])
js['value'] = "Username should only consist of A-Z and 0-9.".format(field=a)
# Ok, looks like everything is legit. Create the account.
ret = _do_create_account(post_vars)
if isinstance(ret,HttpResponse): # if there was an error then return that
return ret
(user, profile, registration) = ret
d = {'name': post_vars['name'],
'key': registration.activation_key,
subject = render_to_string('emails/activation_email_subject.txt', d)
message = render_to_string('emails/activation_email.txt', d)
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)
elif not settings.GENERATE_RANDOM_USER_CREDENTIALS:
res = user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
js['value'] = 'Could not send activation e-mail.'
# 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.
login_user = authenticate(username=post_vars['username'], password=post_vars['password'])
login(request, login_user)
Bridger Maxwell
committed
try_change_enrollment(request)
eamap.user = login_user
eamap.dtsignup = datetime.datetime.now()
eamap.save()
log.debug('Updated ExternalAuthMap for %s to be %s' % (post_vars['username'],eamap))
if settings.MITX_FEATURES.get('BYPASS_ACTIVATION_EMAIL_FOR_EXTAUTH'):
log.debug('bypassing activation email')
login_user.is_active = True
login_user.save()
statsd.increment("common.student.account_created")
return HttpResponse(json.dumps(js), mimetype="application/json")
Brian Wilson
committed
@login_required
@ensure_csrf_cookie
def begin_test_registration(request, course_id):
user = request.user
# 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
try:
course = (course_from_id(course_id))
except ItemNotFoundError:
log.error("User {0} enrolled in non-existent course {1}"
.format(user.username, course_id))
# TODO: placeholder for possible messages...
Brian Wilson
committed
message = ""
if not user.is_active:
message = render_to_string('registration/activate_account_notice.html', {'email': user.email})
context = {'course': course,
'user': user,
'message': message,
'testcenteruser': testcenteruser,
}
return render_to_response('test_center_register.html', context)
def _do_create_or_update_test_center_user(post_vars):
"""
Given cleaned post variables, create the TestCenterUser and UserProfile objects, as well as the
registration for this user.
Returns a tuple (User, UserProfile, TestCenterUser).
Brian Wilson
committed
"""
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
# first determine if we need to create a new TestCenterUser, or if we are making any update
# to an existing TestCenterUser.
username=post_vars['username']
user = User.objects.get(username=username)
needs_saving = False
try:
testcenter_user = TestCenterUser.objects.get(user=user)
# found a TestCenterUser, so check to see if it has changed
needs_updating = any([testcenter_user.__getattribute__(fieldname) != post_vars[fieldname]
for fieldname in TestCenterUser.user_provided_fields()])
if needs_updating:
# TODO: what do we set a timestamp to, in order to get now()?
testcenter_user.user_updated_at = datetime.datetime.now()
# Now do the update:
for fieldname in TestCenterUser.user_provided_fields():
testcenter_user.__setattr__(fieldname, post_vars[fieldname])
needs_saving = True
except TestCenterUser.DoesNotExist:
# did not find the TestCenterUser, so create a new one
testcenter_user = TestCenterUser(user=user)
# testcenter_user.user = user
for fieldname in TestCenterUser.user_provided_fields():
testcenter_user.__setattr__(fieldname, post_vars[fieldname])
# testcenter_user.candidate_id remains unset
testcenter_user.client_candidate_id = 'edx' + '123456' # some unique value
testcenter_user.user_updated_at = datetime.datetime.now()
needs_saving = True
# additional validation occurs at save time, so handle exceptions
Brian Wilson
committed
# 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
if needs_saving:
try:
testcenter_user.save()
except IntegrityError:
js = {'success': False}
# TODO: Figure out the cause of the integrity error
if len(User.objects.filter(username=post_vars['username'])) > 0:
js['value'] = "An account with this username already exists."
js['field'] = 'username'
return HttpResponse(json.dumps(js))
if len(User.objects.filter(email=post_vars['email'])) > 0:
js['value'] = "An account with this e-mail already exists."
js['field'] = 'email'
return HttpResponse(json.dumps(js))
raise
registration = TestCenterRegistration(testcenter_user = testcenter_user)
# registration.register(user)
Brian Wilson
committed
registration.accommodation_request = post_vars['accommodations']
Brian Wilson
committed
return (user, testcenter_user, registration)
Brian Wilson
committed
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
@ensure_csrf_cookie
def create_test_registration(request, post_override=None):
'''
JSON call to create test registration.
Used by form in test_center_register_modal.html, which is included
into dashboard.html
'''
js = {'success': False}
post_vars = post_override if post_override else request.POST
# Confirm we have a properly formed request
for a in ['first_name', 'last_name', 'address_1', 'city', 'country']:
if a not in post_vars:
js['value'] = "Error (401 {field}). E-mail us.".format(field=a)
js['field'] = a
return HttpResponse(json.dumps(js))
# Confirm appropriate fields are there.
for a in ['first_name', 'last_name', 'address_1', 'city', 'country']:
if len(post_vars[a]) < 2:
error_str = {'first_name': 'First name must be minimum of two characters long.',
'last_name': 'Last name must be minimum of two characters long.',
'address_1': 'Last name must be minimum of two characters long.',
'city': 'Last name must be minimum of two characters long.',
'country': 'Last name must be minimum of two characters long.',
}
js['value'] = error_str[a]
js['field'] = a
return HttpResponse(json.dumps(js))
# Once the test_center_user information has been validated, create the entries:
ret = _do_create_or_update_test_center_user(post_vars)
if isinstance(ret,HttpResponse): # if there was an error then return that
return ret
(user, testcenter_user, testcenter_registration) = ret
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
# only do the following if there is accommodation text to send,
# and a destination to which to send it:
if 'accommodation' in post_vars and settings.MITX_FEATURES.get('ACCOMMODATION_EMAIL'):
d = {'accommodation': post_vars['accommodation']
}
# 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)
# skip if destination email address is not specified
try:
dest_addr = settings.MITX_FEATURES['ACCOMMODATION_EMAIL']
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [dest_addr], fail_silently=False)
except:
log.exception(sys.exc_info())
js['value'] = 'Could not send accommodation e-mail.'
return HttpResponse(json.dumps(js))
# statsd.increment("common.student.account_created")
js = {'success': True}
return HttpResponse(json.dumps(js), mimetype="application/json")
def get_random_post_override():
"""
Return a dictionary suitable for passing to post_vars of _do_create_account or post_override
of create_account, with random user info.
"""
Bridger Maxwell
committed
def id_generator(size=6, chars=string.ascii_uppercase + string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for x in range(size))
return {'username': "random_" + id_generator(),
'email': id_generator(size=10, chars=string.ascii_lowercase) + "_dummy_test@mitx.mit.edu",
'password': id_generator(),
'name': (id_generator(size=5, chars=string.ascii_lowercase) + " " +
id_generator(size=7, chars=string.ascii_lowercase)),
'honor_code': u'true',
'terms_of_service': u'true', }
def create_random_account(create_account_function):
def inner_create_random_account(request):
return create_account_function(request, post_override=get_random_post_override())
Bridger Maxwell
committed
return inner_create_random_account
# TODO (vshnayder): do we need GENERATE_RANDOM_USER_CREDENTIALS for anything?
Bridger Maxwell
committed
if settings.GENERATE_RANDOM_USER_CREDENTIALS:
create_account = create_random_account(create_account)
@ensure_csrf_cookie
''' When link in activation e-mail is clicked
'''
r = Registration.objects.filter(activation_key=key)
if len(r) == 1:
Bridger Maxwell
committed
user_logged_in = request.user.is_authenticated()
already_active = True
if not r[0].user.is_active:
r[0].activate()
Bridger Maxwell
committed
already_active = False
resp = render_to_response("registration/activation_complete.html", {'user_logged_in': user_logged_in, 'already_active': already_active})
if len(r) == 0:
return render_to_response("registration/activation_invalid.html", {'csrf': csrf(request)['csrf_token']})
return HttpResponse("Unknown error. Please e-mail us to let us know how it happened.")
@ensure_csrf_cookie
def password_reset(request):
''' Attempts to send a password reset e-mail. '''
if request.method != "POST":
raise Http404
# By default, Django doesn't allow Users with is_active = False to reset their passwords,
# but this bites people who signed up a long time ago, never activated, and forgot their
# password. So for their sake, we'll auto-activate a user for whom password_reset is called.
try:
user = User.objects.get(email=request.POST['email'])
user.is_active = True
user.save()
except:
log.exception("Tried to auto-activate user to enable password reset, but failed.")
form = PasswordResetForm(request.POST)
if form.is_valid():
form.save(use_https = request.is_secure(),
from_email = settings.DEFAULT_FROM_EMAIL,
request = request,
Arjun Singh
committed
domain_override = request.get_host())
return HttpResponse(json.dumps({'success':True,
'value': render_to_string('registration/password_reset_done.html', {})}))
else:
return HttpResponse(json.dumps({'success': False,
@ensure_csrf_cookie
def reactivation_email(request):
''' Send an e-mail to reactivate a deactivated account, or to
return HttpResponse(json.dumps({'success': False,
'error': 'No inactive user with this e-mail exists'}))
return reactivation_email_for_user(user)
def reactivation_email_for_user(user):
reg = Registration.objects.get(user=user)
d = {'name': user.profile.name,
'key': reg.activation_key}
subject = render_to_string('emails/activation_email_subject.txt', d)
subject = ''.join(subject.splitlines())
message = render_to_string('emails/activation_email.txt', d)
res = user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
return HttpResponse(json.dumps({'success': True}))
@ensure_csrf_cookie
def change_email_request(request):
''' AJAX call from the profile page. User wants a new e-mail.
'''
## Make sure it checks for existing e-mail conflicts
if not request.user.is_authenticated:
raise Http404
user = request.user
if not user.check_password(request.POST['password']):
return HttpResponse(json.dumps({'success': False,
'error': 'Invalid password'}))
new_email = request.POST['new_email']
try:
validate_email(new_email)
except ValidationError:
return HttpResponse(json.dumps({'success': False,
'error': 'Valid e-mail address required.'}))
if len(User.objects.filter(email=new_email)) != 0:
## CRITICAL TODO: Handle case sensitivity for e-mails
return HttpResponse(json.dumps({'success': False,
'error': 'An account with this e-mail already exists.'}))
pec_list = PendingEmailChange.objects.filter(user=request.user)
pec = PendingEmailChange()
pec.user = user
pec = pec_list[0]
pec.new_email = request.POST['new_email']
pec.activation_key = uuid.uuid4().hex
pec.save()
return HttpResponse(json.dumps({'success': False,
'error': 'Old email is the same as the new email.'}))
d = {'key': pec.activation_key,
'old_email': user.email,
'new_email': pec.new_email}
subject = render_to_string('emails/email_change_subject.txt', d)
subject = ''.join(subject.splitlines())
message = render_to_string('emails/email_change.txt', d)
res = send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [pec.new_email])
return HttpResponse(json.dumps({'success': True}))
def confirm_email_change(request, key):
''' User requested a new e-mail. This is called when the activation
link is clicked. We confirm with the old e-mail, and update
'''
try:
pec = PendingEmailChange.objects.get(activation_key=key)
return render_to_response("invalid_email_key.html", {})
d = {'old_email': user.email,
'new_email': pec.new_email}
if len(User.objects.filter(email=pec.new_email)) != 0:
return render_to_response("email_exists.html", d)
subject = render_to_string('emails/email_change_subject.txt', d)
subject = ''.join(subject.splitlines())
message = render_to_string('emails/confirm_email_change.txt', d)
up = UserProfile.objects.get(user=user)
meta = up.get_meta()
if 'old_emails' not in meta:
meta['old_emails'] = []
meta['old_emails'].append([user.email, datetime.datetime.now().isoformat()])
# Send it to the old email...
user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
user.email = pec.new_email
user.save()
pec.delete()
# And send it to the new email...
user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
return render_to_response("email_change_successful.html", d)
@ensure_csrf_cookie
def change_name_request(request):
if not request.user.is_authenticated:
raise Http404
pnc = PendingNameChange.objects.get(user=request.user)
pnc = PendingNameChange()
pnc.user = request.user
pnc.new_name = request.POST['new_name']
pnc.rationale = request.POST['rationale']
if len(pnc.new_name) < 2:
return HttpResponse(json.dumps({'success': False, 'error': 'Name required'}))
# 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)
return HttpResponse(json.dumps({'success': True}))
def pending_name_changes(request):
''' Web page which allows staff to approve or reject name changes. '''
if not request.user.is_staff:
raise Http404
changes = list(PendingNameChange.objects.all())
js = {'students': [{'new_name': c.new_name,
'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]}
return render_to_response('name_changes.html', js)