def bio_edit_user_program(request, founduser, foundprogram, external=False): """ Edits a teacher bio, given user and program """ if founduser is None: if external: raise ESPError(), 'No user given.' else: raise Http404 if not founduser.isTeacher(): raise ESPError(False), '%s is not a teacher of ESP.' % \ (founduser.name()) if request.user.id != founduser.id and request.user.is_staff != True: raise ESPError(False), 'You are not authorized to edit this biography.' lastbio = TeacherBio.getLastBio(founduser) # if we submitted a newly edited bio... from esp.web.forms.bioedit_form import BioEditForm if request.method == 'POST' and request.POST.has_key('bio_submitted'): form = BioEditForm(request.POST, request.FILES) if form.is_valid(): if foundprogram is not None: # get the last bio for this program. progbio = TeacherBio.getLastForProgram(founduser, foundprogram) else: progbio = lastbio # the slug bio and bio progbio.slugbio = form.cleaned_data['slugbio'] progbio.bio = form.cleaned_data['bio'] progbio.save() # save the image if form.cleaned_data['picture'] is not None: progbio.picture = form.cleaned_data['picture'] else: progbio.picture = lastbio.picture progbio.save() if external: return True return HttpResponseRedirect(progbio.url()) else: formdata = { 'slugbio': lastbio.slugbio, 'bio': lastbio.bio, 'picture': lastbio.picture } form = BioEditForm(formdata) return render_to_response( 'users/teacherbioedit.html', request, GetNode('Q/Web/myesp'), { 'form': form, 'institution': settings.INSTITUTION_NAME, 'user': founduser, 'picture_file': lastbio.picture })
def reviewClass(self, request, tl, one, two, module, extra, prog): """ Set the review status of a class """ if request.method == 'POST': if not (request.POST.has_key('class_id') and request.POST.has_key('review_status')): raise ESPError(), "Error: missing data on request" class_id = request.POST['class_id'] try: class_subject = ClassSubject.objects.get(pk=class_id) except MultipleObjectsReturned: raise ESPError(), "Error: multiple classes selected" except DoesNotExist: raise ESPError(), "Error: no classes found with id "+str(class_id) review_status = request.POST['review_status'] if review_status == 'ACCEPT': # We can't just do class_subject.accept() since this only # accepts sections that were previously unreviewed for sec in class_subject.sections.all(): sec.status = 10 sec.save() class_subject.accept() elif review_status == 'UNREVIEW': class_subject.status = 0 for sec in class_subject.sections.all(): sec.status = 0 sec.save() elif review_status == 'REJECT': class_subject.reject() else: raise ESPError(), "Error: invalid review status" class_subject.save() return HttpResponse('')
def reviewClass(self, request, tl, one, two, module, extra, prog): """ Set the review status of a class """ if request.method == 'POST': if not ('class_id' in request.POST and 'review_status' in request.POST): raise ESPError("Error: missing data on request") class_id = request.POST['class_id'] try: class_subject = ClassSubject.objects.get(pk=class_id) except ClassSubject.MultipleObjectsReturned: raise ESPError("Error: multiple classes selected") except ClassSubject.DoesNotExist: raise ESPError("Error: no classes found with id "+str(class_id)) review_status = request.POST['review_status'] if review_status == 'ACCEPT': class_subject.accept_all_sections() elif review_status == 'UNREVIEW': class_subject.unreview_all_sections() elif review_status == 'REJECT': class_subject.reject() else: raise ESPError("Error: invalid review status") return HttpResponse('')
def _generate_file(self): """ Generates the png file. """ if self.style == 'INLINE': math_style = '$' elif self.style == 'DISPLAY': math_style = '$$' else: raise ESPError(False), 'Unknown display style' tex = r"\documentclass[fleqn]{article} \usepackage{amssymb,amsmath} " +\ r"\usepackage[latin1]{inputenc} \begin{document} " + \ r" \thispagestyle{empty} \mathindent0cm \parindent0cm %s%s%s \end{document}" % \ (math_style, self.content, math_style) tmppath = os.path.join(TMP, self.file_base) tex_file = open(tmppath + '.tex', 'w') tex_file.write(tex.encode('utf-8')) tex_file.close() if os.system('cd %s && %s -interaction=nonstopmode %s > %s' % \ (TMP, COMMANDS['latex'], tmppath, NULL_FILE)) is not 0: raise ESPError(False), 'latex compilation failed.' if os.system( '%s -q -T tight -bg %s -D %s -o %s %s.dvi > %s' % \ (COMMANDS['dvipng'], LATEX_BG, self.dpi, self.local_path, tmppath, NULL_FILE)) is not 0: raise ESPError(False), 'dvipng failed.'
def copyaclass(self, request, tl, one, two, module, extra, prog): if request.method == 'POST': return self.makeaclass_logic(request, tl, one, two, module, extra, prog) if not request.GET.has_key('cls'): raise ESPError(False), "No class specified!" # Select the class cls_id = request.GET['cls'] classes = ClassSubject.objects.filter(id=cls_id) if len(classes) == 0: raise ESPError(False), "No class found matching this ID!" if len(classes) != 1: raise ESPError(False) cls = classes[0] # Select the correct action if cls.category.category == self.program.open_class_category.category: action = 'editopenclass' else: action = 'edit' return self.makeaclass_logic(request, tl, one, two, module, extra, prog, cls, action, populateonly=True)
def __init__(self, func, *args, **kwargs): """ Wrap func in a ArgCache. """ ## Keep the original function's name and docstring ## If the original function has any more-complicated attrs, ## don't bother to maintain them; we have our own attrs, ## and merging custom stuff could be dangerous. if hasattr(func, '__name__'): self.__name__ = func.__name__ if hasattr(func, '__doc__'): self.__doc__ = func.__doc__ import inspect self.argspec = inspect.getargspec(func) self.func = func params = self.argspec[0] extra_name = kwargs.pop('uid_extra', '') name = describe_func(func) + extra_name uid = get_uid(func) + extra_name if self.argspec[1] is not None: raise ESPError(), "ArgCache does not support varargs." if self.argspec[2] is not None: raise ESPError(), "ArgCache does not support keywords." super(ArgCacheDecorator, self).__init__(name=name, params=params, uid=uid, *args, **kwargs)
def userview(request): """ Render a template displaying all the information about the specified user """ try: user = ESPUser.objects.get(username=request.GET['username']) except ESPUser.DoesNotExist: raise ESPError("Sorry, can't find anyone with that username.", log=False) if 'program' in request.GET: try: program = Program.objects.get(id=request.GET['program']) except Program.DoesNotExist: raise ESPError("Sorry, can't find that program.", log=False) else: program = user.get_last_program_with_profile() teacherbio = TeacherBio.getLastBio(user) if not teacherbio.picture: teacherbio.picture = 'images/not-available.jpg' from esp.users.forms.user_profile import StudentInfoForm if 'graduation_year' in request.GET: user.set_student_grad_year(request.GET['graduation_year']) change_grade_form = StudentInfoForm(user=user) if 'disabled' in change_grade_form.fields['graduation_year'].widget.attrs: del change_grade_form.fields['graduation_year'].widget.attrs[ 'disabled'] change_grade_form.fields['graduation_year'].initial = user.getYOG() change_grade_form.fields['graduation_year'].choices = filter( lambda choice: bool(choice[0]), change_grade_form.fields['graduation_year'].choices) context = { 'user': user, 'taught_classes': user.getTaughtClasses().order_by('parent_program', 'id'), 'enrolled_classes': user.getEnrolledSections().order_by('parent_class__parent_program', 'id'), 'taken_classes': user.getSections().order_by('parent_class__parent_program', 'id'), 'teacherbio': teacherbio, 'domain': settings.SITE_INFO[1], 'change_grade_form': change_grade_form, 'printers': StudentRegCore.printer_names(), 'all_programs': Program.objects.all().order_by('-id'), 'program': program, } return render_to_response("users/userview.html", request, context)
def commprev(self, request, tl, one, two, module, extra, prog): from esp.users.models import PersistentQueryFilter from django.conf import settings filterid, listcount, subject, body = [request.POST['filterid'], request.POST['listcount'], request.POST['subject'], request.POST['body'] ] sendto_fn_name = request.POST.get('sendto_fn_name', MessageRequest.SEND_TO_SELF_REAL) # Set From address if request.POST.get('from', '').strip(): fromemail = request.POST['from'] else: # String together an address like [email protected] fromemail = '%s@%s' % (request.user.username, settings.SITE_INFO[1]) # Set Reply-To address if request.POST.get('replyto', '').strip(): replytoemail = request.POST['replyto'] else: replytoemail = fromemail try: filterid = int(filterid) except: raise ESPError("Corrupted POST data! Please contact us at [email protected] and tell us how you got this error, and we'll look into it.") userlist = PersistentQueryFilter.getFilterFromID(filterid, ESPUser).getList(ESPUser) try: firstuser = userlist[0] except: raise ESPError("You seem to be trying to email 0 people! Please go back, edit your search, and try again.") MessageRequest.assert_is_valid_sendto_fn_or_ESPError(sendto_fn_name) # If they were trying to use HTML, don't sanitize the content. if '<html>' not in body: htmlbody = body.replace('<', '<').replace('>', '>').replace('\n', '<br />') else: htmlbody = body contextdict = {'user' : ActionHandler(firstuser, firstuser), 'program': ActionHandler(self.program, firstuser) } renderedtext = Template(htmlbody).render(DjangoContext(contextdict)) return render_to_response(self.baseDir()+'preview.html', request, {'filterid': filterid, 'sendto_fn_name': sendto_fn_name, 'listcount': listcount, 'subject': subject, 'from': fromemail, 'replyto': replytoemail, 'body': body, 'renderedtext': renderedtext})
def survey_review_single(request, tl, program, instance): """ View a single survey response. """ try: prog = Program.by_prog_inst(program, instance) except Program.DoesNotExist: #raise Http404 raise ESPError(), "Can't find the program %s/%s" % (program, instance) user = ESPUser(request.user) survey_response = None ints = request.REQUEST.items() if len(ints) == 1: srs = SurveyResponse.objects.filter(id=ints[0][0]) if len(srs) == 1: survey_response = srs[0] if survey_response is None: raise ESPError( False ), 'Ideally this page should give you some way to pick an individual response. For now I guess you should go back to <a href="review">reviewing the whole survey</a>.' if tl == 'manage' and user.isAdmin(prog): answers = survey_response.answers.order_by('content_type', 'object_id', 'question') classes_only = False other_responses = None elif tl == 'teach': subject_ct = ContentType.objects.get(app_label="program", model="classsubject") section_ct = ContentType.objects.get(app_label="program", model="classsection") class_ids = [x["id"] for x in user.getTaughtClasses().values('id')] section_ids = [x["id"] for x in user.getTaughtSections().values('id')] answers = survey_response.answers.filter( content_type__in=[subject_ct, section_ct], object_id__in=(class_ids + section_ids)).order_by( 'content_type', 'object_id', 'question') classes_only = True other_responses = SurveyResponse.objects.filter( answers__content_type=subject_ct, answers__object_id__in=class_ids).order_by('id').distinct() else: raise ESPError( False ), 'You need to be a teacher or administrator of this program to review survey responses.' context = { 'user': user, 'program': prog, 'response': survey_response, 'answers': answers, 'classes_only': classes_only, 'other_responses': other_responses } return render_to_response('survey/review_single.html', request, context)
def require_teacher_has_time(self, user, current_user, hours): if not self.teacher_has_time(user, hours): if user == current_user: raise ESPError( False ), 'We love you too! However, you attempted to register for more hours of class than we have in the program. Please go back to the class editing page and reduce the duration, or remove or shorten other classes to make room for this one.' else: raise ESPError( False ), "%(teacher_full)s doesn't have enough free time to teach a class of this length. Please go back to the class editing page and reduce the duration, or have %(teacher_first)s remove or shorten other classes to make room for this one." % { 'teacher_full': user.name(), 'teacher_first': user.first_name }
def getClassFromId(self, request, clsid): try: clsid = int(clsid) except ValueError: message = 'Invalid class ID %s.' % clsid raise ESPError(message, log=False) try: cls = ClassSubject.objects.get(id = clsid, parent_program = self.program) except ClassSubject.DoesNotExist: message = 'Unable to find class %s.' % clsid raise ESPError(message, log=False) return cls
def teacherhandout(self, request, tl, one, two, module, extra, prog, template_file='teacherschedules.html'): # Use the template defined in ProgramPrintables from esp.program.modules.handlers import ProgramPrintables context = {'module': self} pmos = ProgramModuleObj.objects.filter( program=prog, module__handler__icontains='printables') if pmos.count() == 1: pmo = ProgramPrintables(pmos[0]) teacher = ESPUser(request.user) scheditems = [] for cls in teacher.getTaughtClasses().filter( parent_program=self.program): if cls.isAccepted(): for section in cls.sections.all(): scheditems.append({ 'name': teacher.name(), 'teacher': teacher, 'cls': section }) scheditems.sort() context['scheditems'] = scheditems return render_to_response(pmo.baseDir() + template_file, request, context) else: raise ESPError( False ), 'No printables module resolved, so this document cannot be generated. Consult the webmasters.'
def selector(request, keep_files=None): if settings.LOCAL_THEME: raise ESPError(THEME_ERROR_STRING, log=False) context = {} tc = ThemeController() if request.method == 'POST' and 'action' in request.POST: if request.POST['action'] == 'select': theme_name = request.POST['theme'].replace(' (current)', '') # Check for differences between the theme's files and those in the working copy. # If there are differences, require a confirmation from the user for each file. differences = tc.check_local_modifications(theme_name) if len(differences) > 0 and keep_files is None: return confirm_overwrite(request, current_theme=theme_name, differences=differences, orig_view='selector') # Display configuration form if one is provided for the selected theme if tc.get_config_form_class(theme_name) is not None: return configure(request, current_theme=theme_name, force_display=True, keep_files=keep_files) tc.save_customizations('%s-last' % tc.get_current_theme()) backup_info = tc.clear_theme(keep_files=keep_files) tc.load_theme(theme_name, backup_info=backup_info) elif request.POST['action'] == 'clear': tc.save_customizations('%s-last' % tc.get_current_theme()) tc.clear_theme() context['theme_name'] = tc.get_current_theme() context['themes'] = tc.get_theme_names() return render_to_response('themes/selector.html', request, context)
def editclass(self, current_user, reg_data, clsid, form_class=TeacherClassRegForm): reg_form, resource_formset, restype_formset = self.get_forms( reg_data, form_class=form_class) try: cls = ClassSubject.objects.get(id=int(clsid)) except (TypeError, ClassSubject.DoesNotExist): raise ESPError( False ), "The class you're trying to edit (ID %s) does not exist!" % ( repr(clsid)) extra_time = reg_form._get_total_time_requested( ) - cls.sections.count() * float(cls.duration) for teacher in cls.get_teachers(): self.require_teacher_has_time(teacher, current_user, extra_time) self.make_class_happen(cls, None, reg_form, resource_formset, restype_formset, editing=True) self.send_class_mail_to_directors(cls) return cls
def myesp_passwd(request, module): """ Change password """ if request.user.username == 'onsite': raise ESPError( False ), "Sorry, you're not allowed to change the password of this user. It's special." if request.method == "POST": form = UserPasswdForm(user=request.user, data=request.POST) if form.is_valid(): new_data = form.cleaned_data user = authenticate(username=request.user.username, password=new_data['password']) user.set_password(new_data['newpasswd']) user.save() login(request, user) return render_to_response('users/passwd.html', request, {'Success': True}) else: form = UserPasswdForm(user=request.user) return render_to_response('users/passwd.html', request, { 'Problem': False, 'form': form, 'Success': False })
def ajax_schedule_class(self, request, tl, one, two, module, extra, prog): # DON'T CACHE this function! # It's supposed to have side effects, that's the whole point! if not 'action' in request.POST: raise ESPError( "This URL is intended to be used for client<->server communication; it's not for human-readable content.", log=False) # Pull relevant data out of the JSON structure cls_id = request.POST['cls'] cls = ClassSection.objects.get(id=cls_id) action = request.POST['action'] if action == 'deletereg': times = [] classrooms = [None] retval = self.ajax_schedule_deletereg(prog, cls, request.user) elif action == 'assignreg': blockrooms = request.POST['block_room_assignments'].split("\n") times = [] classrooms = [] for br in blockrooms: timeslot, classroom = br.split(",") times.append(timeslot) classrooms.append(classroom) retval = self.ajax_schedule_assignreg(prog, cls, times, classrooms, request.user) else: return self.makeret(prog, ret=False, msg="Unrecognized command: '%s'" % action) return retval
def volunteerschedule(self, request, tl, one, two, module, extra, prog): # Use the template defined in ProgramPrintables from esp.program.modules.handlers import ProgramPrintables context = {'module': self} pmos = ProgramModuleObj.objects.filter( program=prog, module__handler__icontains='printables') if pmos.count() == 1: pmo = ProgramPrintables(pmos[0]) if request.user.isAdmin() and 'user' in request.GET: volunteer = ESPUser.objects.get(id=request.GET['user']) else: volunteer = request.user scheditems = [] offers = VolunteerOffer.objects.filter( user=volunteer, request__program=self.program) for offer in offers: scheditems.append({ 'name': volunteer.name(), 'volunteer': volunteer, 'offer': offer }) #sort the offers by timeslot scheditems.sort( key=lambda item: item['offer'].request.timeslot.start) context['scheditems'] = scheditems return render_to_response(pmo.baseDir() + 'volunteerschedule.html', request, context) else: raise ESPError( 'No printables module resolved, so this document cannot be generated. Consult the webmasters.', log=False)
def waitlist_subscribe(self, request, tl, one, two, module, extra, prog): """ Add this user to the waitlist """ self.request = request if not self.program.isFull(): raise ESPError( False ), "You can't subscribe to the waitlist of a program that isn't full yet! Please click 'Back' and refresh the page to see the button to confirm your registration." waitlist_all = UserBit.objects.filter( verb=GetNode("V/Flags/Public"), qsc=GetNode("/".join(prog.anchor.tree_encode()) + "/Waitlist")).filter(enddate__gte=datetime.now()) waitlist = waitlist_all.filter(user=request.user) if waitlist.count() <= 0: UserBit.objects.create( user=request.user, verb=GetNode("V/Flags/Public"), qsc=GetNode("/".join(prog.anchor.tree_encode()) + "/Waitlist"), recursive=False) already_on_list = False else: already_on_list = True return render_to_response(self.baseDir() + 'waitlist.html', request, (prog, tl), { 'already_on_list': already_on_list, 'waitlist': waitlist_all })
def quiz(self, request, tl, one, two, module, extra, prog): custom_form_id = Tag.getProgramTag('quiz_form_id', prog, None) if custom_form_id: cf = Form.objects.get(id=int(custom_form_id)) else: raise ESPError( 'Cannot find an appropriate form for the quiz. Please ask your administrator to create a form and set the quiz_form_id Tag.' ) form_wizard = FormHandler(cf, request, request.user).get_wizard() form_wizard.curr_request = request if request.method == 'POST': form = form_wizard.get_form(0, request.POST, request.FILES) if form.is_valid(): form_wizard.done([form]) self.controller.markCompleted(request.user) return self.goToCore(tl) else: form = form_wizard.get_form(0) return render_to_response(self.baseDir() + 'quiz.html', request, (prog, tl), { 'prog': prog, 'form': form })
def handle_file(self, file, filename): """ Saves a file from request.FILES. """ import uuid # Do we actually need this? splitname = os.path.basename(filename).split('.') if len(splitname) > 1: self.file_extension = splitname[-1] else: self.file_extension = '' # get list of allowed file extensions if hasattr(settings, 'ALLOWED_EXTENSIONS'): allowed_extensions = [x.lower() for x in settings.ALLOWED_EXTENSIONS] else: allowed_extensions = ['pdf', 'odt', 'odp', 'jpg', 'jpeg', 'gif', 'png', 'doc', 'docx', 'ppt', 'pptx', 'zip', 'txt'] if not self.file_extension.lower() in allowed_extensions: raise ESPError(False), "The file extension provided is not allowed. Allowed extensions: %s." % (', '.join(allowed_extensions),) self.mime_type = file.content_type self.size = file.size # hash the filename, easy way to prevent bad filename attacks self.file_name = filename self.hashed_name = str(uuid.uuid4()) while not self.test_upload_filename(): self.hashed_name = str(uuid.uuid4()) self.target_file.save(self.hashed_name, file)
def render_to_latex(filepath, context_dict=None, filetype='pdf'): """Render some tex source to latex. This will run the latex interpreter and generate the necessary file type, which must be one of those from FILE_MIME_TYPES. """ if filetype not in FILE_MIME_TYPES: raise ESPError('Invalid type received for latex generation: %s should ' 'be one of %s' % (filetype, ', '.join(FILE_MIME_TYPES))) context_dict = context_dict or {} if isinstance(filepath, Template): t = filepath elif isinstance(filepath, (tuple, list)): t = loader.select_template(filepath) else: t = loader.get_template(filepath) context_dict['MEDIA_ROOT'] = settings.MEDIA_ROOT context_dict['file_type'] = filetype rendered_source = t.render(context_dict) contents = gen_latex(rendered_source, filetype) return HttpResponse(contents, content_type=FILE_MIME_TYPES[filetype])
def userview(request): """ Render a template displaying all the information about the specified user """ try: user = ESPUser.objects.get(username=request.GET['username']) except: raise ESPError(False), "Sorry, can't find anyone with that username." teacherbio = TeacherBio.getLastBio(user) if not teacherbio.picture: teacherbio.picture = 'images/not-available.jpg' from esp.users.forms.user_profile import StudentInfoForm if 'graduation_year' in request.GET: student_info = user.getLastProfile().student_info student_info.graduation_year = int(request.GET['graduation_year']) student_info.save() change_grade_form = StudentInfoForm(user=user) if 'disabled' in change_grade_form.fields['graduation_year'].widget.attrs: del change_grade_form.fields['graduation_year'].widget.attrs['disabled'] change_grade_form.fields['graduation_year'].initial = ESPUser.YOGFromGrade(user.getGrade()) change_grade_form.fields['graduation_year'].choices = filter(lambda choice: bool(choice[0]), change_grade_form.fields['graduation_year'].choices) context = { 'user': user, 'taught_classes' : user.getTaughtClasses().order_by('parent_program', 'id'), 'enrolled_classes' : user.getEnrolledSections().order_by('parent_class__parent_program', 'id'), 'taken_classes' : user.getSections().order_by('parent_class__parent_program', 'id'), 'teacherbio': teacherbio, 'domain': settings.SITE_INFO[1], 'change_grade_form': change_grade_form, } return render_to_response("users/userview.html", request, context )
def cancelreg(self, request, tl, one, two, module, extra, prog): self.request = request from esp.program.modules.module_ext import DBReceipt if self.have_paid(request.user): raise ESPError( False ), "You have already paid for this program! Please contact us directly (using the contact information in the footer of this page) to cancel your registration and to request a refund." recs = Record.objects.filter(user=request.user, event="reg_confirmed", program=prog) for rec in recs: rec.delete() # If the appropriate flag is set, remove the student from their classes. scrmi = prog.getModuleExtension('StudentClassRegModuleInfo') if scrmi.cancel_button_dereg: sections = request.user.getSections() for sec in sections: sec.unpreregister_student(request.user) # If a cancel receipt template is there, use it. Otherwise, return to the main studentreg page. try: receipt_text = DBReceipt.objects.get(program=self.program, action='cancel').receipt context = {} context["request"] = request context["program"] = prog return HttpResponse( Template(receipt_text).render( Context(context, autoescape=False))) except: return self.goToCore(tl)
def thread(request, extra): context = {} if request.GET.has_key('success'): context['success'] = True threads = AlumniContact.objects.filter(id=extra) if threads.count() == 1: thread = threads[0] context['thread'] = thread if request.method == 'POST': # Handle submission of replies. data = request.POST form = AlumniMessageForm(thread, data, request=request) try: if form.is_valid(): del form.cleaned_data['thread'] # make the form happy new_message = form.save(commit = False) new_message.thread = thread new_message.save() return HttpResponseRedirect(request.path + '?success=1') except UnicodeDecodeError: raise ESPError(False), "You have entered a comment containing invalid international characters. If you are entering international characters, please make sure your browser uses the Unicode UTF-8 text format to do so." return render_to_response('membership/thread_view.html', request, request.get_node('Q/Web/alumni'), context)
def testMorph(self): class scratchCls(object): pass class scratchDict(dict): def cycle_key(self): pass def flush(self): for i in self.keys(): del self[i] # Make up a fake request object # This definitely doesn't meet the spec of the real request object; # if tests fail as a result in the future, it'll need to be fixed. request = scratchCls() request.backend = 'django.contrib.auth.backends.ModelBackend' request.user = None request.session = scratchDict() # Create a couple users and a userbit self.user, created = ESPUser.objects.get_or_create( username='******') self.userbit = UserBit.objects.get_or_create( user=self.user, verb=GetNode('V/Administer'), qsc=GetNode('Q')) self.basic_user, created = ESPUser.objects.get_or_create( username='******') self.userbit = UserBit.objects.get_or_create( user=self.basic_user, verb=GetNode('V/Flags/UserRole/Student'), qsc=GetNode('Q')) self.user.backend = request.backend self.basic_user.backend = request.backend login(request, self.user) self.assertEqual(request.user, self.user, "Failed to log in as '%s'" % self.user) request.user.switch_to_user(request, self.basic_user, None, None) self.assertEqual(request.user, self.basic_user, "Failed to morph into '%s'" % self.basic_user) request.user.switch_back(request) self.assertEqual(request.user, self.user, "Failed to morph back into '%s'" % self.user) blocked_illegal_morph = True try: ESPUser(request.user).switch_to_user(request, self.basic_user, None, None) self.assertEqual(request.user, self.basic_user, "Failed to morph into '%s'" % self.basic_user) except ESPError(): blocked_illegal_morph = True self.assertTrue(blocked_illegal_morph, "User '%s' was allowed to morph into an admin!")
def deadline_met(self, extension=''): # Short-circuit the request middleware during testing, when we call # this function without an actual request. if hasattr(self, 'user'): user = self.user else: request = get_current_request() user = request.user if not 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 = user.isOnsite(self.program) or user.isAdministrator( self.program) if not canView: deadline = { 'learn': 'Student', 'teach': 'Teacher' }[self.module.module_type] + extension canView = Permission.user_has_perm(user, deadline, program=self.program) return canView
def cybersource(self, request, tl, one, two, module, extra, prog): # Force users to pay for non-optional stuffs user = request.user iac = IndividualAccountingController(self.program, request.user) context = {} context['module'] = self context['one'] = one context['two'] = two context['tl'] = tl context['user'] = user context['contact_email'] = self.program.director_email context['invoice_id'] = iac.get_id() context['identifier'] = iac.get_identifier() payment_type = iac.default_payments_lineitemtype() sibling_type = iac.default_siblingdiscount_lineitemtype() grant_type = iac.default_finaid_lineitemtype() context['itemizedcosts'] = iac.get_transfers().exclude( line_item__in=[payment_type, sibling_type, grant_type]).order_by( '-line_item__required') context['itemizedcosttotal'] = iac.amount_due() context['subtotal'] = iac.amount_requested() context['financial_aid'] = iac.amount_finaid() context['sibling_discount'] = iac.amount_siblingdiscount() context['amount_paid'] = iac.amount_paid() context['result'] = request.GET.get("result") context['post_url'] = settings.CYBERSOURCE_CONFIG['post_url'] context['merchant_id'] = settings.CYBERSOURCE_CONFIG['merchant_id'] if (not context['post_url']) or (not context['merchant_id']): raise ESPError("The Cybersource module is not configured") return render_to_response(self.baseDir() + 'cardpay.html', request, context)
def as_queryset(self, value): """Given data returned by the client, return a QuerySet for the query. The data returned will be in the format specified in query-builder.jsx. """ if value['filter'] in ['and', 'or']: if value['filter'] == 'and': op = operator.and_ else: op = operator.or_ combined = reduce(op, map(self.as_queryset, value['values'])) if value['negated']: return self.base.exclude(pk__in=combined) else: return combined elif value['filter'] in self.filter_dict: filter_obj = self.filter_dict[value['filter']] filter_q = filter_obj.as_q(value['values']) if value['negated'] ^ filter_obj.inverted: # Due to https://code.djangoproject.com/ticket/14645, we have # to write this query a little weirdly. return self.base.exclude(id__in=self.base.filter(filter_q)) else: return self.base.filter(filter_q) else: raise ESPError('Invalid filter %s' % value.get('filter'))
def edit_availability(self, request, tl, one, two, module, extra, prog): """ Admins edits availability of the specified user. """ target_id = None if 'user' in request.GET: target_id = request.GET['user'] elif 'user' in request.POST: target_id = request.POST['user'] else: context = {} return render_to_response( self.baseDir() + 'check_availability.html', request, context) try: teacher = ESPUser.objects.get(id=target_id) except: try: teacher = ESPUser.objects.get(username=target_id) except: raise ESPError("The user with id/username="******" does not appear to exist!", log=False) return self.availabilityForm(request, tl, one, two, prog, teacher, True)
def _fail(key=None): numbers = { 'prog_month': 1, 'prog_day': 1, 'photo_exists': 7, 'call_911': 8, 'teacher_lunch': 9, 'check_in': 10, 'sec1': 5, 'sec2': 5, 'sec3': 5, 'sec4': 5, 'sec5': 5, 'sec6': 5, 'reimburse1': 6, 'reimburse2': 6, 'reimburse3': 6, 'reimburse4': 6, 'security_number': 4, 'room_number': 2, 'first_class': 3, } if key is not None: raise ESPError(False), "We're sorry; you gave an incorrect answer to question %d. Please use your browser's back button to return to the quiz and check your answers." % numbers[key] return HttpResponseRedirect("/teach/Spark/quiz_tryagain.html")