def accept_project_volunteer(request, application_id): # Redirect to login if not logged in if not request.user.is_authenticated(): return redirect( section_url(FrontEndSection.LogIn, {'prev': request.get_full_path()})) volunteer_relation = VolunteerRelation.objects.get(id=application_id) about_project_url = section_url(FrontEndSection.AboutProject, {'id': str(volunteer_relation.project.id)}) if volunteer_relation.is_approved: messages.add_message(request, messages.ERROR, 'This volunteer has already been approved.') return redirect(about_project_url) if volunteer_operation_is_authorized(request, volunteer_relation): # Set approved flag volunteer_relation.is_approved = True volunteer_relation.approved_date = timezone.now() volunteer_relation.save() update_project_timestamp(request, volunteer_relation.project) if request.method == 'GET': messages.add_message( request, messages.SUCCESS, volunteer_relation.volunteer.full_name() + ' has been approved as a volunteer.') return redirect(about_project_url) else: return HttpResponse(status=200) else: messages.add_message( request, messages.ERROR, 'You do not have permission to approve this volunteer.') return redirect(about_project_url)
def user_edit(request, user_id): if not request.user.is_authenticated: return redirect(section_url(FrontEndSection.LogIn)) DemocracyLabUserCreationForm.edit_user(request, user_id) return redirect(section_url(FrontEndSection.Profile, {'id': user_id}))
def handle500(request): exception_type, exception, traceback = sys.exc_info() if isinstance(exception, ReportableError): # Log message print("Error(500): " + exception.message) error_args = merge_dicts(exception.front_end_args, {'errorType': type(exception).__name__}) # Redirect to Error page return redirect(section_url(FrontEndSection.Error, error_args)) else: return redirect(section_url(FrontEndSection.Error))
def send_group_project_invitation_email(project_relation): # TODO: Send message to individual group owners by name project = project_relation.relationship_project group = project_relation.relationship_group project_url = section_url(FrontEndSection.AboutProject, {'id': str(project.id)}) group_url = section_url(FrontEndSection.AboutGroup, {'id': str(group.id)}) invite_header = project.project_name + " has been invited to connect!" email_template = HtmlEmailTemplate() \ .header(invite_header) \ .paragraph('{group_link} has invited you to collaborate and connect'.format( group_link=Html.a(href=group_url, text=group.group_name))) \ .paragraph('\"{message}\"'.format(message=project_relation.introduction_text)) \ .button(url=project_url, text='VIEW YOUR GROUPS') send_to_project_owners(project=project, sender=group.group_creator, subject=invite_header, template=email_template)
def send_volunteer_application_email(volunteer_relation, is_reminder=False): project = volunteer_relation.project user = volunteer_relation.volunteer role_details = Tag.from_field(volunteer_relation.role) role_text = "{subcategory}: {name}".format(subcategory=role_details.subcategory, name=role_details.display_name) project_profile_url = section_url(FrontEndSection.AboutProject, {'id': str(project.id)}) approve_url = settings.PROTOCOL_DOMAIN + '/volunteer/approve/' + str(volunteer_relation.id) + '/' email_subject = '{is_reminder}{firstname} {lastname} would like to volunteer with {project} as {role}'.format( is_reminder='REMINDER: ' if is_reminder else '', firstname=user.first_name, lastname=user.last_name, project=project.project_name, role=role_text) email_template = HtmlEmailTemplate()\ .subheader("Opportunity Information:")\ .text_line("Title: {role}".format(role=role_details.display_name))\ .text_line("Organization: {projectname}".format(projectname=project.project_name))\ .text_line("Date: {currentdate}".format(currentdate=datetime_to_string(timezone.now(), DateTimeFormats.MONTH_DD_YYYY)))\ .subheader("Volunteer Information:")\ .text_line("Name: {firstname} {lastname}".format( firstname=user.first_name, lastname=user.last_name))\ .text_line("Email: " + Html.a(href='mailto:' + user.email, text=user.email)) if user.postal_code: email_template = email_template.text_line("Zip: {zip}".format(zip=user.postal_code)) email_template = email_template.header_left("You Have a New Volunteer!")\ .paragraph('\"{message}\" -{firstname} {lastname}'.format( message=volunteer_relation.application_text, firstname=user.first_name, lastname=user.last_name))\ .paragraph('To contact this volunteer directly, you can reply to this email. To review their profile or approve their application, use the buttons below.')\ .button(url=project_profile_url, text='REVIEW VOLUNTEER')\ .button(url=approve_url, text='APPROVE VOLUNTEER') send_to_project_owners(project=project, sender=user, subject=email_subject, template=email_template)
def test_do_not_prerender_urls(self): urls = [ '/projects/signup/', section_url(FrontEndSection.FindProjects, {'sortField': 'project_name'}) ] for url in urls: self.assertFalse(is_sitemap_url(url), 'Should not be able to prerender ' + url)
def signup(request): if request.method == 'POST': form = DemocracyLabUserCreationForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password1') # TODO: Form validation contributor = Contributor( username=email.lower(), email=email.lower(), first_name=form.cleaned_data.get('first_name'), last_name=form.cleaned_data.get('last_name'), email_verified=False) contributor.set_password(raw_password) contributor.save() user = authenticate(username=contributor.username, password=raw_password) login(request, user) send_verification_email(contributor) subscribe_checked = form.data.get('newsletter_signup') if subscribe_checked: SubscribeToMailingList(email=contributor.email, first_name=contributor.first_name, last_name=contributor.last_name) SubscribeUserToQiqoChat(contributor) return redirect(section_url(FrontEndSection.SignedUp)) else: errors = json.loads(form.errors.as_json()) # inform server console of form invalidity print('Invalid form', errors) # inform client of form invalidity for fieldName in errors: fieldErrors = errors[fieldName] for fieldError in fieldErrors: messages.error(request, fieldError['message']) return redirect(section_url(FrontEndSection.SignUp)) else: return redirect(section_url(FrontEndSection.SignUp))
def project_create(request): if not request.user.is_authenticated(): return redirect(section_url(FrontEndSection.LogIn)) user = get_request_contributor(request) if not user.email_verified: # TODO: Log this return HttpResponse(status=403) project = ProjectCreationForm.create_project(request) return JsonResponse(project.hydrate_to_json())
def login_view(request, provider=None): provider_ids = [p.id for p in registry.get_list()] if request.method == 'POST': email = request.POST['username'] password = request.POST['password'] prev_page = request.POST['prevPage'] prev_page_args = ast.literal_eval(request.POST['prevPageArgs']) user = authenticate(username=email.lower(), password=password) if user is not None and user.is_authenticated: login(request, user) redirect_url = '/' if prev_page.strip('/') == '' else section_url(prev_page, prev_page_args) return redirect(redirect_url) else: messages.error(request, 'Incorrect Email or Password') return redirect(section_url(FrontEndSection.LogIn, {'prev': prev_page})) if provider in provider_ids: return redirect(f'{provider}_login') else: return redirect(section_url(FrontEndSection.LogIn))
def verify_user(request, user_id, token): # Get user info user = Contributor.objects.get(id=user_id) # Verify token if email_verify_token_generator.check_token(user, token): # TODO: Add feedback from the frontend to indicate success/failure contributor = Contributor.objects.get(id=user_id) contributor.email_verified = True contributor.save() return redirect(section_url(FrontEndSection.EmailVerified)) else: return HttpResponse(status=401)
def notify_project_owners_project_approved(project): email_template = HtmlEmailTemplate() \ .paragraph('Your project "{{project_name}}" has been approved. You can see it at {{project_url}}') context = { 'project_name': project.project_name, 'project_url': section_url(FrontEndSection.AboutProject, {'id': str(project.id)}) } email_msg = EmailMessage( subject=project.project_name + " has been approved", from_email=_get_account_from_email(settings.EMAIL_SUPPORT_ACCT), to=_get_co_owner_emails(project) ) email_msg = email_template.render(email_msg, context) send_email(email_msg, settings.EMAIL_SUPPORT_ACCT)
def notify_group_owners_group_approved(group): email_template = HtmlEmailTemplate() \ .paragraph('Your group "{{group_name}}" has been approved. You can see it at {{group_url}}') context = { 'group_name': group.group_name, 'group_url': section_url(FrontEndSection.AboutGroup, {'id': str(group.id)}) } email_msg = EmailMessage( subject=group.group_name + " has been approved", from_email=_get_account_from_email(settings.EMAIL_SUPPORT_ACCT), to=[group.group_creator.email] ) email_msg = email_template.render(email_msg, context) send_email(email_msg, settings.EMAIL_SUPPORT_ACCT)
def notify_event_owners_event_approved(event): email_template = HtmlEmailTemplate() \ .paragraph('Your event "{{event_name}}" has been approved. You can see it at {{event_url}}') context = { 'event_name': event.event_name, 'event_url': section_url(FrontEndSection.AboutEvent, {'id': str(event.id)}) } email_msg = EmailMessage( subject=event.event_name + " has been approved", from_email=_get_account_from_email(settings.EMAIL_SUPPORT_ACCT), to=[event.event_creator.email] ) email_msg = email_template.render(email_msg, context) send_email(email_msg, settings.EMAIL_SUPPORT_ACCT)
def send_verification_email_request(request): if not request.user.is_authenticated: return HttpResponse(status=401) user = get_request_contributor(request) if not user.email_verified: send_verification_email(user) if request.method == 'GET': return redirect(section_url(FrontEndSection.SignedUp)) else: return HttpResponse(status=200) else: # If user's email was already confirmed return HttpResponse(status=403)
def event_create(request): if not request.user.is_authenticated(): return redirect(section_url(FrontEndSection.LogIn)) user = get_request_contributor(request) if not user.email_verified: # TODO: Log this return HttpResponse(status=403) event = None try: event = EventCreationForm.create_event(request) except PermissionDenied: return HttpResponseForbidden() return JsonResponse(event.hydrate_to_json())
def add_signup_details(request): contributor = get_request_contributor(request) form = DemocracyLabUserAddDetailsForm(request.POST) if form.is_valid(): contributor.first_name = form.cleaned_data.get('first_name') contributor.last_name = form.cleaned_data.get('last_name') contributor.save() # SubscribeUserToQiqoChat(contributor) else: errors = json.loads(form.errors.as_json()) # inform server console of form invalidity print('Invalid form', errors) # inform client of form invalidity for fieldName in errors: fieldErrors = errors[fieldName] for fieldError in fieldErrors: messages.error(request, fieldError['message']) return redirect(section_url(FrontEndSection.AddUserDetails)) return redirect(section_url(FrontEndSection.Home))
def about_event_preload(context, request): context = default_preload(context, request) query_args = url_params(request) event_id = query_args['id'] event = Event.get_by_id_or_slug(event_id) event_json = event.hydrate_to_json() if event_json is not None: context['title'] = event_json['event_name'] + ' | DemocracyLab' context['description'] = event_json['event_short_description'] if 'event_thumbnail' in event_json: context['og_image'] = event_json['event_thumbnail']['publicUrl'] slug_or_id = event.event_slug or event.id context['canonical_url'] = section_url(FrontEndSection.AboutEvent, {'id': slug_or_id}) else: print('Failed to preload event info, no cache entry found: ' + event_id) return context
def send_password_reset_email(contributor): # Get token user = Contributor.objects.get(id=contributor.id) reset_parameters = { 'userId': contributor.id, 'token': default_token_generator.make_token(user) } reset_url = section_url(FrontEndSection.ChangePassword, reset_parameters) print(reset_url) # Send email with token email_msg = EmailMessage( subject='DemocracyLab Password Reset', body='Click here to change your password: ' + reset_url, from_email=_get_account_from_email(settings.EMAIL_SUPPORT_ACCT), to=[contributor.email] ) send_email(email_msg, settings.EMAIL_SUPPORT_ACCT)
def send_password_reset_email(contributor): # Get token user = Contributor.objects.get(id=contributor.id) reset_parameters = { 'userId': contributor.id, 'token': default_token_generator.make_token(user) } reset_url = section_url(FrontEndSection.ChangePassword, reset_parameters) # Send email with token email_template = HtmlEmailTemplate()\ .header("Hi {{first_name}}.")\ .paragraph('Please click below to reset your password.')\ .button(url=reset_url, text='RESET PASSWORD') email_msg = EmailMessage(subject='DemocracyLab Password Reset', from_email=_get_account_from_email( settings.EMAIL_SUPPORT_ACCT), to=[contributor.email]) email_msg = email_template.render(email_msg, {'first_name': user.first_name}) send_email(email_msg, settings.EMAIL_SUPPORT_ACCT)
def send_group_creation_notification(group): group_url = section_url(FrontEndSection.AboutGroup, {'id': str(group.id)}) verification_url = settings.PROTOCOL_DOMAIN + '/groups/approve/' + str(group.id) email_template = HtmlEmailTemplate() \ .paragraph('{first_name} {last_name}({email}) has created the group "{group_name}": \n {group_url}'.format( first_name=group.group_creator.first_name, last_name=group.group_creator.last_name, email=group.group_creator.email, group_name=group.group_name, group_url=group_url )) \ .button(url=verification_url, text='APPROVE') email_msg = EmailMessage( subject='New DemocracyLab Group: ' + group.group_name, from_email=_get_account_from_email(settings.EMAIL_SUPPORT_ACCT), to=[settings.ADMIN_EMAIL] ) email_msg = email_template.render(email_msg) send_email(email_msg, settings.EMAIL_SUPPORT_ACCT)
def send_event_creation_notification(event): event_url = section_url(FrontEndSection.AboutEvent, {'id': str(event.id)}) verification_url = settings.PROTOCOL_DOMAIN + '/events/approve/' + str(event.id) email_template = HtmlEmailTemplate() \ .paragraph('{first_name} {last_name}({email}) has created the event "{event_name}": \n {event_url}'.format( first_name=event.event_creator.first_name, last_name=event.event_creator.last_name, email=event.event_creator.email, event_name=event.event_name, event_url=event_url )) \ .button(url=verification_url, text='APPROVE') email_msg = EmailMessage( subject='New DemocracyLab Event: ' + event.event_name, from_email=_get_account_from_email(settings.EMAIL_SUPPORT_ACCT), to=[settings.ADMIN_EMAIL] ) email_msg = email_template.render(email_msg) send_email(email_msg, settings.EMAIL_SUPPORT_ACCT)
def test_section_url(self): expected = settings.PROTOCOL_DOMAIN + '/index/?section=AboutEvent&id=test-slug' self.assertEqual( expected, section_url(FrontEndSection.AboutEvent, {'id': 'test-slug'}))
def update_cached_project_url(project_id): update_cached_url( section_url(FrontEndSection.AboutProject, {'id': project_id}))