Commit 8f4b6faa by Calen Pennington

Merge pull request #72 from MITx/stable-anonymous-user

Pull in guest access to the stable branch
parents 4022478f 0fe9751e
import hashlib import hashlib
import json
import logging import logging
import os import os
import re import re
...@@ -14,7 +13,7 @@ try: # This lets us do __name__ == ='__main__' ...@@ -14,7 +13,7 @@ try: # This lets us do __name__ == ='__main__'
from student.models import UserProfile from student.models import UserProfile
from student.models import UserTestGroup from student.models import UserTestGroup
from mitxmako.shortcuts import render_to_response, render_to_string from mitxmako.shortcuts import render_to_string
from util.cache import cache from util.cache import cache
except: except:
settings = None settings = None
...@@ -97,20 +96,9 @@ def item(l, default="", process=lambda x:x): ...@@ -97,20 +96,9 @@ def item(l, default="", process=lambda x:x):
def id_tag(course): def id_tag(course):
''' Tag all course elements with unique IDs ''' ''' Tag all course elements with unique IDs '''
old_ids = {'video':'youtube',
'problem':'filename',
'sequential':'id',
'html':'filename',
'vertical':'id',
'tab':'id',
'schematic':'id',
'book' : 'id'}
import courseware.modules import courseware.modules
default_ids = courseware.modules.get_default_ids() default_ids = courseware.modules.get_default_ids()
#print default_ids, old_ids
#print default_ids == old_ids
# Tag elements with unique IDs # Tag elements with unique IDs
elements = course.xpath("|".join(['//'+c for c in default_ids])) elements = course.xpath("|".join(['//'+c for c in default_ids]))
for elem in elements: for elem in elements:
...@@ -153,6 +141,9 @@ def propogate_downward_tag(element, attribute_name, parent_attribute = None): ...@@ -153,6 +141,9 @@ def propogate_downward_tag(element, attribute_name, parent_attribute = None):
return return
def user_groups(user): def user_groups(user):
if not user.is_authenticated():
return []
# TODO: Rewrite in Django # TODO: Rewrite in Django
key = 'user_group_names_{user.id}'.format(user=user) key = 'user_group_names_{user.id}'.format(user=user)
cache_expiration = 60 * 60 # one hour cache_expiration = 60 * 60 # one hour
...@@ -177,15 +168,18 @@ def course_xml_process(tree): ...@@ -177,15 +168,18 @@ def course_xml_process(tree):
propogate_downward_tag(tree, "due") propogate_downward_tag(tree, "due")
propogate_downward_tag(tree, "graded") propogate_downward_tag(tree, "graded")
propogate_downward_tag(tree, "graceperiod") propogate_downward_tag(tree, "graceperiod")
propogate_downward_tag(tree, "showanswer")
propogate_downward_tag(tree, "rerandomize")
return tree return tree
def course_file(user): def course_file(user):
''' Given a user, return course.xml''' ''' Given a user, return course.xml'''
#import logging
#log = logging.getLogger("tracking")
#log.info( "DEBUG: cf:"+str(user) )
if user.is_authenticated():
filename = UserProfile.objects.get(user=user).courseware # user.profile_cache.courseware filename = UserProfile.objects.get(user=user).courseware # user.profile_cache.courseware
else:
filename = 'guest_course.xml'
groups = user_groups(user) groups = user_groups(user)
options = {'dev_content':settings.DEV_CONTENT, options = {'dev_content':settings.DEV_CONTENT,
'groups' : groups} 'groups' : groups}
......
import StringIO
import json
import logging import logging
import os
import sys
import sys
import urllib
import uuid
from lxml import etree from lxml import etree
from django.conf import settings from mitxmako.shortcuts import render_to_string
from django.contrib.auth.models import User
from django.core.context_processors import csrf
from django.db import connection
from django.http import Http404
from django.http import HttpResponse
from django.shortcuts import redirect
from django.template import Context
from django.template import Context, loader
from mitxmako.shortcuts import render_to_response, render_to_string
from models import StudentModule from models import StudentModule
from student.models import UserProfile
import track.views import track.views
import courseware.content_parser as content_parser
import courseware.modules import courseware.modules
log = logging.getLogger("mitx.courseware") log = logging.getLogger("mitx.courseware")
...@@ -51,47 +32,6 @@ def make_track_function(request): ...@@ -51,47 +32,6 @@ def make_track_function(request):
return track.views.server_track(request, event_type, event, page='x_module') return track.views.server_track(request, event_type, event, page='x_module')
return f return f
def modx_dispatch(request, module=None, dispatch=None, id=None):
''' Generic view for extensions. '''
if not request.user.is_authenticated():
return redirect('/')
# Grab the student information for the module from the database
s = StudentModule.objects.filter(student=request.user,
module_id=id)
#s = StudentModule.get_with_caching(request.user, id)
if len(s) == 0 or s is None:
log.debug("Couldnt find module for user and id " + str(module) + " " + str(request.user) + " "+ str(id))
raise Http404
s = s[0]
oldgrade = s.grade
oldstate = s.state
dispatch=dispatch.split('?')[0]
ajax_url = '/modx/'+module+'/'+id+'/'
# Grab the XML corresponding to the request from course.xml
xml = content_parser.module_xml(request.user, module, 'id', id)
# Create the module
instance=courseware.modules.get_module_class(module)(xml,
id,
ajax_url=ajax_url,
state=oldstate,
track_function = make_track_function(request),
render_function = None)
# Let the module handle the AJAX
ajax_return=instance.handle_ajax(dispatch, request.POST)
# Save the state back to the database
s.state=instance.get_state()
if instance.get_score():
s.grade=instance.get_score()['score']
if s.grade != oldgrade or s.state != oldstate:
s.save()
# Return whatever the module wanted to return to the client/caller
return HttpResponse(ajax_return)
def grade_histogram(module_id): def grade_histogram(module_id):
''' Print out a histogram of grades on a given problem. ''' Print out a histogram of grades on a given problem.
...@@ -134,8 +74,9 @@ def render_x_module(user, request, xml_module, module_object_preload): ...@@ -134,8 +74,9 @@ def render_x_module(user, request, xml_module, module_object_preload):
track_function = make_track_function(request), track_function = make_track_function(request),
render_function = lambda x: render_module(user, request, x, module_object_preload)) render_function = lambda x: render_module(user, request, x, module_object_preload))
# If instance wasn't already in the database, create it # If instance wasn't already in the database, and this
if not smod: # isn't a guest user, create it
if not smod and user.is_authenticated():
smod=StudentModule(student=user, smod=StudentModule(student=user,
module_type = module_type, module_type = module_type,
module_id=module_id, module_id=module_id,
......
...@@ -92,10 +92,13 @@ class Module(XModule): ...@@ -92,10 +92,13 @@ class Module(XModule):
# User submitted a problem, and hasn't reset. We don't want # User submitted a problem, and hasn't reset. We don't want
# more submissions. # more submissions.
if self.lcp.done and self.rerandomize == "always": if self.lcp.done and self.rerandomize == "always":
#print "!"
check_button = False check_button = False
save_button = False save_button = False
# Only show the reset button if pressing it will show different values
if self.rerandomize != 'always':
reset_button = False
# User hasn't submitted an answer yet -- we don't want resets # User hasn't submitted an answer yet -- we don't want resets
if not self.lcp.done: if not self.lcp.done:
reset_button = False reset_button = False
...@@ -241,7 +244,8 @@ class Module(XModule): ...@@ -241,7 +244,8 @@ class Module(XModule):
return True return True
if self.show_answer == 'closed' and not self.closed(): if self.show_answer == 'closed' and not self.closed():
return False return False
print "aa", self.show_answer if self.show_answer == 'always':
return True
raise Http404 raise Http404
def get_answer(self, get): def get_answer(self, get):
...@@ -270,15 +274,12 @@ class Module(XModule): ...@@ -270,15 +274,12 @@ class Module(XModule):
for key in get: for key in get:
answers['_'.join(key.split('_')[1:])]=get[key] answers['_'.join(key.split('_')[1:])]=get[key]
# print "XXX", answers, get
event_info['answers']=answers event_info['answers']=answers
# Too late. Cannot submit # Too late. Cannot submit
if self.closed(): if self.closed():
event_info['failure']='closed' event_info['failure']='closed'
self.tracker('save_problem_check_fail', event_info) self.tracker('save_problem_check_fail', event_info)
print "cp"
raise Http404 raise Http404
# Problem submitted. Student should reset before checking # Problem submitted. Student should reset before checking
...@@ -286,7 +287,6 @@ class Module(XModule): ...@@ -286,7 +287,6 @@ class Module(XModule):
if self.lcp.done and self.rerandomize == "always": if self.lcp.done and self.rerandomize == "always":
event_info['failure']='unreset' event_info['failure']='unreset'
self.tracker('save_problem_check_fail', event_info) self.tracker('save_problem_check_fail', event_info)
print "cpdr"
raise Http404 raise Http404
try: try:
...@@ -297,10 +297,6 @@ class Module(XModule): ...@@ -297,10 +297,6 @@ class Module(XModule):
except StudentInputError as inst: except StudentInputError as inst:
self.lcp = LoncapaProblem(filename, id=lcp_id, state=old_state) self.lcp = LoncapaProblem(filename, id=lcp_id, state=old_state)
traceback.print_exc() traceback.print_exc()
# print {'error':sys.exc_info(),
# 'answers':answers,
# 'seed':self.lcp.seed,
# 'filename':self.lcp.filename}
return json.dumps({'success':inst.message}) return json.dumps({'success':inst.message})
except: except:
self.lcp = LoncapaProblem(filename, id=lcp_id, state=old_state) self.lcp = LoncapaProblem(filename, id=lcp_id, state=old_state)
...@@ -316,15 +312,13 @@ class Module(XModule): ...@@ -316,15 +312,13 @@ class Module(XModule):
if correct_map[i]!='correct': if correct_map[i]!='correct':
success = 'incorrect' success = 'incorrect'
js=json.dumps({'correct_map' : correct_map,
'success' : success})
event_info['correct_map']=correct_map event_info['correct_map']=correct_map
event_info['success']=success event_info['success']=success
self.tracker('save_problem_check', event_info) self.tracker('save_problem_check', event_info)
return js return json.dumps({'success': success,
'contents': self.get_problem_html(encapsulate=False)})
def save_problem(self, get): def save_problem(self, get):
event_info = dict() event_info = dict()
......
import logging import logging
import os
import random
import sys
import StringIO
import urllib import urllib
import uuid
from django.conf import settings from django.conf import settings
from django.core.context_processors import csrf from django.core.context_processors import csrf
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.http import HttpResponse, Http404 from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponse
from django.shortcuts import redirect from django.shortcuts import redirect
from django.template import Context, loader
from mitxmako.shortcuts import render_to_response, render_to_string from mitxmako.shortcuts import render_to_response, render_to_string
#from django.views.decorators.csrf import ensure_csrf_cookie #from django.views.decorators.csrf import ensure_csrf_cookie
from django.db import connection
from django.views.decorators.cache import cache_control from django.views.decorators.cache import cache_control
from django_future.csrf import ensure_csrf_cookie from django_future.csrf import ensure_csrf_cookie
from lxml import etree from lxml import etree
from courseware import course_settings from courseware import course_settings
from module_render import render_module, modx_dispatch from module_render import render_module, modx_dispatch, make_track_function
from certificates.models import GeneratedCertificate, certificate_state_for_student from certificates.models import GeneratedCertificate, certificate_state_for_student
from models import StudentModule from models import StudentModule
from student.models import UserProfile from student.models import UserProfile
from student.views import student_took_survey from student.views import student_took_survey
import courseware.content_parser as content_parser import courseware.content_parser as content_parser
import courseware.modules.capa_module import courseware.modules
import courseware.grades as grades import courseware.grades as grades
...@@ -56,12 +50,11 @@ def gradebook(request): ...@@ -56,12 +50,11 @@ def gradebook(request):
'grade_cutoffs' : course_settings.GRADE_CUTOFFS,} 'grade_cutoffs' : course_settings.GRADE_CUTOFFS,}
) )
@login_required
@cache_control(no_cache=True, no_store=True, must_revalidate=True) @cache_control(no_cache=True, no_store=True, must_revalidate=True)
def profile(request, student_id = None): def profile(request, student_id = None):
''' User profile. Show username, location, etc, as well as grades . ''' User profile. Show username, location, etc, as well as grades .
We need to allow the user to change some of these settings .''' We need to allow the user to change some of these settings .'''
if not request.user.is_authenticated():
return redirect('/')
if student_id == None: if student_id == None:
student = request.user student = request.user
...@@ -124,7 +117,7 @@ def render_section(request, section): ...@@ -124,7 +117,7 @@ def render_section(request, section):
''' TODO: Consolidate with index ''' TODO: Consolidate with index
''' '''
user = request.user user = request.user
if not settings.COURSEWARE_ENABLED or not user.is_authenticated(): if not settings.COURSEWARE_ENABLED:
return redirect('/') return redirect('/')
# try: # try:
...@@ -136,8 +129,11 @@ def render_section(request, section): ...@@ -136,8 +129,11 @@ def render_section(request, section):
module_ids = dom.xpath("//@id") module_ids = dom.xpath("//@id")
if user.is_authenticated():
module_object_preload = list(StudentModule.objects.filter(student=user, module_object_preload = list(StudentModule.objects.filter(student=user,
module_id__in=module_ids)) module_id__in=module_ids))
else:
module_object_preload = []
module=render_module(user, request, dom, module_object_preload) module=render_module(user, request, dom, module_object_preload)
...@@ -158,7 +154,7 @@ def index(request, course="6.002 Spring 2012", chapter="Using the System", secti ...@@ -158,7 +154,7 @@ def index(request, course="6.002 Spring 2012", chapter="Using the System", secti
''' Displays courseware accordion, and any associated content. ''' Displays courseware accordion, and any associated content.
''' '''
user = request.user user = request.user
if not settings.COURSEWARE_ENABLED or not user.is_authenticated(): if not settings.COURSEWARE_ENABLED:
return redirect('/') return redirect('/')
# Fixes URLs -- we don't get funny encoding characters from spaces # Fixes URLs -- we don't get funny encoding characters from spaces
...@@ -190,8 +186,11 @@ def index(request, course="6.002 Spring 2012", chapter="Using the System", secti ...@@ -190,8 +186,11 @@ def index(request, course="6.002 Spring 2012", chapter="Using the System", secti
module_ids = dom.xpath("//course[@name=$course]/chapter[@name=$chapter]//section[@name=$section]//@id", module_ids = dom.xpath("//course[@name=$course]/chapter[@name=$chapter]//section[@name=$section]//@id",
course=course, chapter=chapter, section=section) course=course, chapter=chapter, section=section)
if user.is_authenticated():
module_object_preload = list(StudentModule.objects.filter(student=user, module_object_preload = list(StudentModule.objects.filter(student=user,
module_id__in=module_ids)) module_id__in=module_ids))
else:
module_object_preload = []
module=render_module(user, request, module, module_object_preload) module=render_module(user, request, module, module_object_preload)
...@@ -206,3 +205,49 @@ def index(request, course="6.002 Spring 2012", chapter="Using the System", secti ...@@ -206,3 +205,49 @@ def index(request, course="6.002 Spring 2012", chapter="Using the System", secti
result = render_to_response('courseware.html', context) result = render_to_response('courseware.html', context)
return result return result
def modx_dispatch(request, module=None, dispatch=None, id=None):
''' Generic view for extensions. '''
# Grab the student information for the module from the database
if request.user.is_authenticated():
s = StudentModule.objects.filter(student=request.user,
module_id=id)
#s = StudentModule.get_with_caching(request.user, id)
if len(s) == 0 or s is None:
log.debug("Couldnt find module for user and id " + str(module) + " " + str(request.user) + " "+ str(id))
raise Http404
s = s[0]
oldgrade = s.grade
oldstate = s.state
else:
oldstate = "{}"
dispatch=dispatch.split('?')[0]
ajax_url = '/modx/'+module+'/'+id+'/'
# Grab the XML corresponding to the request from course.xml
xml = content_parser.module_xml(request.user, module, 'id', id)
# Create the module
instance=courseware.modules.get_module_class(module)(xml,
id,
ajax_url=ajax_url,
state=oldstate,
track_function = make_track_function(request),
render_function = None)
# Let the module handle the AJAX
ajax_return=instance.handle_ajax(dispatch, request.POST)
# Save the state back to the database
if request.user.is_authenticated():
s.state=instance.get_state()
if instance.get_score():
s.grade=instance.get_score()['score']
if s.grade != oldgrade or s.state != oldstate:
s.save()
# Return whatever the module wanted to return to the client/caller
return HttpResponse(ajax_return)
...@@ -9,7 +9,7 @@ from django.db.models import signals ...@@ -9,7 +9,7 @@ from django.db.models import signals
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from markdown import markdown from markdown import markdown
from settings import * from wiki_settings import *
from util.cache import cache from util.cache import cache
......
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import types from django.conf import settings as settings
from django.conf import settings
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
from django.core.context_processors import csrf from django.core.context_processors import csrf
from django.core.urlresolvers import get_callable
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from django.db.models import Q from django.db.models import Q
from django.http import Http404, HttpResponse, HttpResponseRedirect, HttpResponseServerError, HttpResponseForbidden, HttpResponseNotAllowed from django.http import HttpResponse, HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
from django.template import Context
from django.template import RequestContext, Context, loader
from django.utils import simplejson from django.utils import simplejson
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from mitxmako.shortcuts import render_to_response, render_to_string from mitxmako.shortcuts import render_to_response
from mako.lookup import TemplateLookup
from mako.template import Template
import mitxmako.middleware
from models import * # TODO: Clean up from models import Revision, Article, CreateArticleForm, RevisionFormWithTitle, RevisionForm
from settings import * import wiki_settings
def view(request, wiki_url): def view(request, wiki_url):
if not request.user.is_authenticated():
return redirect('/')
(article, path, err) = fetch_from_url(request, wiki_url) (article, path, err) = fetch_from_url(request, wiki_url)
if err: if err:
return err return err
...@@ -45,9 +31,6 @@ def view(request, wiki_url): ...@@ -45,9 +31,6 @@ def view(request, wiki_url):
return render_to_response('simplewiki_view.html', d) return render_to_response('simplewiki_view.html', d)
def view_revision(request, revision_number, wiki_url, revision=None): def view_revision(request, revision_number, wiki_url, revision=None):
if not request.user.is_authenticated():
return redirect('/')
(article, path, err) = fetch_from_url(request, wiki_url) (article, path, err) = fetch_from_url(request, wiki_url)
if err: if err:
return err return err
...@@ -76,8 +59,6 @@ def view_revision(request, revision_number, wiki_url, revision=None): ...@@ -76,8 +59,6 @@ def view_revision(request, revision_number, wiki_url, revision=None):
def root_redirect(request): def root_redirect(request):
if not request.user.is_authenticated():
return redirect('/')
try: try:
root = Article.get_root() root = Article.get_root()
except: except:
...@@ -87,8 +68,6 @@ def root_redirect(request): ...@@ -87,8 +68,6 @@ def root_redirect(request):
return HttpResponseRedirect(reverse('wiki_view', args=(root.get_url()))) return HttpResponseRedirect(reverse('wiki_view', args=(root.get_url())))
def create(request, wiki_url): def create(request, wiki_url):
if not request.user.is_authenticated():
return redirect('/')
url_path = get_url_path(wiki_url) url_path = get_url_path(wiki_url)
...@@ -161,9 +140,6 @@ def create(request, wiki_url): ...@@ -161,9 +140,6 @@ def create(request, wiki_url):
return render_to_response('simplewiki_edit.html', d) return render_to_response('simplewiki_edit.html', d)
def edit(request, wiki_url): def edit(request, wiki_url):
if not request.user.is_authenticated():
return redirect('/')
(article, path, err) = fetch_from_url(request, wiki_url) (article, path, err) = fetch_from_url(request, wiki_url)
if err: if err:
return err return err
...@@ -173,7 +149,7 @@ def edit(request, wiki_url): ...@@ -173,7 +149,7 @@ def edit(request, wiki_url):
if perm_err: if perm_err:
return perm_err return perm_err
if WIKI_ALLOW_TITLE_EDIT: if wiki_settings.WIKI_ALLOW_TITLE_EDIT:
EditForm = RevisionFormWithTitle EditForm = RevisionFormWithTitle
else: else:
EditForm = RevisionForm EditForm = RevisionForm
...@@ -195,7 +171,7 @@ def edit(request, wiki_url): ...@@ -195,7 +171,7 @@ def edit(request, wiki_url):
if not request.user.is_anonymous(): if not request.user.is_anonymous():
new_revision.revision_user = request.user new_revision.revision_user = request.user
new_revision.save() new_revision.save()
if WIKI_ALLOW_TITLE_EDIT: if wiki_settings.WIKI_ALLOW_TITLE_EDIT:
new_revision.article.title = f.cleaned_data['title'] new_revision.article.title = f.cleaned_data['title']
new_revision.article.save() new_revision.article.save()
return HttpResponseRedirect(reverse('wiki_view', args=(article.get_url(),))) return HttpResponseRedirect(reverse('wiki_view', args=(article.get_url(),)))
...@@ -215,9 +191,6 @@ def edit(request, wiki_url): ...@@ -215,9 +191,6 @@ def edit(request, wiki_url):
return render_to_response('simplewiki_edit.html', d) return render_to_response('simplewiki_edit.html', d)
def history(request, wiki_url, page=1): def history(request, wiki_url, page=1):
if not request.user.is_authenticated():
return redirect('/')
(article, path, err) = fetch_from_url(request, wiki_url) (article, path, err) = fetch_from_url(request, wiki_url)
if err: if err:
return err return err
...@@ -237,6 +210,9 @@ def history(request, wiki_url, page=1): ...@@ -237,6 +210,9 @@ def history(request, wiki_url, page=1):
history = Revision.objects.filter(article__exact = article).order_by('-counter').select_related('previous_revision__counter', 'revision_user', 'wiki_article') history = Revision.objects.filter(article__exact = article).order_by('-counter').select_related('previous_revision__counter', 'revision_user', 'wiki_article')
if request.method == 'POST': if request.method == 'POST':
if wiki_settings.WIKI_REQUIRE_LOGIN_EDIT and not request.user.is_authenticated():
return HttpResponseRedirect('/')
if request.POST.__contains__('revision'): #They selected a version, but they can be either deleting or changing the version if request.POST.__contains__('revision'): #They selected a version, but they can be either deleting or changing the version
perm_err = check_permissions(request, article, check_write=True, check_locked=True) perm_err = check_permissions(request, article, check_write=True, check_locked=True)
if perm_err: if perm_err:
...@@ -302,9 +278,6 @@ def history(request, wiki_url, page=1): ...@@ -302,9 +278,6 @@ def history(request, wiki_url, page=1):
def revision_feed(request, page=1): def revision_feed(request, page=1):
if not request.user.is_superuser:
return redirect('/')
page_size = 10 page_size = 10
try: try:
...@@ -332,8 +305,6 @@ def revision_feed(request, page=1): ...@@ -332,8 +305,6 @@ def revision_feed(request, page=1):
return render_to_response('simplewiki_revision_feed.html', d) return render_to_response('simplewiki_revision_feed.html', d)
def search_articles(request): def search_articles(request):
if not request.user.is_authenticated():
return redirect('/')
# blampe: We should check for the presence of other popular django search # blampe: We should check for the presence of other popular django search
# apps and use those if possible. Only fall back on this as a last resort. # apps and use those if possible. Only fall back on this as a last resort.
# Adding some context to results (eg where matches were) would also be nice. # Adding some context to results (eg where matches were) would also be nice.
...@@ -380,9 +351,6 @@ def search_articles(request): ...@@ -380,9 +351,6 @@ def search_articles(request):
def search_add_related(request, wiki_url): def search_add_related(request, wiki_url):
if not request.user.is_authenticated():
return redirect('/')
(article, path, err) = fetch_from_url(request, wiki_url) (article, path, err) = fetch_from_url(request, wiki_url)
if err: if err:
return err return err
...@@ -435,9 +403,6 @@ def add_related(request, wiki_url): ...@@ -435,9 +403,6 @@ def add_related(request, wiki_url):
return HttpResponseRedirect(reverse('wiki_view', args=(article.get_url(),))) return HttpResponseRedirect(reverse('wiki_view', args=(article.get_url(),)))
def remove_related(request, wiki_url, related_id): def remove_related(request, wiki_url, related_id):
if not request.user.is_authenticated():
return redirect('/')
(article, path, err) = fetch_from_url(request, wiki_url) (article, path, err) = fetch_from_url(request, wiki_url)
if err: if err:
return err return err
...@@ -457,8 +422,6 @@ def remove_related(request, wiki_url, related_id): ...@@ -457,8 +422,6 @@ def remove_related(request, wiki_url, related_id):
return HttpResponseRedirect(reverse('wiki_view', args=(article.get_url(),))) return HttpResponseRedirect(reverse('wiki_view', args=(article.get_url(),)))
def random_article(request): def random_article(request):
if not request.user.is_authenticated():
return redirect('/')
from random import randint from random import randint
num_arts = Article.objects.count() num_arts = Article.objects.count()
article = Article.objects.all()[randint(0, num_arts-1)] article = Article.objects.all()[randint(0, num_arts-1)]
...@@ -470,8 +433,6 @@ def encode_err(request, url): ...@@ -470,8 +433,6 @@ def encode_err(request, url):
return render_to_response('simplewiki_error.html', d) return render_to_response('simplewiki_error.html', d)
def not_found(request, wiki_url): def not_found(request, wiki_url):
if not request.user.is_authenticated():
return redirect('/')
"""Generate a NOT FOUND message for some URL""" """Generate a NOT FOUND message for some URL"""
d = {'wiki_err_notfound': True, d = {'wiki_err_notfound': True,
'wiki_url': wiki_url} 'wiki_url': wiki_url}
...@@ -543,17 +504,22 @@ def check_permissions(request, article, check_read=False, check_write=False, che ...@@ -543,17 +504,22 @@ def check_permissions(request, article, check_read=False, check_write=False, che
# LOGIN PROTECTION # # LOGIN PROTECTION #
#################### ####################
if WIKI_REQUIRE_LOGIN_VIEW: if wiki_settings.WIKI_REQUIRE_LOGIN_VIEW:
view = login_required(view) view = login_required(view)
history = login_required(history) history = login_required(history)
# search_related = login_required(search_related) search_articles = login_required(search_articles)
# wiki_encode_err = login_required(wiki_encode_err) root_redirect = login_required(root_redirect)
revision_feed = login_required(revision_feed)
if WIKI_REQUIRE_LOGIN_EDIT: random_article = login_required(random_article)
search_add_related = login_required(search_add_related)
not_found = login_required(not_found)
view_revision = login_required(view_revision)
if wiki_settings.WIKI_REQUIRE_LOGIN_EDIT:
create = login_required(create) create = login_required(create)
edit = login_required(edit) edit = login_required(edit)
add_related = login_required(add_related) add_related = login_required(add_related)
remove_related = login_required(remove_related) remove_related = login_required(remove_related)
if WIKI_CONTEXT_PREPROCESSORS: if wiki_settings.WIKI_CONTEXT_PREPROCESSORS:
settings.TEMPLATE_CONTEXT_PROCESSORS = settings.TEMPLATE_CONTEXT_PROCESSORS + WIKI_CONTEXT_PREPROCESSORS settings.TEMPLATE_CONTEXT_PROCESSORS += wiki_settings.WIKI_CONTEXT_PREPROCESSORS
...@@ -3,14 +3,21 @@ import os ...@@ -3,14 +3,21 @@ import os
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
from django.core.servers.basehttp import FileWrapper from django.core.servers.basehttp import FileWrapper
from django.db.models.fields.files import FieldFile from django.db.models.fields.files import FieldFile
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden, Http404 from django.http import HttpResponse, HttpResponseForbidden, Http404
from django.template import loader, Context from django.template import loader, Context
from settings import * # TODO: Clean up from models import ArticleAttachment, get_attachment_filepath
from models import Article, ArticleAttachment, get_attachment_filepath from views import check_permissions, fetch_from_url
from views import not_found, check_permissions, get_url_path, fetch_from_url
from wiki_settings import (
from simplewiki.settings import WIKI_ALLOW_ANON_ATTACHMENTS WIKI_ALLOW_ANON_ATTACHMENTS,
WIKI_ALLOW_ATTACHMENTS,
WIKI_ATTACHMENTS_MAX,
WIKI_ATTACHMENTS_ROOT,
WIKI_ATTACHMENTS_ALLOWED_EXTENSIONS,
WIKI_REQUIRE_LOGIN_VIEW,
WIKI_REQUIRE_LOGIN_EDIT,
)
def add_attachment(request, wiki_url): def add_attachment(request, wiki_url):
......
# Create your views here. from django.contrib.auth.decorators import login_required
import os from mitxmako.shortcuts import render_to_response
from django.conf import settings
from django.http import Http404
from django.shortcuts import redirect
from mitxmako.shortcuts import render_to_response, render_to_string
@login_required
def index(request, page=0): def index(request, page=0):
if not request.user.is_authenticated():
return redirect('/')
return render_to_response('staticbook.html',{'page':int(page)}) return render_to_response('staticbook.html',{'page':int(page)})
def index_shifted(request, page): def index_shifted(request, page):
......
...@@ -11,14 +11,13 @@ from django.contrib.auth import logout, authenticate, login ...@@ -11,14 +11,13 @@ from django.contrib.auth import logout, authenticate, login
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import PasswordResetForm from django.contrib.auth.forms import PasswordResetForm
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.core.context_processors import csrf from django.core.context_processors import csrf
from django.core.mail import send_mail from django.core.mail import send_mail
from django.core.validators import validate_email, validate_slug, ValidationError from django.core.validators import validate_email, validate_slug, ValidationError
from django.db import connection
from django.http import HttpResponse, Http404 from django.http import HttpResponse, Http404
from django.shortcuts import redirect from django.shortcuts import redirect
from mitxmako.shortcuts import render_to_response, render_to_string from mitxmako.shortcuts import render_to_response, render_to_string
from mako import exceptions
from django_future.csrf import ensure_csrf_cookie from django_future.csrf import ensure_csrf_cookie
...@@ -95,12 +94,11 @@ def logout_user(request): ...@@ -95,12 +94,11 @@ def logout_user(request):
logout(request) logout(request)
return redirect('/') return redirect('/')
@login_required
@ensure_csrf_cookie @ensure_csrf_cookie
def change_setting(request): def change_setting(request):
''' JSON call to change a profile setting: Right now, location and language ''' JSON call to change a profile setting: Right now, location and language
''' '''
if not request.user.is_authenticated():
return redirect('/')
up = UserProfile.objects.get(user=request.user) #request.user.profile_cache up = UserProfile.objects.get(user=request.user) #request.user.profile_cache
if 'location' in request.POST: if 'location' in request.POST:
up.location=request.POST['location'] up.location=request.POST['location']
......
...@@ -181,8 +181,8 @@ CELERY_ALWAYS_EAGER = True ...@@ -181,8 +181,8 @@ CELERY_ALWAYS_EAGER = True
djcelery.setup_loader() djcelery.setup_loader()
################################# SIMPLEWIKI ################################### ################################# SIMPLEWIKI ###################################
WIKI_REQUIRE_LOGIN_EDIT = True SIMPLE_WIKI_REQUIRE_LOGIN_EDIT = True
WIKI_REQUIRE_LOGIN_VIEW = True SIMPLE_WIKI_REQUIRE_LOGIN_VIEW = False
################################# Middleware ################################### ################################# Middleware ###################################
# List of finder classes that know how to find static files in # List of finder classes that know how to find static files in
......
...@@ -60,7 +60,4 @@ def send_feedback(request): ...@@ -60,7 +60,4 @@ def send_feedback(request):
def info(request): def info(request):
''' Info page (link from main header) ''' ''' Info page (link from main header) '''
if not request.user.is_authenticated():
return redirect('/')
return render_to_response("info.html", {}) return render_to_response("info.html", {})
...@@ -45,8 +45,8 @@ DEFAULT_FEEDBACK_EMAIL = 'feedback@mitx.mit.edu' ...@@ -45,8 +45,8 @@ DEFAULT_FEEDBACK_EMAIL = 'feedback@mitx.mit.edu'
GENERATE_RANDOM_USER_CREDENTIALS = False GENERATE_RANDOM_USER_CREDENTIALS = False
WIKI_REQUIRE_LOGIN_EDIT = True SIMPLE_WIKI_REQUIRE_LOGIN_EDIT = True
WIKI_REQUIRE_LOGIN_VIEW = True SIMPLE_WIKI_REQUIRE_LOGIN_VIEW = False
PERFSTATS = False PERFSTATS = False
......
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
<section> <section>
<h1>Circuits &amp; Electronics</h1> <h1>Circuits &amp; Electronics</h1>
<h2>6.002x</h2> <h2>6.002x</h2>
<a class="enroll" rel="leanModal" href="#enroll"><noscript>In order to</noscript> Enroll in 6.002x Circuits <span>&amp;</span> Electronics <noscript>you need to have javascript enabled</noscript></a> <a class="enroll" rel="leanModal" href="/info">View 6.002x Circuits <span>&amp;</span> Electronics as a guest</a>
</section> </section>
<p>6.002x (Circuits and Electronics) is an experimental on-line adaptation of MIT&rsquo;s first undergraduate analog design course: 6.002. This course is running, free of charge, for students worldwide from March 5, 2012 through June 8, 2012.</p> <p>6.002x (Circuits and Electronics) is an experimental on-line adaptation of MIT&rsquo;s first undergraduate analog design course: 6.002. This course is running, free of charge, for students worldwide from March 5, 2012 through June 8, 2012.</p>
</section> </section>
...@@ -51,7 +51,7 @@ ...@@ -51,7 +51,7 @@
</section> </section>
<section class="cta"> <section class="cta">
<a class="enroll" rel="leanModal" href="#enroll"><noscript>In order to</noscript> Enroll in 6.002x Circuits &amp; Electronics <noscript>you need to have javascript enabled</noscript></a> <a class="enroll" rel="leanModal" href="/info">View 6.002x Circuits &amp; Electronics as a guest</a>
</section> </section>
</section> </section>
...@@ -79,38 +79,11 @@ ...@@ -79,38 +79,11 @@
</section> </section>
</section> </section>
<div id="enroll" class="leanModal_box" name="enroll"><%include file="create_account.html" /></div>
<script> <script>
$(function() { $(function() {
// TODO: Clean up as per http://stackoverflow.com/questions/169506/obtain-form-input-fields-using-jquery // TODO: Clean up as per http://stackoverflow.com/questions/169506/obtain-form-input-fields-using-jquery
/* Handles when the user hits 'enroll'. Grabs form data. Does AJAX.
Either shows error, or shows success. */
$('form#enroll_form').submit(function(e) {
e.preventDefault();
var submit_data={};
$.each($("[id^=ca_]"), function(index,value){
submit_data[value.name]=value.value;
});
$.each($("[id^=cb_]"), function(index,value){
submit_data[value.name]=value.checked;
});
postJSON('/create_account',
submit_data,
function(json) {
if(json.success) {
$('#enroll').html(json.value);
} else {
$('#enroll_error').html(json.value).stop().css("background-color", "#933").animate({ backgroundColor: "#333"}, 2000);
}
}
);
});
/* Activate stupid spinner drop-downs in enrollment form */ /* Activate stupid spinner drop-downs in enrollment form */
var spinner_array=$("[id^=spinner_]"); var spinner_array=$("[id^=spinner_]");
spinner_array.each(function(i) { spinner_array.each(function(i) {
......
...@@ -23,11 +23,20 @@ $(document).ready(function(){ ...@@ -23,11 +23,20 @@ $(document).ready(function(){
<section class="main-content"> <section class="main-content">
<div class="info-wrapper"> <div class="info-wrapper">
% if user.is_authenticated():
<section class="updates"> <section class="updates">
<%include file="updates.html" /> <%include file="updates.html" />
</section> </section>
<section class="handouts"> <section class="handouts">
<%include file="handouts.html" /> <%include file="handouts.html" />
</section> </section>
% else:
<section class="updates">
<%include file="guest_updates.html" />
</section>
<section class="handouts">
<%include file="guest_handouts.html" />
</section>
% endif
</div> </div>
</section> </section>
...@@ -85,7 +85,9 @@ ...@@ -85,7 +85,9 @@
</div> </div>
</li> </li>
<li><a href="/s/help.html">Help</a></li> <li><a href="/s/help.html">Help</a></li>
% if user.is_authenticated():
<li><a href="/logout">Log out</a></li> <li><a href="/logout">Log out</a></li>
% endif
</ul> </ul>
</nav> </nav>
</footer> </footer>
......
...@@ -10,10 +10,14 @@ ...@@ -10,10 +10,14 @@
<ul class="coursenav"> <ul class="coursenav">
<li class="courseware"><a href="/courseware">Courseware</a></li> <li class="courseware"><a href="/courseware">Courseware</a></li>
<li class="info"><a href="/info">Course Info</a></li> <li class="info"><a href="/info">Course Info</a></li>
% if user.is_authenticated():
<li class="book"><a href="/book">Textbook</a></li> <li class="book"><a href="/book">Textbook</a></li>
<li class="discussion"><a href="/discussion/questions">Discussion</a></li> <li class="discussion"><a href="/discussion/questions">Discussion</a></li>
% endif
<li class="wiki"><a href="/wiki/view">Wiki</a></li> <li class="wiki"><a href="/wiki/view">Wiki</a></li>
% if user.is_authenticated():
<li class="profile"><a href="/profile">Profile</a></li> <li class="profile"><a href="/profile">Profile</a></li>
% endif
</ul> </ul>
</nav> </nav>
</header> </header>
......
function ${ id }_load() { function ${ id }_content_updated() {
$('#main_${ id }').load('${ ajax_url }problem_get?id=${ id }',
function() {
MathJax.Hub.Queue(["Typeset",MathJax.Hub]); MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
update_schematics(); update_schematics();
$('#check_${ id }').click(function() { $('#check_${ id }').unbind('click').click(function() {
$("input.schematic").each(function(index,element){ element.schematic.update_value(); }); $("input.schematic").each(function(index,element){ element.schematic.update_value(); });
var submit_data={}; var submit_data={};
$.each($("[id^=input_${ id }_]"), function(index,value){ $.each($("[id^=input_${ id }_]"), function(index,value){
...@@ -16,29 +14,30 @@ function ${ id }_load() { ...@@ -16,29 +14,30 @@ function ${ id }_load() {
switch(json.success) { switch(json.success) {
case 'incorrect': // Worked, but answer not case 'incorrect': // Worked, but answer not
case 'correct': case 'correct':
${ id }_load(); $('#main_${ id }').html(json.contents);
//alert("!!"+json.success); ${ id }_content_updated();
break; break;
default: default:
alert(json.success); alert(json.success);
} }}
}); );
log_event('problem_check', submit_data); log_event('problem_check', submit_data);
}); });
$('#reset_${ id }').click(function() { $('#reset_${ id }').unbind('click').click(function() {
var submit_data={}; var submit_data={};
$.each($("[id^=input_${ id }_]"), function(index,value){ $.each($("[id^=input_${ id }_]"), function(index,value){
submit_data[value.id]=value.value; submit_data[value.id]=value.value;
}); });
postJSON('/modx/problem/${ id }/problem_reset', {'id':'${ id }'}, function(json) { postJSON('/modx/problem/${ id }/problem_reset', {'id':'${ id }'}, function(html_as_json) {
${ id }_load(); $('#main_${ id }').html(html_as_json);
${ id }_content_updated();
}); });
log_event('problem_reset', submit_data); log_event('problem_reset', submit_data);
}); });
$('#show_${ id }').click(function() { $('#show_${ id }').unbind('click').click(function() {
postJSON('/modx/problem/${ id }/problem_show', {}, function(data) { postJSON('/modx/problem/${ id }/problem_show', {}, function(data) {
for (var key in data) { for (var key in data) {
$("#answer_"+key).text(data[key]); $("#answer_"+key).text(data[key]);
...@@ -46,23 +45,27 @@ function ${ id }_load() { ...@@ -46,23 +45,27 @@ function ${ id }_load() {
}); });
log_event('problem_show', {'problem':'${ id }'}); log_event('problem_show', {'problem':'${ id }'});
}); });
$('#save_${ id }').click(function() { $('#save_${ id }').unbind('click').click(function() {
$("input.schematic").each(function(index,element){ element.schematic.update_value(); }); $("input.schematic").each(function(index,element){ element.schematic.update_value(); });
var submit_data={}; var submit_data={};
$.each($("[id^=input_${ id }_]"), function(index,value){ $.each($("[id^=input_${ id }_]"), function(index,value) {
submit_data[value.id]=value.value;}); submit_data[value.id]=value.value;
});
postJSON('/modx/problem/${ id }/problem_save', postJSON('/modx/problem/${ id }/problem_save',
submit_data, function(data){ submit_data,
function(data) {
if(data.success) { if(data.success) {
alert('Saved'); alert('Saved');
}} }});
);
log_event('problem_save', submit_data); log_event('problem_save', submit_data);
}); });
} }
);}
function ${ id }_load() {
$('#main_${ id }').load('${ ajax_url }problem_get?id=${ id }', ${ id }_content_updated);
}
$(function() { $(function() {
${ id }_load(); ${ id }_load();
......
...@@ -23,8 +23,8 @@ urlpatterns = ('', ...@@ -23,8 +23,8 @@ urlpatterns = ('',
url(r'^login$', 'student.views.login_user'), url(r'^login$', 'student.views.login_user'),
url(r'^login/(?P<error>[^/]*)$', 'student.views.login_user'), url(r'^login/(?P<error>[^/]*)$', 'student.views.login_user'),
url(r'^logout$', 'student.views.logout_user'), url(r'^logout$', 'student.views.logout_user'),
url(r'^create_account$', 'student.views.create_account'), # url(r'^create_account$', 'student.views.create_account'),
url(r'^activate/(?P<key>[^/]*)$', 'student.views.activate_account'), # url(r'^activate/(?P<key>[^/]*)$', 'student.views.activate_account'),
# url(r'^reactivate/(?P<key>[^/]*)$', 'student.views.reactivation_email'), # url(r'^reactivate/(?P<key>[^/]*)$', 'student.views.reactivation_email'),
url(r'^password_reset/$', 'student.views.password_reset'), url(r'^password_reset/$', 'student.views.password_reset'),
## Obsolete Django views for password resets ## Obsolete Django views for password resets
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment