def navBarDown(request, navbar, node, section): """ Swap the sort_rank of the specified NavBarEntry and the NavBarEntry immediately after it in the list of NavBarEntrys associated with this tree node, so that this NavBarEntry appears to move down one unit on the page Fail silently if this is not possible """ if not UserBit.UserHasPerms(request.user, navbar.path, GetNode(EDIT_VERB_STRING)): raise PermissionDenied, "You don't have permisssion to do that!" navbarList = NavBarEntry.objects.filter( path=navbar.path).order_by('sort_rank') if not navbar.indent: navbarList = navbarList.filter(indent=False) last_n = None for n in navbarList: if last_n != None and navbar == last_n: temp_sort_rank = n.sort_rank n.sort_rank = last_n.sort_rank last_n.sort_rank = temp_sort_rank n.save() last_n.save() last_n = n
def classTemplateEditor(request, program, session): """ Generate and display a listing of all QSD pages in the Class template within the specified program (QSD pages that are created automatically when a new class is created) """ qsd_pages = [] try: template_node = GetNodeOrNoBits( 'Q/Programs/' + program + '/' + session + '/Template', request.user) except DataTree.NoSuchNodeException: raise Http404 for qsd in template_node.quasistaticdata_set.all(): qsd_pages.append({ 'edit_url': qsd.name + ".edit.html", 'view_url': qsd.name + ".html", 'page': qsd }) have_create = UserBit.UserHasPerms(request.user, template_node, GetNode('V/Administer/Edit')) return render_to_response('display/qsd_listing.html', request, program, { 'qsd_pages': qsd_pages, 'have_create': have_create })
def render(self, context): try: user = self.user_variable.resolve(context) except template.VariableDoesNotExist: user = None try: anchor = template.Variable(self.input_anchor) anchor = anchor.resolve(context) except: anchor = GetNode(self.input_anchor) try: qsd = template.Variable(self.qsd_name) qsd = qsd.resolve(context) except: qsd = self.qsd_name edit_bits = UserBit.UserHasPerms(user, anchor, DataTree.get_by_uri('V/Administer/Edit')) qsd_obj = QuasiStaticData.objects.get_by_path__name(anchor, qsd) if qsd_obj == None: new_qsd = QuasiStaticData() new_qsd.path = anchor new_qsd.name = qsd new_qsd.title = qsd new_qsd.content = self.nodelist.render(context) if getattr(user, 'id', False): new_qsd.author = user new_qsd.save() qsd_obj = new_qsd return render_to_response("inclusion/qsd/render_qsd_inline.html", {'qsdrec': qsd_obj, 'edit_bits': edit_bits}, context_instance=context).content
def accesshandler(req): os.environ.update(req.subprocess_env) uri = req.subprocess_env['REQUEST_URI'] # check for PythonOptions _str_to_bool = lambda s: s.lower() in ('1', 'true', 'on', 'yes') options = req.get_options() permission_verb_name = options.get('ESPPermissionName', 'V/Flags/Public') settings_module = options.get('DJANGO_SETTINGS_MODULE', None) if settings_module: os.environ['DJANGO_SETTINGS_MODULE'] = settings_module from esp.users.models import UserBit from esp.datatree.models import DataTree, GetNode, QTree, get_lowest_parent, StringToPerm, PermToString request = AccessHandler()(req) if request.user.is_authenticated(): qsc = get_lowest_parent('Q/Static/' + uri.strip('/')) verb = get_lowest_parent(permission_verb_name) if UserBit.UserHasPerms(request.user, qsc, verb): return apache.OK return apache.HTTP_UNAUTHORIZED
def ajax_qsd(request): """ Ajax function for in-line QSD editing. """ from django.utils import simplejson from esp.lib.templatetags.markdown import markdown EDIT_VERB = 'V/Administer/Edit/QSD' result = {} post_dict = request.POST.copy() if (request.user.id is None): return HttpResponse( content= 'Oops! Your session expired!\nPlease open another window, log in, and try again.\nYour changes will not be lost if you keep this page open.', status=500) if post_dict['cmd'] == "update": qsdold = QuasiStaticData.objects.get(id=post_dict['id']) if not UserBit.UserHasPerms(request.user, qsdold.path, EDIT_VERB): return HttpResponse( content='Sorry, you do not have permission to edit this page.', status=500) qsd = qsdold.copy() qsd.content = post_dict['data'] qsd.load_cur_user_time(request, ) # Local change here, to enable QSD editing. qsd.save() result['status'] = 1 result['content'] = markdown(qsd.content) result['id'] = qsd.id if post_dict['cmd'] == "create": qsd_path = DataTree.objects.get(id=post_dict['anchor']) if not UserBit.UserHasPerms(request.user, qsd_path, EDIT_VERB): return HttpResponse( content="Sorry, you do not have permission to edit this page.", status=500) qsd, created = QuasiStaticData.objects.get_or_create( name=post_dict['name'], path=qsd_path, defaults={'author': request.user}) qsd.content = post_dict['data'] qsd.author = request.user qsd.save() result['status'] = 1 result['content'] = markdown(qsd.content) result['id'] = qsd.id return HttpResponse(simplejson.dumps(result))
def authenhandler(req, **kwargs): """ Authentication handler that checks against Django's auth database. """ # mod_python fakes the environ, and thus doesn't process SetEnv. This fixes # that so that the following import works os.environ.update(req.subprocess_env) uri = req.subprocess_env['REQUEST_URI'] # check for PythonOptions _str_to_bool = lambda s: s.lower() in ('1', 'true', 'on', 'yes') options = req.get_options() permission_verb_name = options.get('ESPPermissionName', 'V/Flags/Public') settings_module = options.get('DJANGO_SETTINGS_MODULE', None) if settings_module: os.environ['DJANGO_SETTINGS_MODULE'] = settings_module from esp.users.models import UserBit from esp.datatree.models import DataTree, GetNode, QTree, get_lowest_parent, StringToPerm, PermToString from django.contrib.auth.models import User from django import db db.reset_queries() # check that the username is valid kwargs = {'username': req.user, 'is_active': True} try: try: user = User.objects.get(**kwargs) except User.DoesNotExist: return apache.HTTP_UNAUTHORIZED # check the password and any permission given if user.check_password(req.get_basic_auth_pw()): if user.is_authenticated(): qsc = get_lowest_parent('Q/Static/' + uri.strip('/')) verb = get_lowest_parent(permission_verb_name) if UserBit.UserHasPerms(user, qsc, verb): return apache.OK else: return apache.HTTP_UNAUTHORIZED else: return apache.HTTP_UNAUTHORIZED finally: db.connection.close()
def _checkDeadline_helper(method, extension, moduleObj, request, tl, *args, **kwargs): from esp.users.models import UserBit from esp.datatree.models import DataTree, GetNode, QTree, get_lowest_parent, StringToPerm, PermToString if tl != 'learn' and tl != 'teach': return (True, None) response = None canView = False if not_logged_in(request): response = HttpResponseRedirect('%s?%s=%s' % (LOGIN_URL, REDIRECT_FIELD_NAME, quote(request.get_full_path()))) else: canView = request.user.updateOnsite(request) if not canView: canView = UserBit.UserHasPerms(request.user, request.program.anchor_id, GetNode('V/Deadline/Registration/'+{'learn':'Student', 'teach':'Teacher'}[tl]+extension)) return (canView, response)
def programTemplateEditor(request): """ Generate and display a listing of all QSD pages in the Programs template (QSD pages that are created automatically when a new program is created) """ qsd_pages = [] template_node = GetNode('Q/Programs/Template') for qsd in template_node.quasistaticdata_set.all(): qsd_pages.append({ 'edit_url': qsd.name + ".edit.html", 'view_url': qsd.name + ".html", 'page': qsd }) have_create = UserBit.UserHasPerms(request.user, template_node, GetNode('V/Administer/Edit')) return render_to_response('display/qsd_listing.html', request, GetNode('Q/Web'), { 'qsd_pages': qsd_pages, 'have_create': have_create })
def deadline_met(self, extension=''): from esp.users.models import UserBit from esp.datatree.models import GetNode, DataTree if not get_current_request().user or not self.program: raise ESPError(False), "There is no user or program object!" if self.module.module_type != 'learn' and self.module.module_type != 'teach': return True canView = get_current_request().user.isOnsite(self.program) if not canView: test_node = GetNode('V/Deadline/Registration/' + { 'learn': 'Student', 'teach': 'Teacher' }[self.module.module_type] + extension) canView = UserBit.UserHasPerms(get_current_request().user, self.program.anchor_id, test_node) return canView
def _checkGrade(moduleObj, request, tl, *args, **kwargs): errorpage = 'errors/program/wronggrade.html' from esp.datatree.models import DataTree, GetNode, QTree, get_lowest_parent, StringToPerm, PermToString from esp.users.models import UserBit verb_override = GetNode('V/Flags/Registration/GradeOverride') # if there's grade override we can just skip everything if UserBit.UserHasPerms(user = request.user, qsc = moduleObj.program.anchor_id, verb = verb_override): return method(moduleObj, request, tl, *args, **kwargs) # now we have to use the grade.. # get the last grade... cur_grade = request.user.getGrade(moduleObj.program) if cur_grade != 0 and (cur_grade < moduleObj.program.grade_min or \ cur_grade > moduleObj.program.grade_max): return render_to_response(errorpage, request, (moduleObj.program, tl), {}) return method(moduleObj, request, tl, *args, **kwargs)
def qsdmedia(request, branch, section, url_name, url_verb, base_url): """ Return a redirect to a media file """ filename = url_name + '.' + url_verb if filename[:6] == 'learn:' or filename[:6] == 'teach:': filename = filename[6:] try: media_rec = Media.objects.get(anchor=branch, friendly_name=filename) except Media.DoesNotExist: raise Http404 except MultipleObjectsReturned: # If there exist multiple Media entries, we want the first one media_rec = Media.objects.filter(anchor=branch, friendly_name=filename).latest('id') # aseering 8-7-2006: Add permissions enforcement; Only show the page if the current user has V/Flags/Public on this node have_view = UserBit.UserHasPerms(request.user, media_rec.anchor, GetNode('V/Flags/Public')) if have_view: return HttpResponseRedirect(media_rec.target_file.url) else: raise Http404
def navBarNew(request, navbar, node, section): """ Create a new NavBarEntry. Put it at the bottom of the current sort_rank. """ child_node = request.POST.get('child_node', '') if node == '': raise ESPError(False), "Please specify a child node." try: child_node = DataTree.objects.get(id=child_node) except DataTree.DoesNotExist: raise ESPError(False), "Invalid child node specified." if not UserBit.UserHasPerms(request.user, node, GetNode(EDIT_VERB_STRING)): raise PermissionDenied, "You don't have permisssion to do that!" try: max_sort_rank = NavBarEntry.objects.filter( path=node).order_by('-sort_rank')[0].sort_rank except IndexError: max_sort_rank = -100 new_sort_rank = max_sort_rank + 100 try: url = request.POST['url'] entry = NavBarEntry() entry.path = child_node entry.sort_rank = new_sort_rank entry.link = url entry.text = request.POST['text'] entry.indent = request.POST['indent'] entry.section = section entry.save() except Exception: raise
def ajax_mover(request, *args, **kwargs): if not request.GET.has_key('ajax_movepage') or \ not request.GET.has_key('seq'): return method(request, *args, **kwargs) START = 'nav_entry__' entries = request.GET['seq'].strip(',').split(',') try: entries = [x[len(START):] for x in entries] except: return method(request, *args, **kwargs) # using some good magic we get a list of tree_node common # ancestors tree_nodes = DataTree.get_only_parents( DataTree.objects.filter(navbar__in=entries)) edit_verb = GetNode(EDIT_PERM) for node in tree_nodes: if not UserBit.UserHasPerms(request.user, node, edit_verb): return method(request, *args, **kwargs) # now we've properly assessed the person knows what # they're doing. We actually do the stuff we wanted. rank = 0 for entry in entries: try: navbar = NavBarEntry.objects.get(pk=entry) navbar.sort_rank = rank navbar.save() rank += DEFAULT_SPACING except: pass return HttpResponse('Success')
def handler(environ, start_response): if environ['REQUEST_URI'][:11] == '/code/login': def unauthorized(): start_response( '401 Authorization Required', [ ('WWW-Authenticate', 'Basic realm="ESP Project"'), ('Content-Type', 'text/html') ] ) return '<html><head><title>401 Authorization Required</title></head><body><h1>401 Authorization Required</h1></body></html>' # Decode the input try: # Require basic authentication method, auth = environ['HTTP_AUTHORIZATION'].split(' ', 1) if method.lower() != 'basic': return unauthorized() username, password = auth.strip().decode('base64').split(':') except: #(KeyError, ValueError, base64.binascii.Error) return unauthorized() # Check that the user exists try: from django.contrib.auth.models import User from esp.datatree.models import get_lowest_parent from esp.users.models import UserBit user = User.objects.get(username=username, is_active=True) except User.DoesNotExist: return unauthorized() # Check the password and any permission given if not ( user.check_password(password) and user.is_authenticated() ): return unauthorized() qsc = get_lowest_parent('Q/Static/' + environ['REQUEST_URI'].strip('/')) verb = get_lowest_parent('V/Flags/Public') if not UserBit.UserHasPerms(user, qsc, verb): return unauthorized() # By now we've verified the user's login and permissions environ['REMOTE_USER'] = username # Eventually pass all requests to Trac from trac.web.main import dispatch_request return dispatch_request(environ, start_response)
def qsd(request, branch, name, section, action): READ_VERB = 'V/Flags/Public' EDIT_VERB = 'V/Administer/Edit/QSD' if action == 'read': base_url = request.path[:-5] else: base_url = request.path[:(-len(action) - 6)] # Detect edit authorizations have_read = True if not have_read and action == 'read': raise Http403, "You do not have permission to access this page." # Fetch the QSD object try: qsd_rec = QuasiStaticData.objects.get_by_path__name(branch, name) if qsd_rec == None: raise QuasiStaticData.DoesNotExist if qsd_rec.disabled: raise QuasiStaticData.DoesNotExist except QuasiStaticData.DoesNotExist: have_edit = UserBit.UserHasPerms(request.user, branch, EDIT_VERB) if have_edit: if action in ( 'edit', 'create', ): qsd_rec = QuasiStaticData() qsd_rec.path = branch qsd_rec.name = name qsd_rec.nav_category = NavBarCategory.default() qsd_rec.title = 'New Page' qsd_rec.content = 'Please insert your text here' qsd_rec.create_date = datetime.now() qsd_rec.keywords = '' qsd_rec.description = '' action = 'edit' if (action == 'read'): edit_link = base_url + '.edit.html' return render_to_response('qsd/nopage_edit.html', request, (branch, section), {'edit_link': edit_link}, use_request_context=False) else: if action == 'read': raise Http404, 'This page does not exist.' else: raise Http403, 'Sorry, you can not modify <tt>%s</tt>.' % request.path if action == 'create': action = 'edit' # Detect the standard read verb if action == 'read': if not have_read: raise Http403, 'You do not have permission to read this page.' # Render response response = render_to_response( 'qsd/qsd.html', request, (branch, section), { 'title': qsd_rec.title, 'nav_category': qsd_rec.nav_category, 'content': qsd_rec.html(), 'qsdrec': qsd_rec, 'have_edit': True, ## Edit-ness is determined client-side these days 'edit_url': base_url + ".edit.html" }, use_request_context=False) # patch_vary_headers(response, ['Cookie']) # if have_edit: # add_never_cache_headers(response) # patch_cache_control(response, no_cache=True, no_store=True) # else: patch_cache_control(response, max_age=3600, public=True) return response # Detect POST if request.POST.has_key('post_edit'): have_edit = UserBit.UserHasPerms(request.user, branch, EDIT_VERB) if not have_edit: raise Http403, "Sorry, you do not have permission to edit this page." # Arguably, this should retrieve the DB object, use the .copy() # method, and then update it. Doing it this way saves a DB call # (and requires me to make fewer changes). qsd_rec_new = QuasiStaticData() qsd_rec_new.path = branch qsd_rec_new.name = name qsd_rec_new.author = request.user qsd_rec_new.nav_category = NavBarCategory.objects.get( id=request.POST['nav_category']) qsd_rec_new.content = request.POST['content'] qsd_rec_new.title = request.POST['title'] qsd_rec_new.description = request.POST['description'] qsd_rec_new.keywords = request.POST['keywords'] qsd_rec_new.save() # We should also purge the cache purge_page(qsd_rec_new.url()) qsd_rec = qsd_rec_new # If any files were uploaded, save them for name, file in request.FILES.iteritems(): m = Media() # Strip "media/" from FILE, and strip the file name; just return the path path = dirname(name[9:]) if path == '': m.anchor = qsd_rec.path else: m.anchor = GetNode('Q/' + dirname(name)) # Do we want a better/manual mechanism for setting friendly_name? m.friendly_name = basename(name) m.format = '' local_filename = name if name[:9] == 'qsdmedia/': local_filename = name[9:] m.handle_file(file, local_filename) m.save() # Detect the edit verb if action == 'edit': have_edit = UserBit.UserHasPerms(request.user, branch, EDIT_VERB) # Enforce authorizations (FIXME: SHOW A REAL ERROR!) if not have_edit: raise ESPError( False), "You don't have permission to edit this page." m = ESPMarkdown(qsd_rec.content, media={}) m.toString() # assert False, m.BrokenLinks() # Render an edit form return render_to_response( 'qsd/qsd_edit.html', request, (branch, section), { 'title': qsd_rec.title, 'content': qsd_rec.content, 'keywords': qsd_rec.keywords, 'description': qsd_rec.description, 'nav_category': qsd_rec.nav_category, 'nav_categories': NavBarCategory.objects.all(), 'qsdrec': qsd_rec, 'qsd': True, 'missing_files': m.BrokenLinks(), 'target_url': base_url.split("/")[-1] + ".edit.html", 'return_to_view': base_url.split("/")[-1] + ".html" }, use_request_context=False) # Operation Complete! raise Http404('Unexpected QSD operation')
def navBarDelete(request, navbar, node, section): if not UserBit.UserHasPerms(request.user, navbar.path or GetNode('Q'), GetNode(EDIT_VERB_STRING)): raise PermissionDenied, "You don't have permission to do that!" navbar.delete()
def ajax_schedule(self, request, tl, one, two, module, extra, prog): import simplejson as json from django.template.loader import render_to_string context = self.prepare({}) context['prog'] = self.program context['one'] = one context['two'] = two context['reg_open'] = bool( UserBit.UserHasPerms( request.user, prog.anchor_id, GetNode('V/Deadline/Registration/' + { 'learn': 'Student', 'teach': 'Teacher' }[tl] + "/Classes"))) schedule_str = render_to_string('users/student_schedule_inline.html', context) script_str = render_to_string('users/student_schedule_inline.js', context) json_data = { 'student_schedule_html': schedule_str, 'script': script_str } # Look at the 'extra' data and act appropriately: # - List, query set, or comma-separated ID list of class sections: # Add the buttons for those class sections to the returned data. # - String 'all': # Add the buttons for all of the student's class sections to the returned data # - Anything else: # Don't do anything. # Rewrite registration button if a particular section was named. (It will be in extra). sec_ids = [] if extra == 'all': sec_ids = user_sections.values_list('id', flat=True) elif isinstance(extra, list) or isinstance(extra, QuerySet): sec_ids = list(extra) else: try: sec_ids = [int(x) for x in extra.split(',')] except: pass for sec_id in sec_ids: try: section = ClassSection.objects.get(id=sec_id) cls = section.parent_class button_context = {'sec': section, 'cls': cls} if section in request.user.getEnrolledSections(self.program): button_context['label'] = 'Registered!' button_context['disabled'] = True addbutton_str1 = render_to_string( self.baseDir() + 'addbutton_fillslot.html', button_context) addbutton_str2 = render_to_string( self.baseDir() + 'addbutton_catalog.html', button_context) json_data['addbutton_fillslot_sec%d_html' % sec_id] = addbutton_str1 json_data['addbutton_catalog_sec%d_html' % sec_id] = addbutton_str2 except Exception, inst: raise AjaxError( 'Encountered an error retrieving updated buttons: %s' % inst)
def can_edit(self, user): return UserBit.UserHasPerms(user, self.path, GetNode('V/Administer/Edit/QSD'))
def _checkUser(request, *args, **kwargs): if not UserBit.UserHasPerms(qsc = branch, verb = verb, user = request.user): raise ESPError(log), error_msg return func(request, *args, **kwargs)
def render_qsd(qsd, user=None): edit_bits = False if user: edit_bits = UserBit.UserHasPerms(user, qsd.path, DataTree.get_by_uri('V/Administer/Edit')) return {'qsdrec': qsd, 'edit_bits': edit_bits}
def survey_view(request, tl, program, instance): try: prog = Program.by_prog_inst(program, instance) except Program.DoesNotExist: raise Http404 user = ESPUser(request.user) if (tl == 'teach' and not user.isTeacher()) or (tl == 'learn' and not user.isStudent()): raise ESPError( False ), 'You need to be a program participant (i.e. student or teacher, not parent or educator) to participate in this survey. Please contact the directors directly if you have additional feedback.' if request.GET.has_key('done'): return render_to_response('survey/completed_survey.html', request, prog.anchor, {'prog': prog}) if tl == 'learn': sv = GetNode('V/Flags/Survey/Filed') else: sv = GetNode('V/Flags/TeacherSurvey/Filed') if UserBit.UserHasPerms(request.user, prog.anchor, sv): raise ESPError( False ), "You've already filled out the survey. Thanks for responding!" surveys = prog.getSurveys().filter(category=tl).select_related() if request.REQUEST.has_key('survey_id'): try: s_id = int(request.REQUEST['survey_id']) surveys = surveys.filter( id=s_id ) # We want to filter, not get: ID could point to a survey that doesn't exist for this program, or at all except ValueError: pass if len(surveys) < 1: raise ESPError(False), "Sorry, no such survey exists for this program!" if len(surveys) > 1: return render_to_response( 'survey/choose_survey.html', request, prog.anchor, { 'surveys': surveys, 'error': request.POST } ) # if request.POST, then we shouldn't have more than one survey any more... survey = surveys[0] if request.POST: response = SurveyResponse() response.survey = survey response.save() ub = UserBit(user=request.user, verb=sv, qsc=prog.anchor) ub.save() response.set_answers(request.POST, save=True) return HttpResponseRedirect(request.path + "?done") else: questions = survey.questions.filter(anchor=prog.anchor).order_by('seq') perclass_questions = survey.questions.filter( anchor__name="Classes", anchor__parent=prog.anchor) classes = sections = timeslots = [] if tl == 'learn': classes = user.getEnrolledClasses(prog, request) timeslots = prog.getTimeSlots().order_by('start') for ts in timeslots: # The order by string really means "title" ts.classsections = prog.sections().filter( meeting_times=ts).exclude( meeting_times__start__lt=ts.start).order_by( 'parent_class__anchor__friendly_name').distinct() for sec in ts.classsections: if user in sec.students(): sec.selected = True elif tl == 'teach': classes = user.getTaughtClasses(prog) sections = user.getTaughtSections(prog).order_by( 'parent_class__anchor__friendly_name') context = { 'survey': survey, 'questions': questions, 'perclass_questions': perclass_questions, 'program': prog, 'classes': classes, 'sections': sections, 'timeslots': timeslots, } return render_to_response('survey/survey.html', request, prog.anchor, context)
# This only works for people who add their @mit.edu address to the list, # _AND_ use their @mit.edu address for their esp.mit.edu account. # I don't know of a way that I trust that I'm unlazy enough # to implement, that gets around this. user_email = username + "@mit.edu" user_set = ESPUser.objects.filter(username=username, email=user_email) # len(user_set) should always be either 0 or 1, by db constraint. # A "for" loop is the easiest way to handle this. for user in user_set: # Grant bits to the program, if needed # This could probably be made cleaner with a call to get_or_create and a test with special code depending on whether the bit was created or not. # There are several fundamental problems; most revolving around the userbit__uniquetest constraint in the db and the fact that, while there may be no _valid_ bit for a given operation, there can be expired bits. # Also, UserBit Implications may trip things up, if they fail to save due to constraint violation. if not UserBit.UserHasPerms(user, prog_node, admin_node): ub, created = UserBit.objects.get_or_create( user=user, qsc=prog_node, verb=admin_node, enddate__gte=datetime.now(), defaults={'enddate': datetime.now() + timedelta(365)}) print(ub, created) if not created: ub.enddate = datetime.now() + timedelta(365) ub.save() # Grant bits to the website, if needed if not UserBit.UserHasPerms(user, web_qsc_node, admin_node): ub, created = UserBit.objects.get_or_create( user=user,
# Conveniently we don't allow spaces in usernames. -ageng 2010-01-02 username = username.replace(' ', '_') if action == "USER_EXISTS": if len(ESPUser.objects.filter(username__iexact=username)[:1]) > 0: return_(True) else: return_(False) elif action == "AUTHENTICATE": # aseering 7/11/2009 -- MediaWiki enforces that the first letter of usernames be capitalized and that lookups are # case-insensitive. This isn't how Django works; so we can't use their "authenticate" builtin. #from django.contrib.auth import authenticate #user = authenticate(username=username, password=password) user = ESPUser.objects.get(username__iexact=username) if not user.check_password(password): return_(False) from esp.users.models import UserBit, GetNode if UserBit.UserHasPerms(user, GetNode("Q/Wiki"), GetNode("V/Administer"), recursive_required=True): return_(True) else: return_(False) else: return_("ERROR_Unknown_Action")
def classchangerequest(request, tl, one, two): from esp.program.models import Program, StudentAppResponse, StudentRegistration, RegistrationType from esp.program.models.class_ import * from urllib import quote try: prog = Program.by_prog_inst(one, two) #DataTree.get_by_uri(treeItem) except Program.DoesNotExist: raise Http404("Program not found.") if tl != "learn": raise Http404 if not request.user or not request.user.is_authenticated(): return HttpResponseRedirect( '%s?%s=%s' % (LOGIN_URL, REDIRECT_FIELD_NAME, quote(request.get_full_path()))) if not request.user.isStudent() and not request.user.isAdmin(prog): allowed_student_types = Tag.getTag("allowed_student_types", prog, default='') matching_user_types = UserBit.valid_objects().filter( user=request.user, verb__parent=GetNode("V/Flags/UserRole"), verb__name__in=allowed_student_types.split(",")) if not matching_user_types: return render_to_response('errors/program/notastudent.html', request, (prog, 'learn'), {}) errorpage = 'errors/program/wronggrade.html' verb_override = GetNode('V/Flags/Registration/GradeOverride') cur_grade = request.user.getGrade(prog) if (not UserBit.UserHasPerms(user = request.user, qsc = prog.anchor_id, verb = verb_override)) and (cur_grade != 0 and (cur_grade < prog.grade_min or \ cur_grade > prog.grade_max)): return render_to_response(errorpage, request, (prog, tl), {}) setattr(request, "program", prog) setattr(request, "tl", tl) setattr(request, "module", "classchangerequest") from django import forms from datetime import datetime from esp.utils.scheduling import getRankInClass timeslots = prog.getTimeSlots() sections = prog.sections().filter(status=10) enrollments = {} for timeslot in timeslots: try: enrollments[timeslot] = ClassSubject.objects.get( sections__studentregistration__relationship__name="Enrolled", sections__studentregistration__user=request.user, sections__meeting_times=timeslot, parent_program=prog, sections__studentregistration__end_date__gte=datetime.now()) except ClassSubject.DoesNotExist: enrollments[timeslot] = None context = {} context['timeslots'] = timeslots context['enrollments'] = enrollments context['user'] = request.user if 'success' in request.GET: context['success'] = True else: context['success'] = False if request.user.isStudent(): sections_by_slot = dict([(timeslot, [ (section, 1 == StudentRegistration.objects.filter( user=context['user'], section=section, relationship__name="Request", end_date__gte=datetime.now()).count()) for section in sections if section.get_meeting_times()[0] == timeslot and section.parent_class.grade_min <= request.user.getGrade( prog) <= section.parent_class.grade_max and section.parent_class not in enrollments.values() and getRankInClass(request.user, section) in (5, 10) ]) for timeslot in timeslots]) else: sections_by_slot = dict([(timeslot, [ (section, False) for section in sections if section.get_meeting_times()[0] == timeslot ]) for timeslot in timeslots]) fields = {} for i, timeslot in enumerate(sections_by_slot.keys()): choices = [('0', "I'm happy with my current enrollment.")] initial = '0' for section in sections_by_slot[timeslot]: choices.append( (section[0].emailcode(), section[0].emailcode() + ": " + section[0].title())) if section[1]: initial = section[0].emailcode() fields['timeslot_' + str(i + 1)] = forms.ChoiceField( label="Timeslot " + str(i + 1) + " (" + timeslot.pretty_time() + ")", choices=choices, initial=initial) form = type('ClassChangeRequestForm', (forms.Form, ), fields) context['form'] = form() if request.method == "POST": old_requests = StudentRegistration.objects.filter( user=context['user'], section__parent_class__parent_program=prog, relationship__name="Request", end_date__gte=datetime.now()) for r in old_requests: r.expire() form = form(request.POST) if form.is_valid(): for value in form.cleaned_data.values(): section = None for s in sections: if s.emailcode() == value: section = s break if not section: continue r = StudentRegistration.objects.get_or_create( user=context['user'], section=section, relationship=RegistrationType.objects.get_or_create( name="Request", category="student")[0])[0] r.end_date = datetime(9999, 1, 1, 0, 0, 0, 0) r.save() return HttpResponseRedirect(request.path.rstrip('/') + '/?success') else: return render_to_response('program/classchangerequest.html', request, (prog, tl), context)
def hasAttended(self): verb = GetNode('V/Flags/Registration/Attended') return UserBit.UserHasPerms(self.student, self.program_anchor_cached(), verb)
def hasPaid(self): verb = GetNode('V/Flags/Registration/Paid') ps = self.student.paymentStatus(self.program_anchor_cached()) return UserBit.UserHasPerms(self.student, self.program_anchor_cached(), verb) or self.student.has_paid( self.program_anchor_cached())
def hasLiability(self): verb = GetNode('V/Flags/Registration/LiabilityFiled') return UserBit.UserHasPerms(self.student, self.program_anchor_cached(), verb)