def configure(request, current_theme=None, force_display=False): context = {} tc = ThemeController() if current_theme is None: current_theme = request.POST.get('theme', None) or tc.get_current_theme() context['theme_name'] = current_theme form_class = tc.get_config_form_class(current_theme) if form_class is None: form = None return render_to_response('themes/configure_form.html', request, context) if request.method == 'POST' and not force_display: form = form_class(request.POST.copy()) if form.is_valid(): # Done; save results and go back to landing page. if form.cleaned_data['theme'] != tc.get_current_theme(): tc.save_customizations('%s-last' % tc.get_current_theme()) if form.cleaned_data['just_selected']: tc.clear_theme() tc.load_theme(form.cleaned_data['theme']) form.save_to_tag() return HttpResponseRedirect('/themes/') else: form = form_class.load_from_tag(theme_name=current_theme, just_selected=force_display) context['form'] = form return render_to_response('themes/configure_form.html', request, context)
def resend_activation_view(request): if request.user.is_authenticated(): return render_to_response('registration/already_logged_in.html', request, request.get_node('Q/Web/myesp'), {}) if request.method == 'POST': form = AwaitingActivationEmailForm(request.POST) if not form.is_valid(): return render_to_response('registration/resend.html', request, request.get_node('Q/Web/myesp'), { 'form': form, 'site': Site.objects.get_current() }) user = ESPUser.objects.get(username=form.cleaned_data['username']) userkey = user.password[user.password.rfind("_") + 1:] send_activation_email(user, userkey) return render_to_response('registration/resend_done.html', request, request.get_node('Q/Web/myesp'), { 'form': form, 'site': Site.objects.get_current() }) else: form = AwaitingActivationEmailForm() return render_to_response('registration/resend.html', request, request.get_node('Q/Web/myesp'), { 'form': form, 'site': Site.objects.get_current() })
def initial_passwd_request(request, success=None): """ This view represents the initial request to have the password reset. Upon successful completion of this view, the user will be emailed at their account. """ if success: return render_to_response('users/recovery_request_success.html', request, request.get_node('Q/Web/myesp'), {}) if request.method == 'POST': form = PasswordResetForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] if username != '': users = ESPUser.objects.filter(username=username) else: users = ESPUser.objects.filter( email__iexact=form.cleaned_data['email']) for user in users: user.recoverPassword() return HttpResponseRedirect('%ssuccess/' % request.path) else: form = PasswordResetForm() return render_to_response('users/recovery_request.html', request, request.get_node('Q/Web/myesp'), {'form': form})
def user_registration_checkemail(request): """Method to handle the first phase of registration when submitted as a form. The method user_registration_phase1 calls this function when it's given a POST request. When the form isn't valid, re-render the same template but with the form errors. When there are already accounts with this email address (depending on some tags), give the user information about them before proceeding. """ form = EmailUserRegForm(request.POST) if form.is_valid(): ## First, check to see if we have any users with the same e-mail if not 'do_reg_no_really' in request.POST and Tag.getBooleanTag('ask_about_duplicate_accounts', default=False): existing_accounts = ESPUser.objects.filter(email=form.cleaned_data['email'], is_active=True).exclude(password='******') awaiting_activation_accounts = ESPUser.objects.filter(email=form.cleaned_data['email']).filter(is_active=False, password__regex='\$(.*)_').exclude(password='******') if len(existing_accounts)+len(awaiting_activation_accounts) != 0: #they have accounts. go back to the same page, but ask them #if they want to try to log in return render_to_response( 'registration/newuser_phase1.html', request, { 'accounts': existing_accounts,'awaitings':awaiting_activation_accounts, 'email':form.cleaned_data['email'], 'site': Site.objects.get_current(), 'form': form }) #form is valid, and not caring about multiple accounts email = urllib.quote(form.cleaned_data['email']) return HttpResponseRedirect(reverse('users.views.user_registration_phase2')+'?email='+email) else: #form is not valid return render_to_response('registration/newuser_phase1.html', request, {'form':form, 'site': Site.objects.get_current()})
def user_registration_phase1(request): """Displays phase 1, and receives and passes off phase 1 submissions.""" if request.user.is_authenticated(): return render_to_response('registration/already_logged_in.html', request, request.get_node('Q/Web/myesp'), {}) #depending on a tag, we'll either have registration all in one page, #or in two separate ones if Tag.getTag("ask_about_duplicate_accounts", default="false").lower() == "false": if request.method == 'POST': return user_registration_validate(request) form = SinglePhaseUserRegForm() return render_to_response('registration/newuser.html', request, request.get_node('Q/Web/myesp'), { 'form': form, 'site': Site.objects.get_current() }) #we do want to ask about duplicate accounts if request.method == 'POST': return user_registration_checkemail(request) form = EmailUserRegForm() return render_to_response('registration/newuser_phase1.html', request, request.get_node('Q/Web/myesp'), { 'form': form, 'site': Site.objects.get_current() })
def join_emaillist(request): """ View to join our email list. """ if request.user.is_authenticated(): return render_to_response('registration/already_logged_in.html', request, request.get_node('Q/Web/myesp'), {}) if request.method == 'POST': form = EmailUserForm(request.POST) if form.is_valid(): # create a user, which will be used if the email address # is used for a real account User.objects.get_or_create(email=form.cleaned_data['email'], username=form.cleaned_data['email'], password='******') add_list_member('announcements', form.cleaned_data['email']) return HttpResponseRedirect('/') else: form = EmailUserRegForm() return render_to_response('registration/emailuser.html', request, request.get_node('Q/Web/myesp'), {'form': form})
def emailpref(request, success=None): if success: return render_to_response('users/emailpref_success.html', request, request.get_node('Q/Web/myesp'), {}) if request.method == 'POST': form = EmailPrefForm(request.POST) if form.is_valid(): ep, created = EmailPref.objects.get_or_create( email=form.cleaned_data['email']) ep.email_opt_in = True ep.first_name = form.cleaned_data['first_name'] ep.last_name = form.cleaned_data['last_name'] ep.sms_number = form.cleaned_data['sms_number'] ep.sms_opt_in = True if ep.sms_number else False ep.save() return redirect('/myesp/emailpref/success') else: form = EmailPrefForm() return render_to_response('users/emailpref.html', request, request.get_node('Q/Web/myesp'), {'form': form})
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 volunteer_signup(request): volunteer_anchor = GetNode('Q/Web/getinvolved') if request.POST: response = VolunteerRegistrationForm(request.POST) if response.is_valid(): data = response.save(from_addr='Splash! Chicago <*****@*****.**>', destination_addrs=['Race Wright <*****@*****.**>']) return render_to_response("shortterm/volunteer_signup/complete.html", request, context={'anchor': volunteer_anchor}) else: response = VolunteerRegistrationForm() return render_to_response("shortterm/volunteer_signup/form.html", request, context={'form': response, 'anchor': volunteer_anchor})
def user_registration_validate(request): """Handle the account creation logic when the form is submitted This function is overloaded to handle either one or two phase reg""" if not Tag.getBooleanTag("ask_about_duplicate_accounts",default=False): form = SinglePhaseUserRegForm(request.POST) else: form = UserRegForm(request.POST) if form.is_valid(): try: #there is an email-only account with that email address to upgrade user = ESPUser.objects.get(email=form.cleaned_data['email'], password = '******') except ESPUser.DoesNotExist: try: #there is an inactive account with that username user = ESPUser.objects.filter( username = form.cleaned_data['username'], is_active = False).latest('date_joined') except ESPUser.DoesNotExist: user = ESPUser(email = form.cleaned_data['email']) user.username = form.cleaned_data['username'] user.last_name = form.cleaned_data['last_name'] user.first_name = form.cleaned_data['first_name'] user.set_password(form.cleaned_data['password']) # Append key to password and disable until activation if desired if Tag.getBooleanTag('require_email_validation', default=False): userkey = random.randint(0,2**31 - 1) user.password += "_%d" % userkey user.is_active = False user.save() ESPUser_Profile.objects.get_or_create(user = user) user.groups.add(Group.objects.get(name=form.cleaned_data['initial_role'])) if not Tag.getBooleanTag('require_email_validation', default=False): user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password']) login(request, user) return HttpResponseRedirect('/myesp/profile/') else: send_activation_email(user,userkey) return render_to_response('registration/account_created_activation_required.html', request, {'user': user, 'site': Site.objects.get_current()}) else: return render_to_response('registration/newuser.html', request, {'form':form})
def make_admin(request): if request.method == 'POST': form = MakeAdminForm(request.POST) if form.is_valid(): target_user = form.cleaned_data['target_user'] make_user_admin(target_user) return render_to_response('users/make_admin_success.html', request, request.get_node('Q/Programs/'), {'target_user': target_user}) else: form = MakeAdminForm() return render_to_response('users/make_admin.html', request, request.get_node('Q/Programs/'), {'form': form})
def landing(request): context = {} tc = ThemeController() context['theme_name'] = tc.get_current_theme() context['last_customization_name'] = Tag.getTag('prev_theme_customization', default='None') return render_to_response('themes/landing.html', request, context)
def myesp(request, module): """ Return page handled by myESP (generally, a user-specific page) """ if myesp_handlers.has_key(module): return myesp_handlers[module](request, module) return render_to_response('users/construction', request, GetNode('Q/Web/myesp'), {})
def home(request): # Get navbars corresponding to the 'home' category nav_category, created = NavBarCategory.objects.get_or_create(name='home') context = { 'navbar_list': makeNavBar(None, GetNode('Q/Web'), '', nav_category) } return render_to_response('index.html', request, GetNode('Q/Web'), context)
def merge_accounts(request): if request.method == 'POST': form = UserMergeForm(request.POST) if form.is_valid(): new_user, old_user = form.cleaned_data[ 'absorber'], form.cleaned_data['absorbee'] merge_users(new_user, old_user) return render_to_response('users/merge_success.html', request, { 'new_user': new_user, 'old_user': old_user }) else: form = UserMergeForm() return render_to_response('users/merge_accounts.html', request, {'form': form})
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 signed_out_message(request): """ If the user is indeed logged out, show them a "Goodbye" message. """ if request.user.is_authenticated(): return HttpResponseRedirect('/') return render_to_response('registration/logged_out.html', request, request.get_node('Q/Web/myesp'), {})
def alumnicontact(request): """ Contact form for alumni. A discussion thread can be associated with a particular program or event from a particular year. Each thread also has one or more alumni associated with it. Each update is e-mailed to esp-membership and the associated alumni. """ context = {} context['form'] = AlumniContactForm(request=request) context['threads'] = AlumniContact.objects.all() if request.GET.has_key('success'): context['success'] = True if request.method == 'POST': data = request.POST form = AlumniContactForm(data, request=request) if form.is_valid(): new_contact = form.load_data() return HttpResponseRedirect('/alumni/thread/%d' % new_contact.id) else: context['form'] = form return render_to_response('membership/alumnicontact.html', request, request.get_node('Q/Web/alumni'), context)
def login_by_bday(request, *args, **kwargs): """ Let a student pick their school. """ if request.user.is_authenticated(): return registration_redirect(request) redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, settings.DEFAULT_REDIRECT) redirect_str = u'' if redirect_to: redirect_str = u'?%s=%s' % (REDIRECT_FIELD_NAME, redirect_to) if request.method == 'POST': form = BirthdaySelectForm(request.POST) if form.is_valid(): month = form.cleaned_data['month'] day = form.cleaned_data['day'] return HttpResponseRedirect(u'/myesp/login/bybday/%s/%s/%s' % (month, day, redirect_str)) else: form = BirthdaySelectForm() return render_to_response( 'registration/login_by_bday.html', request, request.get_node('Q/Web/myesp'), { 'form': form, 'action': request.get_full_path(), 'redirect_field_name': REDIRECT_FIELD_NAME, 'next': redirect_to, 'pwform': BarePasswordForm().as_table() })
def _new_func(request, url='index', subsection=None, filename=None, *args, **kwargs): # Cache which tree node corresponds to this URL cache_key = 'qsdeditor_%s_%s_%s' % (url, subsection, filename) cache_key = cache_key.replace(' ', '') retVal = cache.get(cache_key) if retVal is not None: return view_func(*((request,) + retVal + args), **kwargs) # If we didn't find it in the cache, keep looking # function "constants" READ_VERB = GetNode('V/Flags/Public') DEFAULT_ACTION = 'read' if filename: url += '/%s' % filename # the root of the datatree section = section_redirect_keys[subsection] # Rewrite 'subsection' if we want to. if subsection_map.has_key(subsection): subsection = subsection_map[subsection] tree_root = 'Q/' + section tree_end = url.split('/') view_address = tree_end.pop() if view_address.strip() == '': raise Http404, 'Invalid URL.' tree_node_uri = tree_root + '/' + '/'.join(tree_end) view_address_pieces = view_address.split('.') if len(view_address_pieces) > 1: action = view_address_pieces[-1] view_address = '.'.join(view_address_pieces[:-1]) else: action = DEFAULT_ACTION view_address = view_address_pieces[0] try: # attempt to get the node branch = GetNode(tree_node_uri) except PermissionDenied: raise Http404, "No such site, no bits to create it: '%s'" % \ tree_node_uri except DataTree.NoSuchNodeException, e: edit_link = request.path[:-5]+'.edit.html' branch = e.anchor return render_to_response('qsd/nopage_create.html', request, (branch, section), {'edit_link': edit_link})
def registration_redirect(request): """ A view which returns: - A redirect to the currently open registration if exactly one registration is open - A list of open registration links otherwise """ from esp.users.models import ESPUser from esp.program.models import Program # Make sure we have an ESPUser user = ESPUser(request.user) # prepare the rendered page so it points them to open student/teacher reg's ctxt = {} userrole = {} regperm = None if user.isStudent(): userrole['name'] = 'Student' userrole['base'] = 'learn' userrole['reg'] = 'studentreg' regperm = 'Student/Classes' elif user.isTeacher(): userrole['name'] = 'Teacher' userrole['base'] = 'teach' userrole['reg'] = 'teacherreg' regperm = 'Teacher/Classes' else: # Default to student registration (this will only show if the program # is found via the 'allowed_student_types' Tag) userrole['name'] = user.getUserTypes()[0] userrole['base'] = 'learn' userrole['reg'] = 'studentreg' ctxt['userrole'] = userrole if regperm: progs_deadline = list(Permission.program_by_perm(user, regperm)) else: progs_deadline = [] progs_tag = list(t.target \ for t in Tag.objects.filter(key = "allowed_student_types").select_related() \ if isinstance(t.target, Program) \ and (set(user.getUserTypes()) & set(t.value.split(",")))) progs = list(set(progs_deadline + progs_tag)) #distinct ones # If we have 1 program, automatically redirect to registration for that program. # Most chapters will want this, but it can be disabled by a Tag. if len(progs) == 1 and Tag.getBooleanTag('automatic_registration_redirect', default=True): ctxt['prog'] = progs[0] return HttpResponseRedirect( u'/%s/%s/%s' % (userrole['base'], progs[0].getUrlBase(), userrole['reg'])) else: if len(progs) > 0: # Sort available programs newest first progs.sort(key=lambda x: -x.id) ctxt['progs'] = progs ctxt['prog'] = progs[0] return render_to_response('users/profile_complete.html', request, ctxt)
def _inner_function(request, *args, **kwargs): if request.user.is_authenticated(): return render_to_response('errors/anonymous_only.html', request, request.get_node('Q/Web/about'), {}) return method(request, *args, **kwargs)
def signout(request): """ This view merges Django's logout view with our own "Goodbye" message. """ auth_logout(request) # Tag the (now anonymous) user object so our middleware knows to delete cookies request._cached_user = request.user return render_to_response('registration/logged_out.html', request, {})
def alumnihome(request): """ Main page for alumni. Shows current discussions and all QSD pages in Q/Web/alumni. """ context = {} context['links'] = QuasiStaticData.objects.filter(path=DataTree.get_by_uri('Q/Web/alumni')) context['threads'] = AlumniContact.objects.all() return render_to_response('membership/alumnihome.html', request, request.get_node('Q/Web/alumni'), context)
def email_passwd_followup(request, success=None): """ Allow users to reset their password, given a recovery code. """ if success: return render_to_response('users/recovery_finished.html', request, request.get_node('Q/Web/myesp'), {}) try: code = request.GET['code'] except KeyError: code = request.POST.get('code', '') ticket = PasswordRecoveryTicket.objects.filter(recover_key=code)[:1] if len(ticket) == 0 or not ticket[0].is_valid(): return render_to_response('users/recovery_invalid_code.html', request, request.get_node('Q/Web/myesp'), {}) ticket = ticket[0] if request.method == 'POST': form = NewPasswordSetForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] changed = ticket.change_password(username, password) if changed: auth_user = authenticate( username=form.cleaned_data['username'], password=form.cleaned_data['password']) login(request, auth_user) return HttpResponseRedirect('%ssuccess/' % request.path) else: return render_to_response('users/recovery_invalid_code.html', request, request.get_node('Q/Web/myesp'), {}) else: form = NewPasswordSetForm(initial={'code': code}) return render_to_response('users/recovery_email.html', request, request.get_node('Q/Web/myesp'), {'form': form})
def email_passwd_cancel(request, success=None): """ Allow users to cancel a mis-assigned recovery code. """ if success: return render_to_response('users/recovery_finished.html', request, request.get_node('Q/Web/myesp'), {}) try: code = request.GET['code'] except KeyError: code = request.POST.get('code', '') ticket = PasswordRecoveryTicket.objects.filter(recover_key=code)[:1] if len(ticket) == 0 or not ticket[0].is_valid(): return render_to_response('users/recovery_invalid_code.html', request, request.get_node('Q/Web/myesp'), {}) ticket = ticket[0] ticket.cancel() return render_to_response('users/recovery_cancelled.html', request, request.get_node('Q/Web/myesp'), {})
def formBuilder(request): prog_list = Program.objects.all() form_list = Form.objects.all().order_by('-date_created') if not ESPUser(request.user).isAdministrator(): form_list = form_list.filter(created_by=request.user) return render_to_response( 'customforms/index.html', request, { 'prog_list': prog_list, 'form_list': form_list, 'only_fkey_models': cf_cache.only_fkey_models.keys() })
def school_response_form(request): if request.POST: response = SchoolResponseForm(request.POST) if response.is_valid(): data = response.save() data.send_mail() return HttpResponseRedirect("/school_response/thanks.html") else: response = SchoolResponseForm() return render_to_response("shortterm/school_response/form.html", request, context={ 'form': response })
def path_view(request, model1_name, model2_name): context = defaultdict(list) context['base_model_name'] = model1_name context['model_name'] = model2_name context['base_model'] = globals()[model1_name] context['model'] = globals()[model2_name] context['labels'] = [ label_for_path(context['base_model'], path, models, many, links=True) for (path, models, many) in path_v1(context['base_model'], context['model']) ] return render_to_response('dataviews/paths.html', request, context=context)
def login_checked(request, *args, **kwargs): if request.user.is_authenticated(): # Set response cookies in case of repeat login reply = HttpMetaRedirect('/') reply._new_user = request.user reply.no_set_cookies = False return reply reply = login(request, *args, **kwargs) # Check for user forwarders if request.user.is_authenticated(): old_username = request.user.username user, forwarded = UserForwarder.follow(ESPUser(request.user)) if forwarded: auth_logout(request) auth_login(request, user) # Try to display a friendly error message next_uri = reply.get('Location', '').strip() if next_uri: context = { 'request': request, 'old_username': old_username, 'next_uri': next_uri, 'next_title': next_uri, } if next_uri == '/': context['next_title'] = 'the home page' return render_to_response('users/login_duplicate_warning.html', request, request.get_node('Q/Web/myesp'), context) mask_locations = ['/', '/myesp/signout/', '/admin/logout/'] if reply.get('Location', '') in mask_locations: # We're getting redirected to somewhere undesirable. # Let's try to do something smarter. request.user = ESPUser(request.user) if request.user.isTeacher(): reply = HttpMetaRedirect("/teach/index.html") else: reply = HttpMetaRedirect("/learn/index.html") elif reply.status_code == 302: # Even if the redirect was going to a reasonable place, we need to # turn it into a 200 META redirect in order to set the cookies properly. request.user = ESPUser(request.user) reply = HttpMetaRedirect(reply.get('Location', '')) # Stick the user in the response in order to set cookies if necessary reply._new_user = request.user reply.no_set_cookies = False return reply