class UserManageFormView(UserEditFormView): buttons = (Button('save', _(u'Save')), Button('cancel', _(u'Cancel')), Button('delete', _(u'Delete'))) def schema_factory(self): schema = user_schema() del schema['name'] del schema['password'] return schema def before(self, form): form.appstruct = _massage_groups_out(self.context.__dict__.copy()) def save_success(self, appstruct): _massage_groups_in(appstruct) return super(UserEditFormView, self).save_success(appstruct) def cancel_success(self, appstruct): self.request.session.flash(_(u'No changes made.'), 'info') location = "%s/@@setup-users" % self.request.application_url return HTTPFound(location=location) cancel_failure = cancel_success def delete_success(self, appstruct): principals = get_principals() user = principals.search(email=appstruct['email']).first() location = "%s/@@delete-user?name=%s" % (self.request.application_url, user.name) return HTTPFound(location=location)
def buttons(self): prev_disabled = not self.prev_ok() next_disabled = not self.next_ok() prev_button = Button( name='previous', title='Previous', css_class="btn-warning", disabled=prev_disabled ) # type=submit|reset|button,value=name,css_type="btn-..." cancel_button = Button(name='cancel', title='Cancel', css_class='btn-danger', disabled=False) next_button = Button(name='next', title='Next', css_class="btn-success", disabled=next_disabled) done_button = Button(name='next', title='Done', css_class="btn-success", disabled=next_disabled or not self.request.has_permission('submit')) buttons = [] # TODO: fix focus button if not self.wizard_state.is_first(): buttons.append(prev_button) buttons.append(cancel_button) if self.wizard_state.is_last(): buttons.append(done_button) else: buttons.append(next_button) return buttons
class UserAddFormView(AddFormView): item_type = _(u'User') buttons = (Button('add_user', _(u'Add User')), Button('cancel', _(u'Cancel'))) def schema_factory(self): schema = user_schema() del schema['active'] schema.add( colander.SchemaNode( colander.Boolean(), name=u'send_email', title=_(u'Send password registration link'), default=True, )) return schema def add_user_success(self, appstruct): appstruct.pop('csrf_token', None) _massage_groups_in(appstruct) name = appstruct['name'] = appstruct['name'].lower() appstruct['email'] = appstruct['email'] and appstruct['email'].lower() send_email = appstruct.pop('send_email', False) get_principals()[name] = appstruct if send_email: email_set_password(get_principals()[name], self.request) self.request.session.flash( _(u'${title} added.', mapping=dict(title=appstruct['title'])), 'success') location = self.request.url.split('?')[0] + '?' + urlencode( {'extra': name}) return HTTPFound(location=location)
class UserAddFormView(AddFormView): item_type = _("User") form_options = (("formid", "deform_user_add"), ) buttons = (Button("add_user", _("Add User")), Button("cancel", _("Cancel"))) @staticmethod def schema_factory(): schema = user_schema() del schema["active"] schema.add( colander.SchemaNode( colander.Boolean(), name="send_email", title=_("Send password registration link."), default=True, )) return schema def add_user_success(self, appstruct): appstruct.pop("csrf_token", None) _massage_groups_in(appstruct) name = appstruct["name"] = appstruct["name"].lower() appstruct["email"] = appstruct["email"] and appstruct["email"].lower() send_email = appstruct.pop("send_email", False) get_principals()[name] = appstruct if send_email: email_set_password(get_principals()[name], self.request) self.request.session.flash( _("${title} was added.", mapping=dict(title=appstruct["title"])), "success") location = self.request.url.split("?")[0] + "?" + urlencode( {"extra": name}) return HTTPFound(location=location)
def preferences(request): schema = UserPreferencesSchema() button1 = Button('submit', _('Save changes')) button1.css_class = 'btn-primary' form = Form(schema, buttons=(button1, )) user = request.user if 'submit' in request.POST: controls = request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure as e: return {'form': e.render()} user.update_preferences(appstruct) Session.add(user) request.session.flash( _('The changes were saved successfully'), 'success', ) return HTTPFound(location=request.route_path('user_preferences')) return { 'form': form.render({ 'allow_google_analytics': user.allow_google_analytics, 'send_passwords_periodically': user.send_passwords_periodically, }) }
class BaseFormView(FormView): form_class = Form buttons = (Button('save', _(u'Save')), Button('cancel', _(u'Cancel'))) success_message = _(u"Your changes have been saved.") success_url = None schema_factory = None use_csrf_token = True add_template_vars = () def __init__(self, context, request, **kwargs): self.context = context self.request = request self.__dict__.update(kwargs) def __call__(self): if self.schema_factory is not None: self.schema = self.schema_factory() if self.use_csrf_token and 'csrf_token' not in self.schema: self.schema.children.append(CSRFSchema()['csrf_token']) result = super(BaseFormView, self).__call__() if isinstance(result, dict): result.update(self.more_template_vars()) return result def cancel_success(self, appstruct): return HTTPFound(location=self.request.url) def more_template_vars(self): result = {} for name in self.add_template_vars: result[name] = getattr(self, name) return result
class UserManageFormView(UserEditFormView): buttons = (Button('save', _(u'Save')), Button('cancel', _(u'Cancel')), Button('delete', _(u'Delete'), css_class='btn btn-danger')) def schema_factory(self): schema = user_schema() del schema['name'] return schema def before(self, form): context = self.context.__dict__.copy() context['password'] = u'' form.appstruct = _massage_groups_out(context) def save_success(self, appstruct): if appstruct.get('password'): hashed = get_principals().hash_password(appstruct['password']) appstruct['password'] = hashed else: appstruct.pop('password', None) _massage_groups_in(appstruct) return super(UserEditFormView, self).save_success(appstruct) def cancel_success(self, appstruct): self.request.session.flash(_(u'No changes were made.'), 'info') location = u'{0}/@@setup-users'.format(self.request.application_url) return HTTPFound(location=location) cancel_failure = cancel_success def delete_success(self, appstruct): location = u'{0}/@@delete-user?name={1}'.format( self.request.application_url, self.request.params['name']) return HTTPFound(location=location)
class UserManageFormView(UserEditFormView): buttons = (Button('save', _(u'Save')), Button('cancel', _(u'Cancel')), Button('delete', _(u'Delete'), css_class='btn btn-danger')) def schema_factory(self): schema = user_schema() del schema['name'] del schema['password'] return schema def before(self, form): form.appstruct = _massage_groups_out(self.context.__dict__.copy()) def save_success(self, appstruct): _massage_groups_in(appstruct) return super(UserEditFormView, self).save_success(appstruct) def cancel_success(self, appstruct): self.request.session.flash(_(u'No changes were made.'), 'info') location = "%s/@@setup-users" % self.request.application_url return HTTPFound(location=location) cancel_failure = cancel_success def delete_success(self, appstruct): location = "%s/@@delete-user?name=%s" % ( self.request.application_url, self.request.params['name']) return HTTPFound(location=location)
def form(self): return Form( CreateUserSchema().bind(request=self.request), buttons=[ Button("reset", "Reset", type="reset"), Button("register", "Register"), ], )
def make_client_authorization_form(request): schema = ClientAuthorization() auth_form = Form(schema.bind(request=request), buttons=( Button('submit', title='Authorize Application'), Button('cancel', title='Deny Access'), )) return auth_form
def preferences(request): schema = UserPreferencesSchema() button1 = Button('submit', _('Save changes')) button1.css_class = 'btn-primary' form = Form(schema, buttons=(button1, )) today = request.date_service.today() # use 28 to get a consistent day_to_send no matter what the # current month is. The disadvantage is that there are # several days in a regular month that are not used. day_to_send = get_day_to_send(request.user, 28) if day_to_send > today.day: day_to_send_msg = _( 'You will receive your passwords backup on the day ${day} of this month', mapping={'day': day_to_send}) elif day_to_send < today.day: day_to_send_msg = _( 'You will receive your passwords backup on the day ${day} of next month', mapping={'day': day_to_send}) else: day_to_send_msg = _( 'You will receive your passwords backup today!', mapping={'day': day_to_send}) if 'submit' in request.POST: controls = request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure as e: return {'form': e.render(), 'day_to_send': day_to_send_msg} changes = dict([(pref, appstruct[pref]) for pref in ( analytics.USER_ATTR, 'send_passwords_periodically', )]) result = request.db.users.update({'_id': request.user['_id']}, {'$set': changes}, safe=True) if result['n'] == 1: request.session.flash( _('The changes were saved successfully'), 'success', ) return HTTPFound(location=request.route_path('user_preferences')) else: request.session.flash( _('There were an error while saving your changes'), 'error', ) return {'form': appstruct, 'day_to_send': day_to_send_msg} return {'form': form.render(request.user), 'day_to_send': day_to_send_msg}
def get_form_buttons(): submit = Button(name='submit', title=u'Potvrdi', type='submit', css_class='btn-primary') cancel = Button(name='cancel', title=u'Odustani', type='submit', css_class='btn-default') return submit, cancel
def contact(request): button1 = Button('submit', _('Send message')) button1.css_class = 'btn-primary' button2 = Button('cancel', _('Cancel')) button2.css_class = 'btn-default' form = Form(ContactSchema(), buttons=(button1, button2)) if 'submit' in request.POST: controls = request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure as e: return {'form': e.render()} context = {'link': request.route_url('contact')} context.update(appstruct) subject = ("%s sent a message from Yith's contact form" % appstruct['name']) result = send_email_to_admins( request, 'yithlibraryserver:templates/email_contact', context, subject, extra_headers={'Reply-To': appstruct['email']}, ) if result is None: log.error( '%s <%s> tried to send a message from the contact form but no ' 'admin emails were configured. Message: %s' % ( appstruct['name'], appstruct['email'], appstruct['message'], ) ) request.session.flash( _('Thank you very much for sharing your opinion'), 'info', ) return HTTPFound(location=request.route_path('home')) elif 'cancel' in request.POST: return HTTPFound(location=request.route_path('home')) initial = {} if request.user is not None: initial['name'] = request.user.get('first_name', '') if request.user.get('email_verified', False): initial['email'] = request.user.get('email', '') return {'form': form.render(initial)}
def make_disable_user_form(request): schema = DisableUser() # This form will be on a page with multiple forms, # so we have to set the formid attribute for the ajax # stuff to work. disable_user_form = Form( schema=schema.bind(request=request), buttons=(Button('submit', title='Yes'), Button('cancel', title='No')), formid='disable-form', ) return disable_user_form
def destroy(request): schema = AccountDestroySchema() button1 = Button('submit', _('Yes, I am sure. Destroy my account')) button1.css_class = 'btn-danger' button2 = Button('cancel', _('Cancel')) button2.css_class = 'btn-default' form = Form(schema, buttons=(button1, button2)) user = request.user can_destroy = len(user.applications) == 0 context = { 'passwords': len(user.passwords), 'can_destroy': can_destroy, } if 'submit' in request.POST: if not can_destroy: request.session.flash( _('You must remove your applications before destroying your account'), 'error', ) return HTTPFound(location=request.route_path('oauth2_developer_applications')) controls = request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure as e: context['form'] = e.render() return context reason = appstruct['reason'] notify_admins_of_account_removal(request, user, reason) Session.delete(user) request.session.flash( _('Your account has been removed. Have a nice day!'), 'success', ) return logout(request) elif 'cancel' in request.POST: request.session.flash( _('Thanks for reconsidering removing your account!'), 'info', ) return HTTPFound(location=request.route_path('user_information')) context['form'] = form.render() return context
class GroupAddFormView(UserAddFormView): buttons = (Button('add_group', _(u'Add Group')), Button('cancel', _(u'Cancel'))) def schema_factory(self): schema = group_schema() del schema['active'] return schema def add_group_success(self, appstruct): appstruct['name'] = u'group:%s' % appstruct['name'].lower() return self.add_user_success(appstruct)
def user_information(request): schema = UserSchema() button1 = Button('submit', _('Save changes')) button1.css_class = 'btn-primary' form = Form(schema, buttons=(button1, )) if 'submit' in request.POST: controls = request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure as e: return {'form': e.render()} changes = { 'first_name': appstruct['first_name'], 'last_name': appstruct['last_name'], 'screen_name': appstruct['screen_name'], 'email': appstruct['email']['email'], } if request.user['email'] != appstruct['email']['email']: changes['email_verified'] = False result = request.db.users.update({'_id': request.user['_id']}, {'$set': changes}, safe=True) if result['n'] == 1: request.session.flash( _('The changes were saved successfully'), 'success', ) return HTTPFound(location=request.route_path('user_information')) else: request.session.flash( _('There were an error while saving your changes'), 'error', ) return {'form': appstruct} return { 'form': form.render({ 'first_name': request.user['first_name'], 'last_name': request.user['last_name'], 'screen_name': request.user['screen_name'], 'email': { 'email': request.user['email'], 'email_verified': request.user['email_verified'], }, }), }
class GroupAddFormView(UserAddFormView): item_type = _(u"Group") form_options = (('formid', 'deform_group_add'), ) buttons = (Button('add_group', _(u'Add Group')), Button('cancel', _(u'Cancel'))) def schema_factory(self): schema = group_schema() del schema['active'] return schema def add_group_success(self, appstruct): appstruct['name'] = u'group:{0}'.format(appstruct['name'].lower()) return self.add_user_success(appstruct)
class ConfirmBadPollMethodView(BaseForm): buttons = ( Button( "edit", title=_("Change method"), ), Button("override", title=_("Override - I'm aware of the consequences"), css_class='btn-danger'), BaseForm.button_cancel, ) def get_schema(self): return colander.Schema() def __call__(self): values = super(ConfirmBadPollMethodView, self).__call__() if isinstance(values, dict): values["bad_method_text"] = self.request.session.get( '_bad_method_text', '') values["bad_method_recommendation"] = self.request.session.get( '_bad_method_recommendation', '') return values def _cleanup(self): self.request.session.pop('_bad_method_text', None) self.request.session.pop('_bad_method_recommendation', None) def edit_success(self, appstruct): self._cleanup() url = self.request.resource_url(self.context, "edit") return HTTPFound(location=url) def override_success(self, appstruct): try: self.context.set_workflow_state(self.request, "ongoing") except WorkflowError as exc: raise HTTPForbidden(str(exc)) self._cleanup() url = self.request.resource_url(self.context.__parent__, anchor=self.context.uid) return HTTPFound(location=url) def cancel_success(self, *args): self._cleanup() url = self.request.resource_url(self.context.__parent__, anchor=self.context.uid) return HTTPFound(location=url)
class GroupAddFormView(UserAddFormView): item_type = _("Group") form_options = (("formid", "deform_group_add"), ) buttons = (Button("add_group", _("Add Group")), Button("cancel", _("Cancel"))) @staticmethod def schema_factory(): schema = group_schema() del schema["active"] return schema def add_group_success(self, appstruct): appstruct["name"] = "group:{}".format(appstruct["name"].lower()) return self.add_user_success(appstruct)
def generate_form(self): if self.tab == 'group': btn = Button(name='update', title='Update Group Permission', css_class="btn btn-success btn-lg btn-block", disabled=not self.request.has_permission('admin')) form = Form(schema=self.schema(), buttons=(btn, ), formid='deform') elif self.tab == 'profile': btn = Button(name='update', title='Update Profile', css_class="btn btn-success btn-lg btn-block") form = Form(schema=self.schema(), buttons=(btn, ), formid='deform') else: form = Form(schema=self.schema(), formid='deform') return form
def destroy(request): schema = AccountDestroySchema() button1 = Button('submit', _('Yes, I am sure. Destroy my account')) button1.css_class = 'btn-danger' button2 = Button('cancel', _('Cancel')) button2.css_class = '' form = Form(schema, buttons=(button1, button2)) passwords_manager = PasswordsManager(request.db) context = { 'passwords': passwords_manager.retrieve(request.user).count(), } if 'submit' in request.POST: controls = request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure as e: context['form'] = e.render() return context reason = appstruct['reason'] admin_emails = request.registry.settings['admin_emails'] if admin_emails: notify_admins_of_account_removal(request, request.user, reason, admin_emails) passwords_manager.delete(request.user) # TODO: remove user's applications delete_user(request.db, request.user) request.session.flash( _('Your account has been removed. Have a nice day!'), 'success', ) return logout(request) elif 'cancel' in request.POST: request.session.flash( _('Thanks for reconsidering removing your account!'), 'info', ) return HTTPFound(location=request.route_path('user_information')) context['form'] = form.render() return context
def register(context, request): schema = RegisterSchema().bind(request=request) form = Form(schema, buttons=(Button('register', _(u'Register')), )) rendered_form = None if 'register' in request.POST: try: appstruct = form.validate(request.POST.items()) except ValidationFailure, e: request.session.flash(_(u"There was an error."), 'error') rendered_form = e.render() else: settings = get_settings() appstruct['groups'] = u'' appstruct['roles'] = u'' register_groups = settings['kotti.register.group'] if register_groups: appstruct['groups'] = [register_groups] register_roles = settings['kotti.register.role'] if register_roles: appstruct['roles'] = set(['role:' + register_roles]) appstruct['send_email'] = True form = UserAddFormView(context, request) form.add_user_success(appstruct) success_msg = _( 'Congratulations! You are successfully registered. ' 'You should receive an email with a link to set your ' 'password momentarily.') request.session.flash(success_msg, 'success') return HTTPFound(location=request.application_url)
def make_new_authorization_form(request): schema = Authorization() new_authoization_form = Form( schema=schema.bind(request=request), buttons=(Button(u'submit', title=u'Create'), ), ) return new_authoization_form
def make_login_form(request, action=''): schema = Login() login_form = Form(schema=schema.bind(request=request), action=action, bootstrap_form_style='form-vertical', buttons=(Button('submit', title='Log In'), 'cancel')) return login_form
def edit(self): if self._is_new(): return HTTPNotFound() else: # Create a readonly issue form resp = super().edit(readonly=True) issue = self._get_object() event = Event(issue_id=issue.id) event.status = issue.status event.author = self._author event_form = Form( self._event_schema, formid="new_event_form", buttons=[Button(name="formsubmit", title=_("Submit"))], action=self._request.route_url( "c2cgeoform_item", table="events", id="new" ), ) resp.update( { "event_form": event_form, "event_form_render_args": (event_form.schema.dictify(event),), "event_form_render_kwargs": { "request": self._request, "user_admin": USER_ADMIN, "obj": issue, }, "events": self.events(issue), "wms_layer": self._get_object().type.wms_layer, } ) return resp
class login(FormView): schema = LoginSchema(validator=login_validator) buttons = ( Button('log in', type='submit'), Button('forgot', title='Password help?'), ) form_class = partial(Form, bootstrap_form_style='form-vertical', formid='auth') def log_in_success(self, form): request = self.request user = (AuthUser.get_by_login(form['username']) or AuthUser.get_by_email(form['username'])) headers = remember(request, user.auth_id) return HTTPSeeOther(headers=headers, location=get_came_from(request))
def __init__(self, request): super(Login, self).__init__(request) schema = LoginSchema().bind(request=self.request) self.form = Form(schema, buttons=(Button(title=u'Login!'), ), method=u'post', action=self.request.route_path('login'))
def __init__(self, *args, **kwargs): """Initialize DefaultRegisterForm.""" sign_up_button = Button(name="sign_up", title="Sign up with email", css_class="btn-lg btn-block") kwargs['buttons'] = (sign_up_button, ) super().__init__(*args, **kwargs)
def edit(self): location = self.request.context form = Form( LocationForm().bind( request=self.request, location=location), buttons=('Save', Button(name='cancel', type='button')), appstruct=location.appstruct) if self.request.method == 'POST': data = self.request.POST.items() try: values = form.validate(data) except ValidationFailure: pass else: location.update(**values) self.request.session.flash( _("Your changes have been saved"), 'success') return HTTPFound( self.request.route_url( 'locations', traverse=(location.id, 'edit'))) return { 'form': form, 'location': location, 'period': self.period }
def __init__(self, *args, **kwargs): """Initialize DefaultLoginForm.""" login_button = Button(name="login_email", title="Login with email", css_class="btn-lg btn-block") kwargs['buttons'] = (login_button, ) super().__init__(*args, **kwargs)
def _get_login_form(request, use_ajax=False): """ Return the login form object :param obj request: The pyramid request object :param bool use_ajax: Is this form called through xhr (should it be an ajax form) ? """ if use_ajax: action = request.route_path('login') ajax_options = """{ 'dataType': 'json', 'success': ajaxAuthCallback }""" else: action = None ajax_options = "{}" form = Form( get_auth_schema(), action=action, use_ajax=use_ajax, formid="authentication", ajax_options=ajax_options, bootstrap_form_style="authentication-form", buttons=(Button( name="submit", title="Connexion", type='submit', ), ), ) return form
def generate_form(self): submit_button = Button(name='submit', title='Submit', css_class='btn btn-success') return Form(schema=ESGFLogonSchema().bind(request=self.request), buttons=(submit_button, ), formid="esgflogon")
def get_duplicate_form(request, counter=None): """ Return the form for task duplication """ duplicate_js.need() schema = DuplicateSchema().bind(request=request) action = request.route_path( request.context.__name__, id=request.context.id, _query=dict(action='duplicate'), ) valid_btn = Button( name='submit', value="duplicate", type='submit', title=u"Valider", ) form = Form( schema=schema, buttons=(valid_btn, ), action=action, formid="duplicate_form", counter=counter, ) return form
def ballot_voting_form(ballot_voting, request): yes_no_choices = [(True, _('Yes')), (False, _('No')), (None, _('Abstention'))] max_points = 9 if len(ballot_voting.options) > 3 else 3 point_choices = [(i, str(i)) for i in range(max_points+1)] schema = Schema() for option in ballot_voting.options: option_schema = SchemaNode(Mapping(), name=str(option.uuid), title=option.title) option_schema.add(SchemaNode( Boolean(), validator=OneOf([x[0] for x in yes_no_choices]), widget=RadioChoiceWidget(values=yes_no_choices, inline=True), name='yes_no', title=f'Stimmst du dem Antrag zu?')) option_schema.add(SchemaNode( Int(), validator=OneOf([x[0] for x in point_choices]), widget=RadioChoiceWidget(values=point_choices, inline=True, null_value='0'), name='points', title='Welche Punktzahl gibst du dem Antrag?', missing=0)) schema.add(option_schema) form = Form(schema, request, buttons=[Button(title=_('check'))]) return form
def user_information(request): schema = UserSchema() button1 = Button('submit', _('Save changes')) button1.css_class = 'btn-primary' form = Form(schema, buttons=(button1, )) user = request.user if 'submit' in request.POST: controls = request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure as e: return {'form': e.render()} changes = { 'first_name': appstruct['first_name'], 'last_name': appstruct['last_name'], 'screen_name': appstruct['screen_name'], 'email': appstruct['email']['email'], } user.update_user_info(changes) Session.add(user) request.session.flash( _('The changes were saved successfully'), 'success', ) return HTTPFound(location=request.route_path('user_information')) return { 'form': form.render({ 'first_name': user.first_name, 'last_name': user.last_name, 'screen_name': user.screen_name, 'email': { 'email': user.email, 'email_verified': user.email_verified, }, }), }
def developer_application_new(request): assert_authenticated_user_is_registered(request) schema = ApplicationSchema() button1 = Button('submit', _('Save application')) button1.css_class = 'btn-primary' button2 = Button('cancel', _('Cancel')) button2.css_class = '' form = Form(schema, buttons=(button1, button2)) if 'submit' in request.POST: controls = request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure as e: return {'form': e.render()} # the data is fine, save into the db application = { 'owner': request.user['_id'], 'name': appstruct['name'], 'main_url': appstruct['main_url'], 'callback_url': appstruct['callback_url'], 'authorized_origins': appstruct['authorized_origins'], 'production_ready': appstruct['production_ready'], 'image_url': appstruct['image_url'], 'description': appstruct['description'], } create_client_id_and_secret(application) request.session.flash( _('The application ${app} was created successfully', mapping={'app': appstruct['name']}), 'success') request.db.applications.insert(application, safe=True) return HTTPFound( location=request.route_path('oauth2_developer_applications')) elif 'cancel' in request.POST: return HTTPFound( location=request.route_path('oauth2_developer_applications')) # this is a GET return {'form': form.render()}
def preferences(request): schema = UserPreferencesSchema() button1 = Button('submit', _('Save changes')) button1.css_class = 'btn-primary' form = Form(schema, buttons=(button1, )) if 'submit' in request.POST: controls = request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure as e: return {'form': e.render()} changes = dict([(pref, appstruct[pref]) for pref in ( analytics.USER_ATTR, 'send_passwords_periodically', )]) result = request.db.users.update({'_id': request.user['_id']}, {'$set': changes}) if result['n'] == 1: request.session.flash( _('The changes were saved successfully'), 'success', ) return HTTPFound(location=request.route_path('user_preferences')) else: request.session.flash( _('There were an error while saving your changes'), 'error', ) return {'form': appstruct} return {'form': form.render(request.user)}
def register_new_user(request): try: user_info = request.session['user_info'] except KeyError: return HTTPBadRequest('Missing user info in the session') try: next_url = request.session['next_url'] except KeyError: next_url = request.route_url('oauth2_clients') schema = NewUserSchema() button1 = Button('submit', _('Register into Yith Library')) button1.css_class = 'btn-primary' button2 = Button('cancel', _('Cancel')) button2.css_class = 'btn-default logout' form = Form(schema, buttons=(button1, button2)) if 'submit' in request.POST: controls = request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure as e: return { 'form': e.render(), 'provider': user_info.get('provider', ''), 'email': user_info.get('email', ''), 'next_url': next_url, } provider = user_info['provider'] provider_key = provider + '_id' email = appstruct['email'] if email != '' and email == user_info['email']: email_verified = True else: email_verified = False now = datetime.datetime.now(tz=utc) user_attrs = { provider_key: user_info[provider_key], 'screen_name': appstruct['screen_name'], 'first_name': appstruct['first_name'], 'last_name': appstruct['last_name'], 'email': email, 'email_verified': email_verified, 'date_joined': now, 'last_login': now, 'send_passwords_periodically': False, } if request.google_analytics.is_in_session(): allow_analytics = request.google_analytics.show_in_session() user_attrs[analytics.USER_ATTR] = allow_analytics request.google_analytics.clean_session() _id = request.db.users.insert(user_attrs) if not email_verified and email != '': evc = EmailVerificationCode() user = request.db.users.find_one({'_id': _id}) if evc.store(request.db, user): link = request.route_url('user_verify_email') evc.send(request, user, link) del request.session['user_info'] if 'next_url' in request.session: del request.session['next_url'] request.session['current_provider'] = provider return HTTPFound(location=next_url, headers=remember(request, str(_id))) elif 'cancel' in request.POST: del request.session['user_info'] if 'next_url' in request.session: del request.session['next_url'] return HTTPFound(location=next_url) return { 'form': form.render({ 'first_name': user_info.get('first_name', ''), 'last_name': user_info.get('last_name', ''), 'screen_name': user_info.get('screen_name', ''), 'email': user_info.get('email', ''), }), 'provider': user_info.get('provider', ''), 'email': user_info.get('email', ''), 'next_url': next_url, }
def developer_application_edit(request): app_id = request.matchdict['app'] try: uuid.UUID(app_id) except ValueError: return HTTPBadRequest() try: app = Session.query(Application).filter(Application.id == app_id).one() except NoResultFound: return HTTPNotFound() assert_authenticated_user_is_registered(request) if app.user != request.user: return HTTPUnauthorized() schema = FullApplicationSchema() button1 = Button('submit', _('Save application')) button1.css_class = 'btn-primary' button2 = Button('delete', _('Delete application')) button2.css_class = 'btn-danger' button3 = Button('cancel', _('Cancel')) button3.css_class = 'btn-default' form = Form(schema, buttons=(button1, button2, button3)) if 'submit' in request.POST: controls = request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure as e: return {'form': e.render(), 'app': app} # the data is fine, save into the db app.name = appstruct['name'] app.main_url = appstruct['main_url'] app.callback_url = appstruct['callback_url'] app.authorized_origins = appstruct['authorized_origins'] app.production_ready = appstruct['production_ready'] app.image_url = appstruct['image_url'] app.description = appstruct['description'] Session.add(app) request.session.flash(_('The changes were saved successfully'), 'success') return HTTPFound( location=request.route_path('oauth2_developer_applications')) elif 'delete' in request.POST: return HTTPFound( location=request.route_path('oauth2_developer_application_delete', app=app.id)) elif 'cancel' in request.POST: return HTTPFound( location=request.route_path('oauth2_developer_applications')) # this is a GET return { 'form': form.render({ 'name': app.name, 'main_url': app.main_url, 'callback_url': app.callback_url, 'authorized_origins': app.authorized_origins, 'production_ready': app.production_ready, 'image_url': app.image_url, 'description': app.description, 'client_id': app.id, 'client_secret': app.secret, }), 'app': app, }
def register_new_user(request): try: user_info = request.session['user_info'] except KeyError: return HTTPBadRequest('Missing user info in the session') try: next_url = request.session['next_url'] except KeyError: next_url = request.route_url('oauth2_clients') schema = NewUserSchema() button1 = Button('submit', _('Register into Yith Library')) button1.css_class = 'btn-primary' button2 = Button('cancel', _('Cancel')) button2.css_class = 'btn-default logout' form = Form(schema, buttons=(button1, button2)) if 'submit' in request.POST: controls = request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure as e: return { 'form': e.render(), 'provider': user_info.get('provider', ''), 'email': user_info.get('email', ''), 'next_url': next_url, } email = appstruct['email'] if email != '' and email == user_info['email']: email_verified = True else: email_verified = False user_attrs = { 'screen_name': appstruct['screen_name'], 'first_name': appstruct['first_name'], 'last_name': appstruct['last_name'], 'email': email, 'email_verified': email_verified, } if request.google_analytics.is_in_session(): allow_analytics = request.google_analytics.show_in_session() user_attrs[analytics.USER_ATTR] = allow_analytics request.google_analytics.clean_session() user = User(**user_attrs) provider = user_info['provider'] external_id = user_info['external_id'] user.add_identity(provider, external_id) Session.add(user) if not email_verified and email != '': evc = EmailVerificationCode() user.email_verification_code = evc.code link = request.route_url('user_verify_email') evc.send(request, user, link) del request.session['user_info'] if 'next_url' in request.session: del request.session['next_url'] Session.flush() request.session['current_provider'] = provider return HTTPFound(location=next_url, headers=remember(request, str(user.id))) elif 'cancel' in request.POST: del request.session['user_info'] if 'next_url' in request.session: del request.session['next_url'] return HTTPFound(location=next_url) return { 'form': form.render({ 'first_name': user_info.get('first_name', ''), 'last_name': user_info.get('last_name', ''), 'screen_name': user_info.get('screen_name', ''), 'email': user_info.get('email', ''), }), 'provider': user_info.get('provider', ''), 'email': user_info.get('email', ''), 'next_url': next_url, }
def developer_application_edit(request): try: app_id = bson.ObjectId(request.matchdict['app']) except bson.errors.InvalidId: return HTTPBadRequest(body='Invalid application id') assert_authenticated_user_is_registered(request) app = request.db.applications.find_one(app_id) if app is None: return HTTPNotFound() if app['owner'] != request.user['_id']: return HTTPUnauthorized() schema = FullApplicationSchema() button1 = Button('submit', _('Save application')) button1.css_class = 'btn-primary' button2 = Button('delete', _('Delete application')) button2.css_class = 'btn-danger' button3 = Button('cancel', _('Cancel')) button3.css_class = '' form = Form(schema, buttons=(button1, button2, button3)) if 'submit' in request.POST: controls = request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure as e: return {'form': e.render(), 'app': app} # the data is fine, save into the db application = { 'owner': request.user['_id'], 'name': appstruct['name'], 'main_url': appstruct['main_url'], 'callback_url': appstruct['callback_url'], 'authorized_origins': appstruct['authorized_origins'], 'production_ready': appstruct['production_ready'], 'image_url': appstruct['image_url'], 'description': appstruct['description'], 'client_id': app['client_id'], 'client_secret': app['client_secret'], } request.db.applications.update({'_id': app['_id']}, application, safe=True) request.session.flash(_('The changes were saved successfully'), 'success') return HTTPFound( location=request.route_path('oauth2_developer_applications')) elif 'delete' in request.POST: return HTTPFound( location=request.route_path('oauth2_developer_application_delete', app=app['_id'])) elif 'cancel' in request.POST: return HTTPFound( location=request.route_path('oauth2_developer_applications')) # this is a GET return {'form': form.render(app), 'app': app}
def contact(request): button1 = Button('submit', _('Send message')) button1.css_class = 'btn-primary' button2 = Button('cancel', _('Cancel')) button2.css_class = '' form = Form(ContactSchema(), buttons=(button1, button2)) if 'submit' in request.POST: controls = request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure as e: return {'form': e.render()} context = {'link': request.route_url('contact')} context.update(appstruct) text_body = render('yithlibraryserver:templates/email_contact.txt', context, request=request) # chamaleon txt templates are rendered as utf-8 bytestrings text_body = text_body.decode('utf-8') html_body = render('yithlibraryserver:templates/email_contact.pt', context, request=request) admin_emails = request.registry.settings['admin_emails'] if admin_emails: message = Message( subject=("%s sent a message from Yith's contact form" % appstruct['name']), recipients=request.registry.settings['admin_emails'], body=text_body, html=html_body, extra_headers={'Reply-To': appstruct['email']}, ) get_mailer(request).send(message) else: log.error( '%s <%s> tried to send a message from the contact form but no ' 'admin emails were configured. Message: %s' % ( appstruct['name'], appstruct['email'], appstruct['message'], ) ) request.session.flash( _('Thank you very much for sharing your opinion'), 'info', ) return HTTPFound(location=request.route_path('home')) elif 'cancel' in request.POST: return HTTPFound(location=request.route_path('home')) initial = {} if request.user is not None: initial['name'] = request.user.get('first_name', '') if request.user.get('email_verified', False): initial['email'] = request.user.get('email', '') return {'form': form.render(initial)}