def password_form(self): # if admin is changing password for another user no verification of current password is needed if self.context != self.api.user_profile and self.api.context_has_permission( MANAGE_SERVER, self.api.root): schema = createSchema('ChangePasswordAdminSchema') else: schema = createSchema('ChangePasswordSchema') add_csrf_token(self.context, self.request, schema) schema = schema.bind(context=self.context, request=self.request, api=self.api) form = Form(schema, buttons=(button_update, button_cancel)) self.api.register_form_resources(form) post = self.request.POST if 'update' in post: controls = post.items() try: #appstruct is deforms convention. It will be the submitted data in a dict. appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response self.context.set_password(appstruct['password']) msg = _(u"Password changed") self.api.flash_messages.add(msg) url = resource_url(self.context, self.request) return HTTPFound(location=url)
def password_form(self): # if admin is changing password for another user no verification of current password is needed if self.context != self.api.user_profile and self.api.context_has_permission(MANAGE_SERVER, self.api.root): schema = createSchema('ChangePasswordAdminSchema') else: schema = createSchema('ChangePasswordSchema') add_csrf_token(self.context, self.request, schema) schema = schema.bind(context=self.context, request=self.request, api = self.api) form = Form(schema, buttons=(button_update, button_cancel)) self.api.register_form_resources(form) post = self.request.POST if 'update' in post: controls = post.items() try: #appstruct is deforms convention. It will be the submitted data in a dict. appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response self.context.set_password(appstruct['password']) msg = _(u"Password changed") self.api.flash_messages.add(msg) url = resource_url(self.context, self.request) return HTTPFound(location=url)
def test_subscriber_integration(self): self.config.scan('voteit.core.schemas.user') L = [] def subscriber(obj, event): L.append((obj, event)) self.config.add_subscriber(subscriber, [IEditUserSchema, ISchemaCreatedEvent]) createSchema('EditUserSchema') self.failUnless(len(L))
def add(self): if 'cancel' in self.request.POST: url = resource_url(self.context, self.request) return HTTPFound(location=url) type = self.request.GET['type'] obj = createContent(type) schema = createSchema(obj.schemas['add']).bind(context = self.context, request = self.request) form = Form(schema, buttons=('save', 'cancel',)) self.register_form_resources(form) if 'save' in self.request.POST: controls = self.request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response obj.set_field_appstruct(appstruct) name = obj.suggest_name(self.context) self.context[name] = obj url = resource_url(self.context, self.request) return HTTPFound(location=url)
def request_password(self): schema = createSchema('RequestNewPasswordSchema').bind(context=self.context, request=self.request) form = Form(schema, buttons=(button_request, button_cancel)) self.api.register_form_resources(form) #Handle submitted information if 'request' in self.request.POST: controls = self.request.POST.items() try: #appstruct is deforms convention. It will be the submitted data in a dict. appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response userid_or_email = appstruct['userid_or_email'] #userid here can be either an email address or a login name if '@' in userid_or_email: #assume email user = self.context['users'].get_user_by_email(userid_or_email) else: user = self.context['users'].get(userid_or_email) if IUser.providedBy(user): user.new_request_password_token(self.request) self.api.flash_messages.add(_('Email sent.')) url = resource_url(self.api.root, self.request) return HTTPFound(location = url) self.api.flash_messages.add(_('Username or email not found.'), type='error')
def add_form(self): post = self.request.POST if 'cancel' in post: self.api.flash_messages.add(_(u"Canceled")) url = resource_url(self.context, self.request) return HTTPFound(location=url) schema = createSchema('AddUserSchema') add_csrf_token(self.context, self.request, schema) schema = schema.bind(context=self.context, request=self.request, api = self.api) form = Form(schema, buttons=(button_add, button_cancel)) self.api.register_form_resources(form) if 'add' in post: controls = post.items() try: #appstruct is deforms convention. It will be the submitted data in a dict. appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response #Userid and name should be consistent name = appstruct['userid'] del appstruct['userid'] #creators takes care of setting the role owner as well as adding it to creators attr. obj = createContent('User', creators=[name], **appstruct) self.context[name] = obj self.api.flash_messages.add(_(u"Successfully added")) url = resource_url(self.context, self.request) return HTTPFound(location=url)
def view_edit_manage_connected_profiles(self): schema = createSchema('ManageConnectedProfilesSchema').bind( context=self.context, request=self.request) form = Form(schema, buttons=(button_delete, button_cancel)) self.api.register_form_resources(form) #Handle submitted information if 'delete' in self.request.POST: controls = self.request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response domains = appstruct['auth_domains'] if domains: for domain in domains: del self.context.auth_domains[domain] msg = _(u"Removing information for: ${domains}", mapping={'domains': ", ".join(domains)}) self.api.flash_messages.add(msg) else: self.api.flash_messages.add(_(u"Nothing updated")) url = resource_url(self.context, self.request) return HTTPFound(location=url)
def feedback(self): """ Feedback form """ schema = createSchema("FeedbackSchema").bind(context=self.context, request=self.request, api=self.api) form = Form(schema, action=self.request.resource_url(self.context, "feedback"), buttons=(button_send,)) self.api.register_form_resources(form) post = self.request.POST if self.request.method == "POST": controls = post.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response["form"] = e.render() return self.response sender = appstruct["email"] and appstruct["email"] or "VoteIT <*****@*****.**>" recipients = ("*****@*****.**",) response = { "api": self.api, "meeting": self.api.meeting, "name": appstruct["name"], "email": appstruct["email"], "subject": appstruct["subject"], "message": appstruct["message"], } body_html = render("templates/email/feedback.pt", response, request=self.request) subject = "[%s] | %s" % (self.api.translate(_(u"VoteIT Feedback")), appstruct["subject"]) msg = Message(subject=subject, sender=sender and sender or None, recipients=recipients, html=body_html) mailer = get_mailer(self.request) mailer.send(msg) self.api.flash_messages.add(_(u"Message sent to VoteIT")) url = self.request.resource_url(self.context) return HTTPFound(location=url)
def ticket_claim(self): """ After login or registration, redirect back here, where information about the ticket will be displayed, and a confirmation that you want to use the ticket for the current user. While we use a regular deform form, it's not ment to be displayed or handle any validation. """ if not self.api.userid: raise HTTPForbidden("Direct access to this view for unauthorized users not allowed.") schema = createSchema('ClaimTicketSchema', validator = deferred_token_form_validator) schema = schema.bind(context=self.context, request=self.request, api = self.api) form = deform.Form(schema, buttons=(button_add, button_cancel)) if self.request.GET.get('claim'): controls = self.request.params.items() try: appstruct = form.validate(controls) except deform.ValidationFailure, e: msg = _(u"ticket_validation_fail", default = u"Ticket validation failed. Either the ticket doesn't exist, was already used or the url used improperly. " u"If you need help, please contact the moderator that invited you to this meeting.") self.api.flash_messages.add(msg, type = 'error') url = self.request.resource_url(self.api.root) return HTTPFound(location = url) #Everything in order, claim ticket ticket = self.context.invite_tickets[appstruct['email']] ticket.claim(self.request) self.api.flash_messages.add(_(u"You've been granted access to the meeting. Welcome!")) url = self.request.resource_url(self.context) return HTTPFound(location=url)
def group_form(self): if IMeeting.providedBy(self.context): self.response['title'] = _(u"Edit permissions") else: self.response['title'] = _(u"Root permissions") post = self.request.POST if 'cancel' in post: url = resource_url(self.context, self.request) return HTTPFound(location=url) schema = createSchema('PermissionsSchema') add_csrf_token(self.context, self.request, schema) schema = schema.bind(context=self.context, request=self.request, api=self.api) form = Form(schema, buttons=('save', 'cancel')) self.api.register_form_resources(form) if 'save' in post: controls = post.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response #Set permissions self.context.set_security(appstruct['userids_and_groups']) url = resource_url(self.context, self.request) return HTTPFound(location=url)
def start_survey_view(self): """ This view askes the participant which language it wants and redirects to the first section. This starts the survey for this participant. """ try: self.context.check_open() except SurveyUnavailableError as e: self.add_flash_message(e.msg) url = self.request.resource_url(self.context, 'unavailable') return HTTPFound(location=url) selected_language = None available_languages = self.context.get_available_languages() schema = createSchema(self.context.schemas['language']) schema = schema.bind(languages = available_languages, context = self.context, request = self.request) form = Form(schema, buttons=(self.buttons['save'],)) self.response['form_resources'] = form.get_widget_resources() post = self.request.POST if 'save' in post: controls = self.request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response selected_language = appstruct['selected_language']
def variant(self): question_name = self.request.GET.get('question_name', None) globalquestions = self.root['questions'] if question_name not in globalquestions: self.add_flash_message(_(u"Invalid question name.")) url = self.request.resource_url(self.context) return HTTPFound(location=url) question = globalquestions[question_name] schema = createSchema(question.schemas['translate']) schema.title = _(u"Edit question variant for this organisation") schema = schema.bind(context = question, request = self.request) # add default locale description = question.get_original_title() descriptions = question.get_question_text() self.trans_util.add_translation_schema(schema['question_text'], self.trans_util.default_locale_name, description=description) self.trans_util.add_translations_schema(schema['question_text'], self.context, descriptions=descriptions, only_with_description=True) form = Form(schema, action = self.request.url, buttons=(self.buttons['save'], self.buttons['cancel'])) self.response['form_resources'] = form.get_widget_resources() if 'save' in self.request.POST: controls = self.request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response for (lang, value) in appstruct['question_text'].items(): self.context.set_variant(question_name, lang, value) url = self.request.resource_url(self.context, 'variants') return HTTPFound(location = url)
def openid_login_complete(context, request): domain = context.profile['accounts'][0]['domain'] openid_identifier = context.profile['accounts'][0]['username'] force_domain = request.registry.settings.get('openid_domain', None) if force_domain and domain != force_domain: fm = request.registry.getAdapter(request, IFlashMessages) msg = _( u"openid_domain_not_allowed_error", default= u"OpenID logins only allowed from this domain: ${force_domain} - domain was: ${domain}", mapping={ 'force_domain': force_domain, 'domain': domain }) fm.add(msg, type='error') return HTTPFound(location='/') schema = createSchema('CSORegisterUserOpenIDSchema').bind(context=context, request=request) form = Form(schema, action='/openid_register', buttons=(button_register, )) appstruct = { 'openid_identifier': openid_identifier, 'domain': domain, 'came_from': request.session.get('came_from', '') } del request.session['came_from'] return {'form': form.render(appstruct=appstruct)}
def participants_view(self): """ Overview of participants. """ self.response['participants'] = participants = self.context.get_participants_data() not_finished = [x for x in participants if x['finished']<100] self.response['not_finished'] = not_finished self.response['closed_survey'] = self._closed_survey(self.context) schema = createSchema(self.context.schemas['reminder']) schema = schema.bind(context = self.context, request = self.request) form = Form(schema, buttons=(self.buttons['send'],)) self.response['form_resources'] = form.get_widget_resources() post = self.request.POST if 'send' in post: controls = self.request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response for participant in not_finished: # a participant with less then 100% completion will receive the invite ticket again with specified message ticket_uid = participant['uid'] email = self.context.tickets[ticket_uid] self.context.send_invitation_email(self.request, email, ticket_uid, appstruct['subject'], appstruct['message']) self.add_flash_message(_(u"Reminder has been sent"))
def import_view(self): if not has_permission(MANAGE_SERVER, self.api.root, self.request): raise HTTPForbidden("You're not allowed to access this view") redirect_url = resource_url(self.context, self.request) export_import = self.request.registry.queryAdapter(self.api.root, IExportImport) if not export_import: msg = _(u"ExportImport component not included in VoteIT. You need to register it to use this.") self.api.flash_messages.add(msg, type = 'error') return HTTPFound(location=redirect_url) schema = createSchema('ImportSchema').bind(context = self.context, request = self.request) form = deform.Form(schema, buttons=(button_import, button_cancel)) self.api.register_form_resources(form) if 'import' in self.request.POST: controls = self.request.params.items() try: appstruct = form.validate(controls) except deform.ValidationFailure, e: self.response['form'] = e.render() return self.response name = appstruct['name'] filedata = appstruct['upload'] export_import.import_data(self.context, name, filedata['fp']) filedata.clear() self.api.flash_messages.add(_(u"Created new objects from import")) return HTTPFound(location=redirect_url)
def claim_participant_number(self): """ This view is for participants who're already members of this meeting, but haven't registered their number yet. """ if self.api.userid in self.participant_numbers.userid_to_number: number = self.participant_numbers.userid_to_number[self.api.userid] msg = _(u"already_assigned_number_error", default = u"You've already been assigned the number ${number} so you don't need to do anything else.", mapping = {'number': number}) self.api.flash_messages.add(msg, type = 'error') return HTTPFound(location = self.api.meeting_url) schema = createSchema('ClaimParticipantNumber') schema = schema.bind(context = self.context, request = self.request, api = self.api) form = deform.Form(schema, buttons = [deform.Button('submit', title = _(u"Submit"))]) if 'submit' in self.request.POST: controls = self.request.POST.items() try: appstruct = form.validate(controls) except deform.ValidationFailure, e: self.response['form'] = e.render() return self.response number = self.participant_numbers.claim_ticket(self.api.userid, appstruct['token']) msg = _(u"number_now_assigned_notice", default = u"You're now assigned number ${number}.", mapping = {'number': number}) self.api.flash_messages.add(msg) return HTTPFound(location = self.api.meeting_url)
def add_permission(self): if ISiteRoot.providedBy(self.context): self.response['title'] = _(u"Add permission") post = self.request.POST if 'cancel' in post: url = resource_url(self.context, self.request) return HTTPFound(location=url) schema = createSchema('SinglePermissionSchema') add_csrf_token(self.context, self.request, schema) schema = schema.bind(context=self.context, request=self.request, api=self.api) form = Form(schema, buttons=(button_add, button_cancel)) self.api.register_form_resources(form) if IMeeting.providedBy(self.context): self.response['tabs'] = self.api.render_single_view_component( self.context, self.request, 'tabs', 'manage_tickets') if 'add' in post: controls = post.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response #Set permissions self.context.set_groups(appstruct['userid'], appstruct['groups'], event=True) msg = _(u"Added permssion for user ${userid}", mapping={'userid': appstruct['userid']}) self.api.flash_messages.add(msg) url = resource_url(self.context, self.request) return HTTPFound(location=url)
def request_password(self): schema = createSchema('RequestNewPasswordSchema').bind( context=self.context, request=self.request) form = Form(schema, buttons=(button_request, button_cancel)) self.api.register_form_resources(form) #Handle submitted information if 'request' in self.request.POST: controls = self.request.POST.items() try: #appstruct is deforms convention. It will be the submitted data in a dict. appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response userid_or_email = appstruct['userid_or_email'] #userid here can be either an email address or a login name if '@' in userid_or_email: #assume email user = self.context['users'].get_user_by_email(userid_or_email) else: user = self.context['users'].get(userid_or_email) if IUser.providedBy(user): user.new_request_password_token(self.request) self.api.flash_messages.add(_('Email sent.')) url = resource_url(self.api.root, self.request) return HTTPFound(location=url) self.api.flash_messages.add(_('Username or email not found.'), type='error')
def edit_form(self): """ For configuring polls that haven't started yet. """ schema_name = self.api.get_schema_name(self.context.content_type, 'edit') schema = createSchema(schema_name, after_bind=poll_schema_after_bind) add_csrf_token(self.context, self.request, schema) schema = schema.bind(context=self.context, request=self.request, api = self.api) form = Form(schema, buttons=(button_update, button_cancel)) self.api.register_form_resources(form) post = self.request.POST if self.request.method == 'POST': if 'update' in post: controls = post.items() try: #appstruct is deforms convention. It will be the submitted data in a dict. appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response removed_uids = set(self.context.proposal_uids) - set(appstruct['proposals']) if removed_uids: #Adjust removed proposals back to published state, if they're locked for uid in removed_uids: prop = self.context.get_proposal_by_uid(uid) if prop.get_workflow_state() == 'voting': prop.set_workflow_state(self.request, u'published') updated = self.context.set_field_appstruct(appstruct) if updated: self.api.flash_messages.add(_(u"Successfully updated")) else: self.api.flash_messages.add(_(u"Nothing changed")) if 'cancel' in post: self.api.flash_messages.add(_(u"Canceled")) url = self.request.resource_url(self.context.__parent__, anchor = self.context.uid) return HTTPFound(location = url)
def settings(self): meeting = find_interface(self.context, IMeeting) assert meeting schema = createSchema('SpeakerListSettingsSchema') settings = dict(speaker_list_count = 1, safe_positions = 0) settings.update(meeting.get_field_appstruct(schema)) return settings
def survey_view(self): if self.userid: return HTTPFound(location = self.request.resource_url(self.context, 'view')) try: self.context.check_open() self.response['survey_open'] = True except SurveyUnavailableError: self.response['survey_open'] = False self.response['allow_anonymous_to_participate'] = self.context.get_field_value('allow_anonymous_to_participate', False) if self.response['survey_open']: schema = createSchema('ParticipantControlsSchema') schema = schema.bind(context = self.context, request = self.request) form = Form(schema, buttons=(self.buttons['send'],)) self.response['form_resources'] = form.get_widget_resources() if 'send' in self.request.POST: controls = self.request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response if appstruct['participant_actions'] == u"send_anon_invitation" and self.response['allow_anonymous_to_participate']: self.send_invitation(appstruct['email']) if appstruct['participant_actions'] == u"start_anon" and self.context.get_field_value('allow_anonymous_to_start', False): if appstruct['email'] in self.context.tickets.values(): #Check if participant actually started the survey, or was just invited #FIXME: We're looping twice - we should use a reverse key registry instead. for (participant_uid, email) in self.context.tickets.items(): #This will of course be true, since we already know email is in there. if appstruct['email'] == email: if self.root['participants'].participant_by_ids(self.context.__name__, participant_uid): #Abort if survey data founds msg = _(u"email_already_used_notice", default = u"Your email address has already been used within this survey. " u"If you need to change your replies, use the access link provided when you started " u"the survey, or resend the link by using the form below.") self.add_flash_message(msg) return HTTPFound(location = self.request.resource_url(self.context)) invitation_uid = self.context.create_ticket(appstruct['email']) access_link = self.request.resource_url(self.context, 'do', query = {'uid': invitation_uid}) msg = _(u"participant_unverified_link_notice", default = u"Important! Since you're starting this survey without a verified email, please copy this " u"link in case you need to access the survey again: ${link}", mapping = {'link': access_link}) self.add_flash_message(msg) return HTTPFound(location = access_link) if appstruct['participant_actions'] == u"resend_access": if appstruct['email'] not in self.context.tickets.values() and not self.response['allow_anonymous_to_participate']: msg = _(u"cant_resend_access_error", default = u"Unable to resend access code - your email wasn't found among the invited.") self.add_flash_message(msg) return HTTPFound(location = self.request.resource_url(self.context)) self.send_invitation(appstruct['email']) self.response['form'] = form.render()
def show_dummy_text_view(self): schema = createSchema(self.context.schemas['edit']) form = Form(schema) lang = self.get_lang() appstruct = {'title': self.context.get_title(lang = lang), 'description': self.context.get_description(lang = lang)} self.response['form_resources'] = form.get_widget_resources() self.response['dummy_form'] = form.render(readonly = True, appstruct = appstruct) return self.response
def schema(self): schema = createSchema("ClaimParticipantNumber") if self.context.get_field_value('pn_ap_public_roles', False): schema['token'].missing = u"" schema['token'].description = _(u"token_validator_description_when_ok_without", default = u"Enter your code to claim your participant number and all permissions associated with it. " u"If you're not supposed to have a participant number, you're allowed to proceed by clicking " u"'Request access'.") return schema
def admin_view(self): schema = createSchema(self.context.schemas['edit']) schema = schema.bind(context = self.context, request = self.request) appstruct = self.context.get_field_appstruct(schema) form = Form(schema, buttons=()) self.response['form_resources'] = form.get_widget_resources() self.response['form'] = form.render(readonly = True, appstruct = appstruct) self.response['listing'] = self.listing_sniplet() return self.response
def inline_add_form(api, content_type, bind_data): """ Expects the context for the add form to be the current requests context. This is only used within the agenda item view currently. """ tag = api.request.GET.get('tag', '') schema_name = api.get_schema_name(content_type, 'add') schema = createSchema(schema_name, bind = bind_data) query = {'content_type': content_type, 'tag': tag} url = api.request.resource_url(api.context, '_inline_form', query = query) return Form(schema, action = url, buttons = (button_add,), use_ajax = True)
def ajax_set_groups(self): schema = createSchema('PermissionsSchema') add_csrf_token(self.context, self.request, schema) schema = schema.bind(context=self.context, request=self.request, api = self.api) form = Form(schema, buttons=('save', 'cancel')) controls = self.request.POST.items() appstruct = form.validate(controls) #FIXME: Handle error some way, and return a proper response self.context.set_security(appstruct['userids_and_groups']) return Response() # i.e. 200 ok
def contact(self): """ Contact moderators of the meeting """ recipients = [] for userid in find_role_userids(self.context, ROLE_MODERATOR): user = self.api.get_user(userid) email = user.get_field_value('email') if email: recipients.append(email) if not recipients: for userid in find_authorized_userids(self.context, (MODERATE_MEETING, )): user = self.api.get_user(userid) email = user.get_field_value('email') if email: recipients.append(email) schema = createSchema('ContactSchema').bind(context=self.context, request=self.request, api=self.api) form = Form(schema, buttons=(button_send, )) self.api.register_form_resources(form) post = self.request.POST if self.request.method == 'POST': controls = post.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response if appstruct.get('email', None): sender = appstruct['email'] if self.api.user_profile: sender += " <%s>" % self.api.user_profile.title else: sender = None response = { 'api': self.api, 'meeting': self.context, 'name': appstruct['name'], 'email': appstruct['email'], 'subject': appstruct['subject'], 'message': appstruct['message'], } body_html = render('templates/email/help_contact.pt', response, request=self.request) subject = "[%s] %s" % (self.context.title, appstruct['subject']) send_email(subject, recipients, body_html, sender=sender, request=self.request) self.api.flash_messages.add(_(u"Message sent to the moderators")) url = self.request.resource_url(self.context) return HTTPFound(location=url)
def access_policy(self): schema = createSchema("AccessPolicyMeetingSchema") add_csrf_token(self.context, self.request, schema) schema = schema.bind(context=self.context, request=self.request, api = self.api) result = self.form(schema) if 'save' in self.request.POST and isinstance(result, HTTPFound): ap = self.request.registry.queryAdapter(self.context, IAccessPolicy, name = self.context.get_field_value('access_policy', '')) if ap and ap.configurable: self.api.flash_messages.add(_(u"Review access policy configuration")) url = self.request.resource_url(self.context, 'configure_access_policy') return HTTPFound(location = url) return result
def test_form(self): self.config.scan('voteit.core.schemas.meeting') self.config.include('voteit.core.models.flash_messages') self.config.testing_securitypolicy(userid='dummy', permissive=True) self._load_vcs() context = self._fixture() request = testing.DummyRequest() obj = self._cut(context, request) schema = createSchema("PresentationMeetingSchema").bind( context=context, request=request) response = obj.form(schema) self.assertIn('form', response)
def test_form_validation_error(self): self.config.scan('voteit.core.schemas.meeting') self.config.include('voteit.core.models.flash_messages') self.config.testing_securitypolicy(userid='dummy', permissive=True) self._load_vcs() context = self._fixture() request = testing.DummyRequest(post={'save': 'save', 'title': '', 'description': 'Dummy Description'}, is_xhr=False) obj = self._cut(context, request) schema = createSchema("PresentationMeetingSchema").bind(context=context, request=request) response = obj.form(schema) self.assertIn('form', response)
def test_form_cancel(self): self.config.scan('voteit.core.schemas.meeting') self.config.include('voteit.core.models.flash_messages') self.config.testing_securitypolicy(userid='dummy', permissive=True) self._load_vcs() context = self._fixture() request = testing.DummyRequest(post={'cancel': 'cancel'}, is_xhr=False) obj = self._cut(context, request) schema = createSchema("PresentationMeetingSchema").bind(context=context, request=request) response = obj.form(schema) self.assertEqual(response.location, 'http://example.com/m/')
def test_form(self): self.config.scan('voteit.core.schemas.meeting') self.config.include('voteit.core.models.flash_messages') self.config.testing_securitypolicy(userid='dummy', permissive=True) self._load_vcs() context = self._fixture() request = testing.DummyRequest() obj = self._cut(context, request) schema = createSchema("PresentationMeetingSchema").bind(context=context, request=request) response = obj.form(schema) self.assertIn('form', response)
def test_form_cancel(self): self.config.scan('voteit.core.schemas.meeting') self.config.include('voteit.core.models.flash_messages') self.config.testing_securitypolicy(userid='dummy', permissive=True) self._load_vcs() context = self._fixture() request = testing.DummyRequest(post={'cancel': 'cancel'}, is_xhr=False) obj = self._cut(context, request) schema = createSchema("PresentationMeetingSchema").bind( context=context, request=request) response = obj.form(schema) self.assertEqual(response.location, 'http://example.com/m/')
def add_tickets(self): """ Add ticket invites to this meeting. Renders a form where you can paste email addresses and select which roles they should have once they register. When the form is submitted, it will also email users. """ post = self.request.POST if 'cancel' in post: self.api.flash_messages.add(_(u"Canceled")) url = self.request.resource_url(self.context) return HTTPFound(location=url) schema = createSchema('AddTicketsSchema') add_csrf_token(self.context, self.request, schema) schema = schema.bind(context=self.context, request=self.request, api = self.api) form = deform.Form(schema, buttons=(button_add, button_cancel)) self.api.register_form_resources(form) self.response['tabs'] = self.api.render_single_view_component(self.context, self.request, 'tabs', 'manage_tickets') if 'add' in post: controls = post.items() try: appstruct = form.validate(controls) except deform.ValidationFailure, e: self.response['form'] = e.render() return self.response emails = appstruct['emails'].splitlines() roles = appstruct['roles'] added = 0 rejected = 0 for email in emails: result = self.context.add_invite_ticket(email, roles, sent_by = self.api.userid) if result: added += 1 else: rejected += 1 if not rejected: msg = _('added_tickets_text', default=u"Successfully added ${added} invites", mapping={'added': added}) elif not added: msg = _('no_tickets_added', default = u"No tickets added - all you specified probably exist already. (Proccessed ${rejected})", mapping = {'rejected': rejected}) self.api.flash_messages.add(msg) url = self.request.resource_url(self.context, 'add_tickets') return HTTPFound(location = url) else: msg = _('added_tickets_text_some_rejected', default=u"Successfully added ${added} invites but discarded ${rejected} since they already existed or were already used.", mapping={'added': added, 'rejected': rejected}) self.api.flash_messages.add(msg) self.request.session['send_tickets.emails'] = emails self.request.session['send_tickets.message'] = appstruct['message'] url = self.request.resource_url(self.context, 'send_tickets') return HTTPFound(location = url)
def ajax_set_groups(self): schema = createSchema('PermissionsSchema') add_csrf_token(self.context, self.request, schema) schema = schema.bind(context=self.context, request=self.request, api=self.api) form = Form(schema, buttons=('save', 'cancel')) controls = self.request.POST.items() appstruct = form.validate(controls) #FIXME: Handle error some way, and return a proper response self.context.set_security(appstruct['userids_and_groups']) return Response() # i.e. 200 ok
def support(self): """ Support form - requires support email to be set! """ support_email = self.api.root.get_field_value('support_email', None) if not support_email: self.api.flash_messages.add( _(u"No support email set for this site. Form won't work!")) url = self.request.resource_url(self.context) return HTTPFound(location=url) schema = createSchema('SupportSchema').bind(context=self.context, request=self.request, api=self.api) form = Form(schema, action=self.request.resource_url(self.context, 'support'), buttons=(button_send, )) self.api.register_form_resources(form) post = self.request.POST if self.request.method == 'POST': controls = post.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response sender = appstruct['email'] and appstruct[ 'email'] or "VoteIT <*****@*****.**>" response = { 'api': self.api, 'meeting': self.api.meeting, 'name': appstruct['name'], 'email': appstruct['email'], 'subject': appstruct['subject'], 'message': appstruct['message'], 'meeting_title': appstruct.get('meeting_title', ''), } body_html = render('templates/email/support.pt', response, request=self.request) title = "%s %s" % (self.api.root.get_field_value( 'site_title', u"VoteIT"), self.api.translate(_(u"Support"))) subject = "[%s] | %s" % (title, appstruct['subject']) msg = Message(subject=subject, sender=sender and sender or None, recipients=(support_email, ), html=body_html) mailer = get_mailer(self.request) mailer.send(msg) self.api.flash_messages.add(_(u"Support request sent!")) url = self.request.resource_url(self.context) return HTTPFound(location=url)
def add_form(self): content_type = self.request.params.get('content_type') tag = self.request.GET.get('tag', None) #Permission check add_permission = self.api.content_types_add_perm(content_type) if not has_permission(add_permission, self.context, self.request): raise HTTPForbidden( "You're not allowed to add '%s' in this context." % content_type) factory = self.api.get_content_factory(content_type) schema_name = self.api.get_schema_name(content_type, 'add') schema = createSchema(schema_name).bind(context=self.context, request=self.request, api=self.api) form = Form(schema, buttons=(button_add, button_cancel)) self.api.register_form_resources(form) if content_type == 'AgendaItem': self.response['tabs'] = self.api.render_single_view_component( self.context, self.request, 'tabs', 'manage_agenda') post = self.request.POST if 'add' in post: controls = post.items() try: #appstruct is deforms convention. It will be the submitted data in a dict. appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response kwargs = {} kwargs.update(appstruct) if self.api.userid: kwargs['creators'] = [self.api.userid] obj = createContent(content_type, **kwargs) name = self.generate_slug(obj.title) self.context[name] = obj self.api.flash_messages.add(_(u"Successfully added")) #Success, redirect url = self.request.resource_url(obj) #Polls might have a special redirect action if the poll plugin has a settings schema: if content_type == 'Poll': if obj.get_poll_plugin().get_settings_schema() is not None: url += 'poll_config' else: url = self.request.resource_url(obj.__parent__, anchor=obj.uid) msg = _( u"private_poll_info", default= u"The poll is created in private state, to show it the participants you have to change the state to upcoming." ) self.api.flash_messages.add(msg) return HTTPFound(location=url)
def schema(self): schema = createSchema(self.factory._callable.schemas['add']) if self.content_type == 'SurveySection': self.trans_util.add_translations_schema(schema['heading_translations'], self.context) self.trans_util.add_translations_schema(schema['description_translations'], self.context, richtext=True) if self.content_type == 'Question': self.trans_util.add_translations_schema(schema['question_text'], self.context) if self.content_type == 'Choice': add_translations_node(schema, 'title_translations') if self.content_type == 'TextSection': add_translations_node(schema, 'title_translations', based_on = 'title') add_translations_node(schema, 'description_translations', based_on = 'description') return schema
def discussion_answer(self): content_type = 'DiscussionPost' ai = find_interface(self.context, IAgendaItem) add_permission = self.api.content_types_add_perm(content_type) if not has_permission(add_permission, ai, self.request): raise HTTPForbidden("You're not allowed to add '%s' in this context." % content_type) schema_name = self.api.get_schema_name(content_type, 'add') schema = createSchema(schema_name).bind(context = self.context, request = self.request, api = self.api) url = self.request.resource_url(self.context, 'answer') form = Form(schema, action=url, buttons=(button_add,), formid="answer-form-%s" % self.context.uid, use_ajax=False, ajax_options=ajax_options) self.api.register_form_resources(form) self.response['user_image_tag'] = self.api.user_profile.get_image_tag(request = self.request) self.response['content_type'] = content_type post = self.request.POST if 'add' in post: controls = post.items() try: #appstruct is deforms convention. It will be the submitted data in a dict. appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() if self.request.is_xhr: return Response(render("templates/ajax_edit.pt", self.response, request = self.request)) return self.response kwargs = {} kwargs['text'] = appstruct['text'] if self.api.userid: kwargs['creators'] = [self.api.userid] ai = find_interface(self.context, IAgendaItem) obj = createContent(content_type, **kwargs) name = generate_slug(ai, obj.title) ai[name] = obj #Success, redirect url = self.request.resource_url(ai, anchor=obj.uid) if self.request.is_xhr: return Response(headers = [('X-Relocate', url)]) return HTTPFound(location=url)
def register(self): """ Register and log in a user. Be sure to catch came_from since ticket system will use that url to send people who've been invited but haven't registered yet to this view. """ browser_result = self.browser_check() if browser_result: return browser_result schema = createSchema('RegisterUserSchema').bind(context=self.context, request=self.request, api=self.api) form = deform.Form(schema, buttons=(button_register, )) self.api.register_form_resources(form) appstruct = {} POST = self.request.POST users = self.context.users if 'register' in POST: controls = POST.items() try: appstruct = form.validate(controls) except deform.ValidationFailure, e: self.response['form'] = e.render() return self.response #Userid and name should be consistent - and not stored name = appstruct['userid'] del appstruct['userid'] #Came from should not be stored either came_from = urllib.unquote(appstruct['came_from']) if came_from == u'/': came_from = None del appstruct['came_from'] obj = createContent('User', creators=[name], **appstruct) self.context.users[name] = obj headers = remember(self.request, name) # login user if came_from: msg = _(u"You're now registered. Welcome!") self.api.flash_messages.add(msg) return HTTPFound(location=came_from, headers=headers) msg = _( u"joined_without_ticket_intro_text", default=u"You're now registered. Welcome! " u"Please take some time to update your profile and write something about yourself. " u"To join a meeting, you need to either have an invitaion that will have been sent " u"to you via email, or the url of a meeting to request access to it." ) self.api.flash_messages.add(msg) return HTTPFound(location=self.request.resource_url(obj), headers=headers)
def login_box(context, request, va, **kwargs): api = kwargs['api'] if api.userid or request.path_url.endswith('/login'): return u"" #FIXME: Ticket system makes it a bit of a hassle to make login detached from registration. #We'll do that later. For now, let's just check if user is on login or registration page login_schema = createSchema('LoginSchema').bind(context = context, request = request) action_url = request.resource_url(api.root, 'login') login_form = Form(login_schema, buttons=(button_login,), action=action_url) api.register_form_resources(login_form) response = dict( api = api, form = login_form.render(), ) return render('templates/sidebars/login_pw.pt', response, request = request)
def schema(self): schema = createSchema(self.context.schemas['edit']) #FIXME: Translations up for refactoring! if ISurvey.providedBy(self.context): self.trans_util.add_translations_schema(schema['heading_translations'], self.context) if ISurveySection.providedBy(self.context): self.trans_util.add_translations_schema(schema['heading_translations'], self.context) self.trans_util.add_translations_schema(schema['description_translations'], self.context, richtext=True) if IQuestion.providedBy(self.context): self.trans_util.add_translations_schema(schema['question_text'], self.context) if IChoice.providedBy(self.context): add_translations_node(schema, 'title_translations') if ITextSection.providedBy(self.context): add_translations_node(schema, 'title_translations', based_on = 'title') add_translations_node(schema, 'description_translations', based_on = 'description') return schema
def rec_to_discussions_form(self): """ Note: This is far from finished, don't use this unless you really know what you're doing! """ schema = createSchema('PopulateFromRecommendationsSchema') add_csrf_token(self.context, self.request, schema) schema = schema.bind(context = self.context, request = self.request, api = self.api) form = deform.Form(schema, buttons=(button_save,)) self.api.register_form_resources(form) post = self.request.POST if 'save' in post: controls = post.items() try: appstruct = form.validate(controls) except deform.ValidationFailure, e: self.response['form'] = e.render() return self.response adjust_wf = appstruct['adjust_wf'] group = appstruct['group'] userid = appstruct['userid'] dry_run = appstruct['dry_run'] created_discussion_posts = 0 wf_adjusted_proposals = 0 proposals_and_rec = self.get_proposals_and_rec(group) handled_props = len(proposals_and_rec) for (prop, rec) in proposals_and_rec: if rec['text']: created_discussion_posts += 1 text = "%s\n%s" % (rec['text'], u" ".join([u'#%s' % x for x in prop.get_tags()])) post = createContent('DiscussionPost', creators = [userid], text = text) name = post.suggest_name(prop.__parent__) prop.__parent__[name] = post if rec['state'] and adjust_wf: wf_adjusted_proposals += 1 prop.workflow.initialize(prop) prop.set_workflow_state(self.request, rec['state']) self.api.flash_messages.add(_(u"Done - handled ${count} proposals", mapping = {'count': handled_props})) self.api.flash_messages.add(_(u"${count} new discussion posts added", mapping = {'count': created_discussion_posts})) if wf_adjusted_proposals: self.api.flash_messages.add(_(u"${count} proposals workflow adjusted", mapping = {'count': wf_adjusted_proposals})) if dry_run: from transaction import abort abort() self.api.flash_messages.add(_(u"DRY RUN - transaction aborted and nothing saved!")) return HTTPFound(location = self.request.resource_url(self.context))
def add_meeting(self): """ Custom view used when adding meetings. FIXME: We may want to use custom callbacks on add instead, rather than lots of hacks in views. """ content_type = self.request.params.get('content_type') #Permission check add_permission = self.api.content_types_add_perm(content_type) if not has_permission(add_permission, self.context, self.request): raise HTTPForbidden( "You're not allowed to add '%s' in this context." % content_type) factory = self.api.get_content_factory(content_type) schema_name = self.api.get_schema_name(content_type, 'add') schema = createSchema(schema_name) add_csrf_token(self.context, self.request, schema) schema = schema.bind(context=self.context, request=self.request, api=self.api) form = Form(schema, buttons=(button_add, button_cancel)) self.api.register_form_resources(form) post = self.request.POST if 'add' in post: controls = post.items() try: #appstruct is deforms convention. It will be the submitted data in a dict. appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response copy_users_and_perms = appstruct['copy_users_and_perms'] del appstruct['copy_users_and_perms'] kwargs = {} kwargs.update(appstruct) if self.api.userid: kwargs['creators'] = [self.api.userid] obj = createContent(content_type, **kwargs) name = self.generate_slug(obj.title) self.context[name] = obj if copy_users_and_perms: obj.copy_users_and_perms(copy_users_and_perms) self.api.flash_messages.add( _(u"Users and their permissions successfully copied")) else: self.api.flash_messages.add(_(u"Successfully added")) #Success, redirect url = self.request.resource_url(obj) return HTTPFound(location=url)
def test_form_validation_error(self): self.config.scan('voteit.core.schemas.meeting') self.config.include('voteit.core.models.flash_messages') self.config.testing_securitypolicy(userid='dummy', permissive=True) self._load_vcs() context = self._fixture() request = testing.DummyRequest(post={ 'save': 'save', 'title': '', 'description': 'Dummy Description' }, is_xhr=False) obj = self._cut(context, request) schema = createSchema("PresentationMeetingSchema").bind( context=context, request=request) response = obj.form(schema) self.assertIn('form', response)
def twitter_login_complete(context, request): result = { 'profile': context.profile, 'credentials': context.credentials, } schema = createSchema('CSORegisterUserSchema').bind(context=context, request=request) form = Form(schema, action='/twitter_register', buttons=(button_register, )) oauth_token = result['credentials']['oauthAccessToken'] oauth_userid = result['profile']['accounts'][0]['userid'] if 'displayName' in result['profile']: userid = result['profile']['displayName'] else: userid = '' if 'name' in result['profile']: first_name = result['profile']['name']['givenName'] last_name = result['profile']['name']['familyName'] else: first_name = '' last_name = '' if 'verifiedEmail' in result['profile']: email = result['profile']['verifiedEmail'] else: email = '' if not NEW_USERID_PATTERN.match(userid): userid = '' appstruct = { 'userid': userid, 'oauth_access_token': oauth_token, 'oauth_userid': oauth_userid, 'first_name': first_name, 'last_name': last_name, 'email': email, } appstruct['came_from'] = request.session.get('came_from', '') del request.session['came_from'] return {'form': form.render(appstruct=appstruct)}
def login_box(context, request, va, **kwargs): api = kwargs['api'] if api.userid or request.path_url.endswith('/login'): return u"" #FIXME: Ticket system makes it a bit of a hassle to make login detached from registration. #We'll do that later. For now, let's just check if user is on login or registration page login_schema = createSchema('LoginSchema').bind(context=context, request=request) action_url = request.resource_url(api.root, 'login') login_form = Form(login_schema, buttons=(button_login, ), action=action_url) api.register_form_resources(login_form) response = dict( api=api, form=login_form.render(), ) return render('templates/sidebars/login_pw.pt', response, request=request)
def search(self): schema = createSchema('SearchSchema').bind(context = self.context, request = self.request) form = Form(schema, buttons=(button_search,)) self.api.register_form_resources(form) appstruct = {} self.response['results'] = [] def _results_ts(count): """ Note about the odd syntax: pluralize returns unicode, so it won't be translated. Hence it needs to be converted back to a translation string. """ return _(self.api.pluralize(_(u"item"), _(u"items"), count)) post = self.request.POST if 'search' in post: controls = post.items() try: #appstruct is deforms convention. It will be the submitted data in a dict. appstruct = form.validate(controls) except ValidationFailure, e: #pragma : no cover self.response['search_form'] = e.render() return self.response #Preform the actual search query = {} if appstruct['query']: query['searchable_text'] = appstruct['query'] query['path'] = resource_path(self.api.meeting) if self.api.userid: query['allowed_to_view'] = effective_principals(self.request) else: query['allowed_to_view'] = [Everyone] cat_query = self.api.root.catalog.query get_metadata = self.api.root.catalog.document_map.get_metadata try: num, results = cat_query(SEARCH_VIEW_QUERY, names = query, sort_index = 'created', reverse = True) self.response['results'] = [get_metadata(x) for x in results] except ParseError, e: msg = _(u"search_exception_notice", default = u"Search resulted in an error - it's not possible to search for common operator words like 'if' or 'the'.") self.api.flash_messages.add(msg, type = 'error')
def feedback(self): """ Feedback form """ schema = createSchema('FeedbackSchema').bind(context=self.context, request=self.request, api=self.api) form = Form(schema, action=self.request.resource_url(self.context, 'feedback'), buttons=(button_send, )) self.api.register_form_resources(form) post = self.request.POST if self.request.method == 'POST': controls = post.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response sender = appstruct['email'] and appstruct[ 'email'] or "VoteIT <*****@*****.**>" recipients = ("*****@*****.**", ) response = { 'api': self.api, 'meeting': self.api.meeting, 'name': appstruct['name'], 'email': appstruct['email'], 'subject': appstruct['subject'], 'message': appstruct['message'], } body_html = render('templates/email/feedback.pt', response, request=self.request) subject = "[%s] | %s" % (self.api.translate( _(u"VoteIT Feedback")), appstruct['subject']) msg = Message(subject=subject, sender=sender and sender or None, recipients=recipients, html=body_html) mailer = get_mailer(self.request) mailer.send(msg) self.api.flash_messages.add(_(u"Message sent to VoteIT")) url = self.request.resource_url(self.context) return HTTPFound(location=url)
def edit_form(self): self.response['title'] = _( u"Edit %s" % self.api.translate(self.context.display_name)) content_type = self.context.content_type schema_name = self.api.get_schema_name(content_type, 'edit') schema = createSchema(schema_name) add_csrf_token(self.context, self.request, schema) add_came_from(self.context, self.request, schema) schema = schema.bind(context=self.context, request=self.request, api=self.api) form = Form(schema, buttons=(button_update, button_cancel)) self.api.register_form_resources(form) post = self.request.POST if self.request.method == 'POST': came_from = None if 'update' in post: controls = post.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response #Came from should not be stored either came_from = appstruct.pop('came_from', '') updated = self.context.set_field_appstruct(appstruct) if updated: self.api.flash_messages.add(_(u"Successfully updated")) else: self.api.flash_messages.add(_(u"Nothing updated")) if 'cancel' in post: self.api.flash_messages.add(_(u"Canceled")) if came_from: url = urllib.unquote(came_from) elif self.context.content_type == 'Poll': url = self.request.resource_url(self.context.__parent__, anchor=self.context.uid) else: url = self.request.resource_url(self.context) return HTTPFound(location=url)
def login(self): """ Login action used by sidebar widget for password login. """ browser_result = self.browser_check() if browser_result: return browser_result #FIXME: Validation in schema, not in view schema = createSchema( 'LoginSchema', validator=deferred_login_password_validator).bind( context=self.context, request=self.request, api=self.api) form = deform.Form(schema, buttons=(button_login, )) self.api.register_form_resources(form) users = self.context.users POST = self.request.POST if 'login' in POST: controls = POST.items() try: appstruct = form.validate(controls) except deform.ValidationFailure, e: self.response['form'] = e.render() return self.response # Force lowercase userid userid = appstruct['userid'].lower() password = appstruct['password'] came_from = appstruct['came_from'] #userid here can be either an email address or a login name if '@' in userid: #assume email user = users.get_user_by_email(userid) else: user = users.get(userid) if not IUser.providedBy(user): raise HTTPForbidden( u"Userid returned something else then a user from users folder." ) #Password validation already handled by schema here headers = remember(self.request, user.__name__) url = self.request.resource_url(self.context) if came_from: url = urllib.unquote(came_from) return HTTPFound(location=url, headers=headers)
def edit_form(self): """ For configuring polls that haven't started yet. """ schema_name = self.api.get_schema_name(self.context.content_type, 'edit') schema = createSchema(schema_name, after_bind=poll_schema_after_bind) add_csrf_token(self.context, self.request, schema) schema = schema.bind(context=self.context, request=self.request, api=self.api) form = Form(schema, buttons=(button_update, button_cancel)) self.api.register_form_resources(form) post = self.request.POST if self.request.method == 'POST': if 'update' in post: controls = post.items() try: #appstruct is deforms convention. It will be the submitted data in a dict. appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response removed_uids = set(self.context.proposal_uids) - set( appstruct['proposals']) if removed_uids: #Adjust removed proposals back to published state, if they're locked for uid in removed_uids: prop = self.context.get_proposal_by_uid(uid) if prop.get_workflow_state() == 'voting': prop.set_workflow_state(self.request, u'published') updated = self.context.set_field_appstruct(appstruct) if updated: self.api.flash_messages.add(_(u"Successfully updated")) else: self.api.flash_messages.add(_(u"Nothing changed")) if 'cancel' in post: self.api.flash_messages.add(_(u"Canceled")) url = self.request.resource_url(self.context.__parent__, anchor=self.context.uid) return HTTPFound(location=url)
def token_password_change(self): schema = createSchema('TokenPasswordChangeSchema').bind( context=self.context, request=self.request) form = Form(schema, buttons=(button_change, button_cancel)) self.api.register_form_resources(form) post = self.request.POST if 'change' in post: controls = post.items() try: #appstruct is deforms convention. It will be the submitted data in a dict. appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response self.context.remove_password_token() self.context.set_password(appstruct['password']) self.api.flash_messages.add(_(u"Password set. You may login now.")) url = "%slogin" % resource_url(self.api.root, self.request) return HTTPFound(location=url)
def move_object(self): """ Move object to a new parent. """ schema = createSchema('MoveObjectSchema') add_csrf_token(self.context, self.request, schema) schema = schema.bind(context=self.context, request=self.request, api=self.api) form = Form(schema, buttons=(button_update, button_cancel)) post = self.request.POST if 'update' in post: controls = post.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response new_parent_path = urllib.unquote(appstruct['new_parent_path']) new_parent = find_resource(self.api.root, new_parent_path) context = move_object(self.context, new_parent) self.api.flash_messages.add(_(u"Moved")) url = self.request.resource_url(context) return HTTPFound(location=url)
def ticket_claim(self): """ After login or registration, redirect back here, where information about the ticket will be displayed, and a confirmation that you want to use the ticket for the current user. While we use a regular deform form, it's not ment to be displayed or handle any validation. """ if not self.api.userid: raise HTTPForbidden( "Direct access to this view for unauthorized users not allowed." ) schema = createSchema('ClaimTicketSchema', validator=deferred_token_form_validator) schema = schema.bind(context=self.context, request=self.request, api=self.api) form = deform.Form(schema, buttons=(button_add, button_cancel)) if self.request.GET.get('claim'): controls = self.request.params.items() try: appstruct = form.validate(controls) except deform.ValidationFailure, e: msg = _( u"ticket_validation_fail", default= u"Ticket validation failed. Either the ticket doesn't exist, was already used or the url used improperly. " u"If you need help, please contact the moderator that invited you to this meeting." ) self.api.flash_messages.add(msg, type='error') url = self.request.resource_url(self.api.root) return HTTPFound(location=url) #Everything in order, claim ticket ticket = self.context.invite_tickets[appstruct['email']] ticket.claim(self.request) self.api.flash_messages.add( _(u"You've been granted access to the meeting. Welcome!")) url = self.request.resource_url(self.context) return HTTPFound(location=url)
def manage_layout(self): """ Manage layout """ self.response['title'] = _(u"Layout") schema = createSchema('LayoutSchema') add_csrf_token(self.context, self.request, schema) schema = schema.bind(context=self.context, request=self.request, api=self.api) form = Form(schema, buttons=(button_save, button_cancel,)) self.api.register_form_resources(form) post = self.request.POST if 'save' in post: controls = post.items() try: appstruct = form.validate(controls) except ValidationFailure, e: self.response['form'] = e.render() return self.response self.context.set_field_appstruct(appstruct) url = self.request.resource_url(self.context) return HTTPFound(location=url)