Exemplo n.º 1
0
class Login(form.FormBase):
    form_fields = form.Fields(ILoginForm)
    prefix = ""
    form_name = _(u"Login")
    template = NamedTemplate("alchemist.form")

    def __call__(self):
        if not IUnauthenticatedPrincipal.providedBy(self.request.principal):
            app = getSite()
            workspace = app["workspace"]
            self.request.response.redirect(
                ui_utils.url.absoluteURL(workspace, self.request))
        return super(Login, self).__call__()

    @form.action(_(u"Login"))
    def handle_login(self, action, data):
        if IUnauthenticatedPrincipal.providedBy(self.request.principal):
            self.status = _(u"Invalid account credentials")
        else:
            site_url = ui_utils.url.absoluteURL(getSite(), self.request)
            camefrom = self.request.get('camefrom', site_url + '/')
            self.status = _("You are now logged in")
            self.request.response.redirect(camefrom)
Exemplo n.º 2
0
class ReorderForm(PageForm):
    """Item reordering form.

    We use an intermediate list of ids to represent the item order.

    Note that this form must be subclassed with the ``save_ordering``
    method overriden.
    """
    class IReorderForm(interface.Interface):
        ordering = schema.List(title=u"Ordering", value_type=schema.TextLine())

    template = NamedTemplate("alchemist.form")
    form_name = _(u"Item reordering")
    form_fields = formlib.form.Fields(IReorderForm, render_context=True)

    def setUpWidgets(self, ignore_request=False):
        class context:
            ordering = list(self.context)

        self.adapters = {
            self.IReorderForm: context,
        }

        self.widgets = formlib.form.setUpWidgets(self.form_fields,
                                                 self.prefix,
                                                 self.context,
                                                 self.request,
                                                 form=self,
                                                 adapters=self.adapters,
                                                 ignore_request=ignore_request)

    def save_ordering(self, ordering):
        raise NotImplementedError("Must be defined by subclass")

    @formlib.form.action(_(u"Save"), name="save")
    def handle_save(self, action, data):
        self.save_ordering(data["ordering"])
Exemplo n.º 3
0
class RestoreLogin(form.FormBase):
    form_fields = form.Fields(IRestoreLoginForm)
    prefix = ""
    form_name = _(u"Restore Login")

    template = NamedTemplate("alchemist.form")

    def __call__(self):
        if not IUnauthenticatedPrincipal.providedBy(self.request.principal):
            app = getSite()
            workspace = app["workspace"]
            self.request.response.redirect(
                ui_utils.url.absoluteURL(workspace, self.request))

        return super(RestoreLogin, self).__call__()

    @form.action(_(u"Restore"), name="restore")
    def handle_restore(self, action, data):
        email = data.get("email", "")
        if email:
            app = BungeniApp()
            settings = EmailSettings(app)
            session = Session()
            user = session.query(User).filter(User.email == email).first()
            if user:
                mailer = getUtility(IBungeniMailer)
                self.message = _(u"Your login is: ") + user.login

                text = ViewPageTemplateFile("templates/mail.pt")(self)
                message = MIMEText(text)
                message.set_charset("utf-8")
                message["Subject"] = _(u"Bungeni login restoration")
                message["To"] = email
                mailer.send(message)
                self.status = _(u"Your login was sent to you email.")
            else:
                self.status = _(u"Wrong email address.")
Exemplo n.º 4
0
class ChangePasswordForm(BaseForm):
    form_fields = form.Fields(IChangePasswordForm)
    
    prefix = ""
    form_name = _("change_password_form_title", 
        default=u"Change password")
    
    # !+ only used here [ bungeni.ui.login.Login ] ?
    template = NamedTemplate("alchemist.form")
    
    def __init__(self, *args, **kwargs):
        super(ChangePasswordForm, self).__init__(*args, **kwargs)
        self.session = Session()
        self.user = get_db_user(self.context)
            
    def __call__(self):
        if IUnauthenticatedPrincipal.providedBy(self.request.principal):
            self.request.response.redirect(
                        ui_utils.url.absoluteURL(
                        getSite(), self.request)+"/login"
                        )
        return super(ChangePasswordForm, self).__call__()
    
    @form.action(_("label_change_password", default=u"Change password"), 
        name="change_password")
    def save_password(self, action, data):
        password = data.get("pswd","")
        confirm_password= data.get("confirm_password","")
        
        if password:
            if password != confirm_password:
                self.status = _("Password confirmation failed")
                return
            self.user._password = password
        
        self.status = _("Password changed")
Exemplo n.º 5
0
class OAuthAuthorizeForm(form.FormBase):
    class IOAuthAuthorizeForm(interface.Interface):
        client_id = schema.TextLine(required=False)
        state = schema.TextLine(required=False)
        time = schema.TextLine(required=False)
        nonce = schema.TextLine(required=False)

    form_fields = form.Fields(IOAuthAuthorizeForm)
    form_fields["client_id"].custom_widget = widgets.HiddenTextWidget
    form_fields["state"].custom_widget = widgets.HiddenTextWidget
    form_fields["nonce"].custom_widget = widgets.HiddenTextWidget
    form_fields["time"].custom_widget = widgets.HiddenTextWidget
    template = NamedTemplate("alchemist.form")
    form_name = _("authorise_oauth_application",
                  default=u"Authorise OAuth Application")

    def __init__(self, context, request, parameters={}):
        self.parameters = parameters
        if self.parameters:
            self.parameters["time"] = time.time()
            self.parameters["nonce"] = self.generate_nonce(
                self.parameters["client_id"], self.parameters["time"])
        self.action_url = "/oauth/authorize-form"
        super(OAuthAuthorizeForm, self).__init__(context, request)

    def __call__(self):
        authorization_token = self.check_authorization()
        if authorization_token:
            redirect_uri = self.get_redirect_uri(
                authorization_token, self.request.form.get("state", None))

            self.request.response.redirect(redirect_uri, trusted=True)
        else:
            return super(OAuthAuthorizeForm, self).__call__()

    def get_authorization_token(self, authorization):
        authorization_token = domain.OAuthAuthorizationToken()
        authorization_token.authorization = authorization
        authorization_token.authorization_code = get_key()
        authorization_token.expiry = datetime.now() + timedelta(
            seconds=capi.oauth_authorization_token_expiry_time)
        authorization_token.refresh_token = get_key()
        return authorization_token

    def check_authorization(self):
        session = Session()
        client_id = self.request.form.get("client_id", None)
        user = get_login_user()
        if client_id:
            try:
                authorization = session.query(domain.OAuthAuthorization).join(
                    domain.OAuthApplication).filter(
                        sa.and_(
                            domain.OAuthApplication.identifier == client_id,
                            domain.OAuthAuthorization.user_id ==
                            user.user_id)).one()
                authorization_token = self.get_authorization_token(
                    authorization)
                session.add(authorization_token)
                return authorization_token
            except NoResultFound:
                return None
        return None

    def setUpWidgets(self, ignore_request=False):
        self.widgets = form.setUpWidgets(
            self.form_fields,
            "",
            self.context,
            self.request,
            data=self.parameters if self.parameters else self.request.form,
            ignore_request=ignore_request)

    def generate_nonce(self, client_id, auth_time):
        data = "{0}:{1}:{2}".format(client_id,
                                    get_login_user().user_id, auth_time)
        return hmac.new(capi.oauth_hmac_key, data, hashlib.sha1).hexdigest()

    def verify_data(self, action, data):
        errors = []
        for key, value in self.request.form.iteritems():
            data[key] = value
        t_delta = timedelta(seconds=capi.oauth_authorization_token_expiry_time)
        auth_time = datetime.fromtimestamp(float(data["time"]))
        max_time = auth_time + t_delta
        if (datetime.now() > max_time):
            errors.append(InvalidGrant)
        nonce = self.generate_nonce(data["client_id"], data["time"])
        if data["nonce"] != nonce:
            errors.append(InvalidGrant)
        return errors

    def handle_failure(self, action, data, errors):
        return ErrorPage(self.context, self.request, errors[0])()

    def get_redirect_uri(self, authorization_token, state=None):
        redirect_uri = "{0}?code={1}".format(
            authorization_token.authorization.application.redirection_endpoint,
            authorization_token.authorization_code)
        if state:
            redirect_uri = "{0}&state={1}".format(redirect_uri, state)
        return redirect_uri

    @form.action(_(u"Authorize application"),
                 name="authorize",
                 validator=verify_data,
                 failure=handle_failure)
    def handle_authorize_app(self, action, data):
        session = Session()
        authorization = domain.OAuthAuthorization()
        authorization.user_id = get_login_user().user_id
        app = session.query(domain.OAuthApplication).filter(
            domain.OAuthApplication.identifier == data["client_id"]).one()
        authorization.application_id = app.application_id
        authorization.active = True
        session.add(authorization)
        authorization_token = self.get_authorization_token(authorization)
        session.add(authorization_token)
        session.flush()
        redirect_uri = self.get_redirect_uri(authorization_token,
                                             data["state"])
        self.request.response.redirect(redirect_uri, trusted=True)

    @form.action(_(u"Cancel"), name="cancel")
    def handle_cancel(self, action, data):
        session = Session()
        app = session.query(domain.OAuthApplication).filter(
            domain.OAuthApplication.application_identifier ==
            data["client_id"]).one()
        error = UnauthorizedClient(app.redirection_endpoint, data["state"])
        redirect_error(self.context, self.request, error)
Exemplo n.º 6
0
class LoginBase(form.FormBase):
    template = NamedTemplate("alchemist.form")
    prefix = ""
Exemplo n.º 7
0
class DeleteForm(PageForm):
    """Delete-form for Bungeni content.

    Confirmation

        The user is presented with a confirmation form which details
        the items that are going to be deleted.

    Subobjects

        Recursively, a permission check is carried out for each item
        that is going to be deleted. If a permission check fails, an
        error message is displayed to the user.

    Will redirect back to the container on success.
    """
    # zpt
    # !+form_template(mr, jul-2010) this is unused here, but needed by
    # some adapter of this "object delete" view
    form_template = NamedTemplate("alchemist.form")
    template = ViewPageTemplateFile("templates/delete.pt")

    _next_url = None
    form_fields = formlib.form.Fields()

    def _can_delete_item(self, action):
        return True

    def nextURL(self):
        return self._next_url

    def update(self):
        self.subobjects = self.get_subobjects()
        super(DeleteForm, self).update()

    def get_subobjects(self):
        return ()

    def delete_subobjects(self):
        return 0

    @formlib.form.action(_(u"Delete"), condition=_can_delete_item)
    def handle_delete(self, action, data):
        count = self.delete_subobjects()
        container = self.context.__parent__
        trusted = removeSecurityProxy(self.context)
        session = Session()
        session.delete(trusted)
        count += 1

        try:
            session.flush()
        except IntegrityError, e:
            # this should not happen in production; it's a critical
            # error, because the transaction might have failed in the
            # second phase of the commit
            session.rollback()
            log.critical(e)

            self.status = _(u"Could not delete item due to "
                            "database integrity error")

            return self.render()
        # !+SESSION_CLOSE(taras.sterch, july-2011) there is no need to close the
        # session. Transaction manager will take care of this. Hope it does not
        # brake anything.
        #session.close()

        #TODO: check that it is removed from the index!
        notify(
            ObjectRemovedEvent(self.context,
                               oldParent=container,
                               oldName=self.context.__name__))
        # we have to switch our context here otherwise the deleted object will
        # be merged into the session again and reappear magically
        self.context = container
        next_url = self.nextURL()

        if next_url is None:
            next_url = url.absoluteURL(container, self.request) + \
                       "/?portal_status_message=%d items deleted" % count

        self.request.response.redirect(next_url)
Exemplo n.º 8
0
class PageForm(BaseForm, formlib.form.PageForm, browser.BungeniBrowserView):
    template = NamedTemplate("alchemist.form")
Exemplo n.º 9
0
class DynamicFields( object ):

    mode = None # required string attribute
    template = NamedTemplate('alchemist.form')
    form_fields = form.Fields()

    def getDomainModel( self ):
        return getattr( self.context, 'domain_model', self.context.__class__)
    
    def update( self ):
        """
        override update method to setup fields dynamically before widgets are
        setup and actions called.
        """
        domain_model = self.getDomainModel()
        self.form_fields = setUpFields( domain_model, self.mode )
        super( DynamicFields, self).update()
        setWidgetErrors( self.widgets, self.errors )
        
    @property
    def form_name( self ):
        # play nice w/ containers or content views, or content
        domain_model = getattr( self.context, 'domain_model', None)
        if domain_model is None:
            domain_model = getattr( self, 'domain_model', None)
            if domain_model is None and IAlchemistContent.providedBy( self.context ):
                domain_model = self.context.__class__
        if domain_model is None:
            return self.mode.title()
        return "%s %s"%(self.mode.title(), domain_model.__name__)

    def splitwidgets( self ):
        """
        return two lists of form fields split into two, int overflow into
        first column.
        """
        # give first and second set of field names
        field_count = len( self.form_fields )
        first_half_count = math.ceil( field_count / 2.0 )
        first_half_widgets, second_half_widgets = [], []
        
        for idx, field in itertools.izip( itertools.count(), self.form_fields ):
            if idx < first_half_count:
                first_half_widgets.append( self.widgets[ field.__name__ ] )
            else:
                second_half_widgets.append( self.widgets[ field.__name__ ] )

        return first_half_widgets, second_half_widgets

    def validateUnique( self, action, data ):
        """
        verification method for adding or editing against anything existing
        that conflicts with an existing row, as regards unique column constraints.
        
        this is somewhat costly as we basically reinvoke parsing form data twice,
        we need to extend zope.formlib to ignore existing values in the data dictionary
        to avoid this.
        
        its also costly because we're doing a query per unique column data we find, in
        order to unambigously identify the field thats problematic. but presumably those
        are very fast due to the unique constraint.
        
        TODO : assumes column == attribute         
        """
        errors = form.getWidgetsData( self.widgets, self.prefix, data ) + \
                 form.checkInvariants(self.form_fields, data) 
        if errors:
            return errors
        
        domain_model = removeSecurityProxy( self.getDomainModel() )
        
        # find unique columns in data model.. TODO do this statically
        mapper = orm.class_mapper( domain_model  )
        ucols = list( unique_columns( mapper ) )

        errors = []
        # query out any existing values with the same unique values,
        
        s = Session()        
        # find data matching unique columns
        for key, col in ucols:
            if key in data:
                # on edit ignore new value if its the same as the previous value
                if isinstance( self.context, domain_model ) \
                   and data[key] == getattr( self.context, key, None):
                   continue
                
                value = s.query( domain_model ).filter( col == data[key] ).count()
                if not value:
                    continue
                
                widget = self.widgets[ key ]
                error = form.WidgetInputError( widget.name, 
                                               widget.label, 
                                              u"Duplicate Value for Unique Field" )
                widget._error = error
                errors.append( error )
        
        if errors:
            return tuple(errors)
Exemplo n.º 10
0
class OAuthAuthorizeForm(form.FormBase):
    form_fields = form.Fields(IOAuthAuthorizeForm)
    form_fields["client_id"].custom_widget = widgets.HiddenTextWidget
    form_fields["state"].custom_widget = widgets.HiddenTextWidget
    form_fields["nonce"].custom_widget = widgets.HiddenTextWidget
    form_fields["time"].custom_widget = widgets.HiddenTextWidget
    template = NamedTemplate("alchemist.form")
    form_name = _("authorise_oauth_application",
        default=u"Authorise OAuth Application")

    def __init__(self, context, request, parameters={}):
        self.parameters = parameters
        if self.parameters:
            self.parameters["time"] = time.time()
            self.parameters["nonce"] = self.generate_nonce(
                self.parameters["time"])
        self.action_url = "/api/oauth/authorize-form"
        super(OAuthAuthorizeForm, self).__init__(context, request)

    def setUpWidgets(self, ignore_request=False):
        
        self.widgets = form.setUpWidgets(
            self.form_fields, self.prefix, self.context, self.request,
            data=self.parameters if self.parameters else self.request.form,
            ignore_request=ignore_request
        )

    def generate_nonce(self, auth_time):
        data = "{0}:{1}:{2}".format(
            self.parameters["client_id"], get_db_user().user_id, auth_time)
        return hmac.new(capi.oauth_hmac_key, data, hashlib.sha1).hexdigest()

    def check_authorization(self, action, data):
        errors = []
        data = self.request.form
        if not data.get("form.time", None) or not data.get("form.nonce", None):
            errors.append(InvalidRequest)
            return errors
        max_time = datetime.fromtimestamp(float(data["form.time"])) + \
            timedelta(seconds=capi.oauth_authorization_token_expiry_time)
        if (datetime.now() > max_time):
            errors.append(InvalidGrant)
        if data["form.nonce"] != self.generate_nonce(data["form.time"]):
            errors.append(InvalidGrant)
        return errors

    def handle_failure(self, action, data, errors):
        return ErrorPage(self.context, self.request, errors[0])()

    @form.action(_(u"Authorize application"), name="authorize",
        validator=check_authorization, failure=handle_failure)
    def handle_authorize_app(self, action, data):
        session = Session()
        oauth_authorization = domain.OAuthAuthorization()
        oauth_authorization.user_id = get_db_user().user_id
        app = session.query(domain.OAuthApplication
            ).filter(domain.OAuthApplication.identifier ==
                data["client_id"]
            ).one()
        oauth_authorization.application_id = app.application_id
        oauth_authorization.authorization_code = get_key()
        oauth_authorization.expiry = datetime.now() + timedelta(
            seconds=capi.oauth_authorization_token_expiry_time)
        oauth_authorization.active = True
        session.add(oauth_authorization)
        redirect_uri = "{0}?code={1}".format(
            app.redirection_endpoint, oauth_authorization.authorization_code)
        if data.get("state", None):
            redirect_uri = "{0}&state={1}".format(redirect_uri,  data["state"])
        self.request.response.redirect(redirect_uri, trusted=True)

    @form.action(_(u"Cancel"), name="cancel")
    def handle_cancel(self, action, data):
        session = Session()
        app = session.query(domain.OAuthApplication
            ).filter(domain.OAuthApplication.application_identifier
                     == data["client_id"]
            ).one()
        error = UnauthorizedClient(app.redirection_endpoint, data["state"])
        redirect_error(self.context, self.request, error)
Exemplo n.º 11
0
class ContentViewletManager(manager.ViewletManagerBase):
    template = NamedTemplate('alchemist.content')
Exemplo n.º 12
0
class AttributesViewViewlet(core.DynamicFields, DisplayFormViewlet):

    mode = "view"
    template = NamedTemplate('alchemist.subform')
    form_name = _(u"General")
Exemplo n.º 13
0
class ArchiveDatesForm(form.PageForm):

    status = None
    
    class IDateRangeSchema(interface.Interface):
        range_start_date = schema.Date(
            title=_(u"From"),
            description=_(u"Leave blank or set lower limit"),
            required=False)

        range_end_date = schema.Date(
            title=_(u"To"),
            description=_(u"Leave blank or set upper limit"),
            required=False)

        parliament = schema.Choice(
            title=_(u"Or select"),
            description=_(u"Set date range to that of a given particular parliament"),
            vocabulary="bungeni.vocabulary.ParliamentSource",
            required=False)

    template = NamedTemplate('alchemist.subform')
    form_fields = form.Fields(IDateRangeSchema, render_context=True)
    form_fields['range_start_date'].custom_widget = DateWidget
    form_fields['range_end_date'].custom_widget = DateWidget
    form_description = _(u"Filter the archive by date range")

    def is_in_parliament(self, context):
        parent = context
        while not IParliament.providedBy(parent):
            parent = getattr(parent, '__parent__', None)
            if parent is None:
                return False
        return True
            
    def get_start_end_restictions(self, context):
        parent = context
        while not hasattr(parent,'start_date'):
            parent = getattr(parent, '__parent__', None)
            if parent is None:
                return None, None
        return getattr(parent, 'start_date', None), getattr(parent, 'end_date', None)

    def setUpWidgets(self, ignore_request=False, cookie=None):
        if ignore_request is False:
            start_date, end_date = get_date_range(self.request)
        else:
            start_date = end_date = None

        context = type("context", (), {
            'range_start_date': start_date,
            'range_end_date': end_date,
            'parliament': None})

        self.adapters = {
            self.IDateRangeSchema: context,
            }
        if self.is_in_parliament(self.context):
            self.form_fields = self.form_fields.omit('parliament')
            
        self.widgets = form.setUpWidgets(
            self.form_fields, self.prefix, self.context, self.request,
            form=self, adapters=self.adapters, ignore_request=True)
        try:
            self.widgets['parliament']._messageNoValue = _(
                u"parliament...")
        except KeyError:
            pass
        start, end = self.get_start_end_restictions(self.context)
        self.widgets['range_start_date'].set_min_date(start)
        self.widgets['range_end_date'].set_min_date(start)
        self.widgets['range_start_date'].set_max_date(end)
        self.widgets['range_end_date'].set_max_date(end)
        
        
    @form.action(_(u"Filter"))
    def handle_filter(self, action, data):
        start_date = data.get('range_start_date')
        end_date = data.get('range_end_date')
        params = {}

        if start_date and end_date:
            if start_date > end_date:
                self.status = _("Invalid Date Range")
                unset_date_range(self.request)
                return
        start, end = self.get_start_end_restictions(self.context)
        if start_date and end:
            if start_date > end:
                  self.status = (_("Start date must be before %s") %
                        end.strftime("%d %B %Y"))
                  unset_date_range(self.request)
                  return
        if end_date and start:
            if end_date < start:
                  self.status = (_("End date must be after %s") %
                        start.strftime("%d %B %Y"))
                  unset_date_range(self.request)
                  return
                                
        set_date_range(self.request, start_date, end_date)
        self.request.response.redirect(
            "?portal_status_message=%s" % translate(
                _(u"Date range set")))

    @form.action(_(u"Clear"))
    def handle_clear(self, action, data):
        unset_date_range(self.request)
        
        self.request.response.redirect(
            "?portal_status_message=%s" % translate(
                _(u"Date range cleared")))
Exemplo n.º 14
0
class GenerateDebateRecordTakes(BungeniBrowserView, ui.BaseForm):
    """View to generate takes
    """
    form_fields = []
    template = NamedTemplate("alchemist.subform")

    def __init__(self, context, request):
        if IDebateTakeContainer.providedBy(context):
            self.context = removeSecurityProxy(context).__parent__
        else:
            self.context = removeSecurityProxy(context)
        self.prm = IPrincipalRoleMap(self.context)
        self.request = request
        #super(GenerateDebateRecordTakes, self).__init__(context, request)

    def get_take_duration(self):
        return component.getUtility(IDebateRecordConfig).get_take_duration()

    def get_transcriber_role(self):
        return component.getUtility(IDebateRecordConfig).get_transcriber_role()

    def get_transcribers(self):
        transcribers = []
        transcriber_role = self.get_transcriber_role()
        users = common.get_local_users_for_subrole(transcriber_role)
        for user in users:
            if self.user_is_assigned(user.login, transcriber_role):
                transcribers.append(user)
        return transcribers

    def user_is_assigned(self, user_login, role_id):
        if self.prm.getSetting(role_id, user_login) == Allow:
            return True
        return False

    def get_take_name(self, take_count):
        take_name_prefix = ""
        b_take_count = take_count
        while (take_count / 26):
            take_count = take_count / 26
            take_name_prefix = take_name_prefix + chr(64 + take_count)
        return take_name_prefix + chr(65 + (b_take_count % 26))

    def has_no_takes(self, action=None):
        return False if len(self.context.debate_takes) > 0 else True

    @formlib.form.action(label=_("Generate takes"),
                         name="generate",
                         condition=has_no_takes)
    def handle_generate_takes(self, action, data):
        transcribers = self.get_transcribers()
        next_url = url.absoluteURL(self.context, self.request)
        if not transcribers:
            return self.request.response.redirect(next_url + "/takes")
        sitting = self.context.sitting
        take_time_delta = datetime.timedelta(seconds=self.get_take_duration())
        current_end_time = sitting.start_date
        current_start_time = sitting.start_date
        take_count = 0
        session = Session()
        while current_end_time < sitting.end_date:
            take = domain.DebateTake()
            take.debate_record_id = self.context.debate_record_id
            take.start_date = current_start_time
            if ((current_end_time + take_time_delta) > sitting.end_date):
                current_end_time = sitting.end_date
            else:
                current_end_time = current_end_time + take_time_delta
                current_start_time = current_end_time + datetime.timedelta(
                    seconds=1)
            take.end_date = current_end_time
            take.transcriber_id = transcribers[take_count %
                                               len(transcribers)].user_id
            take.debate_take_name = self.get_take_name(take_count)
            take_count = take_count + 1
            session.add(take)
        session.flush()
        return self.request.response.redirect(next_url + "/takes")
Exemplo n.º 15
0
class DocumentEditForm(EditForm):
    form_fields = Fields(ISimpleDocument)
    label = u"Edit document"

    template = NamedTemplate('simpledocument.form')
Exemplo n.º 16
0
class PageForm(BaseForm, form.PageForm):
    template = NamedTemplate('alchemist.form')
Exemplo n.º 17
0
class PageForm(BaseForm, formlib.form.PageForm, browser.BungeniBrowserView):
    #template = z3evoque.PageViewTemplateFile("form.html#page")
    template = NamedTemplate("alchemist.form")
Exemplo n.º 18
0
class RestorePassword(form.FormBase):
    form_fields = form.Fields(IRestorePasswordForm)
    prefix = ""
    form_name = _(u"Restore Password")
    
    template = NamedTemplate("alchemist.form")
    
    def __call__(self):
        if not IUnauthenticatedPrincipal.providedBy(self.request.principal):
            app = getSite()
            workspace = app["workspace"]
            self.request.response.redirect(
                        ui_utils.url.absoluteURL(workspace, self.request))
            
        return super(RestorePassword, self).__call__()
            
    @form.action(_(u"Restore"), name="restore")
    def handle_restore(self, action, data):
        site_url = ui_utils.url.absoluteURL(getSite(), self.request)
        login = data.get("login", "")
        email = data.get("email", "")
        user = None
            
        app = BungeniApp()
        settings = EmailSettings(app)
            
        session = Session()
        if email:
            user = session.query(User).filter(
                                User.email==email).first()
        elif login:
            user = session.query(User).filter(
                                User.login==login).first()
                                    
        if user:
            email = user.email
            link = session.query(PasswordRestoreLink).filter(
                PasswordRestoreLink.user_id==user.user_id).first()
            if link:
                if not link.expired():
                    self.status = _(u"This user's link is still active!")
                    return
            else:
                link = PasswordRestoreLink()
                
            link.hash = hashlib.sha224(user.login + 
                                        SECRET_KEY + 
                                        str(datetime.datetime.now())).hexdigest()
            link.expiration_date = datetime.datetime.now() + datetime.timedelta(1)
            link.user_id = user.user_id
            session.add(link)
                        
            mailer = getUtility(ISMTPMailer, name="bungeni.smtp")
                
                
            self.message = _(u"Restore password link: ")\
                        + "%s/reset_password?key=%s" % (site_url, link.hash)
            self.message += u"\n\n"
            self.message += _(u"This link will expire in 24 hours.")
                
            text = ViewPageTemplateFile("templates/mail.pt")(self)
            message = MIMEText(text)
            message.set_charset("utf-8")
            message["Subject"] = _(u"Bungeni password restoration")
            message["From"] = settings.default_sender
                
            mailer.send(settings.default_sender, email, str(message))
            self.status = _(u"Email was sent!")
        else:
            self.status = _(u"User not found!")
Exemplo n.º 19
0
class DeleteForm(PageForm):
    """Delete-form for Bungeni content.

    Confirmation

        The user is presented with a confirmation form which details
        the items that are going to be deleted.

    Subobjects

        Recursively, a permission check is carried out for each item
        that is going to be deleted. If a permission check fails, an
        error message is displayed to the user.

    Will redirect back to the container on success.
    """
    form_template = NamedTemplate("alchemist.form")
    template = ViewPageTemplateFile("templates/delete.pt")
    #template = z3evoque.PageViewTemplateFile("delete.html")

    _next_url = None
    form_fields = formlib.form.Fields()

    def _can_delete_item(self, action):
        return True

    def nextURL(self):
        return self._next_url

    def update(self):
        self.subobjects = self.get_subobjects()
        super(DeleteForm, self).update()

    def get_subobjects(self):
        return ()

    def delete_subobjects(self):
        return 0

    @formlib.form.action(_(u"Delete"),
                         name="delete",
                         condition=_can_delete_item)
    def handle_delete(self, action, data):
        count = self.delete_subobjects()
        container = self.context.__parent__
        trusted = removeSecurityProxy(self.context)
        session = Session()
        session.delete(trusted)
        count += 1
        try:
            session.flush()
        except IntegrityError, e:
            # this should not happen in production; it's a critical
            # error, because the transaction might have failed in the
            # second phase of the commit
            session.rollback()
            log.critical(e)
            self.status = _(
                "Could not delete item due to database integrity error. "
                "You may wish to try deleting any related sub-records first?")
            return self.render()

        #TODO: check that it is removed from the index!
        notify(
            ObjectRemovedEvent(self.context,
                               oldParent=container,
                               oldName=self.context.__name__))
        # we have to switch our context here otherwise the deleted object will
        # be merged into the session again and reappear magically
        self.context = container
        cascade_modifications(container)
        next_url = self.nextURL()

        if next_url is None:
            next_url = url.absoluteURL(container, self.request) + \
                       "/?portal_status_message=%d items deleted" % count
        if self.is_headless:
            log.info("Deleting in headless mode - No redirection")
        else:
            self.request.response.redirect(next_url)
Exemplo n.º 20
0
class Profile(BaseForm):
    form_fields = form.Fields(IProfileForm)
    
    form_fields["gender"].custom_widget=widgets.CustomRadioWidget
    form_fields["date_of_birth"].custom_widget=widgets.DateWidget
    form_fields["description"].custom_widget=widgets.RichTextEditor
    form_fields["image"].custom_widget=widgets.ImageInputWidget
    
    prefix = ""
    form_name = _(u"Profile")
    
    # !+ only used here [ bungeni.ui.login.Login ] ?
    template = NamedTemplate("alchemist.form")
    
    def __init__(self, *args, **kwargs):
        super(Profile, self).__init__(*args, **kwargs)
        self.user = get_db_user(self.context)
        self.context = self.user
            
    def __call__(self):
        if IUnauthenticatedPrincipal.providedBy(self.request.principal):
            self.request.response.redirect(
                        ui_utils.url.absoluteURL(
                        getSite(), self.request)+"/login"
                        )
        return super(Profile, self).__call__()
    
    def setUpWidgets(self, ignore_request=False):
        super(Profile, self).setUpWidgets(ignore_request=ignore_request)
        for widget in self.widgets:
            name = widget.name
            if self.request.get(name,None) is None:
                self.widgets[name].setRenderedValue(
                                    getattr(self.user, name, None))
            else:
                self.widgets[name].setRenderedValue(
                                    self.request.get(name,None))
                if name == "gender":
                    self.widgets[name].setRenderedValue(
                                        self.request.get(name)[0])
        
    def _do_save(self, data):
        email = data.get("email","")
        first_name = data.get("first_name","")
        last_name = data.get("last_name","") 
        middle_name = data.get("middle_name","")
        description = data.get("description","")
        gender = data.get("gender","")
        image = data.get("image","")
        date_of_birth = data.get("date_of_birth","")
        birth_nationality = data.get("birth_nationality","")
        birth_country = data.get("birth_country","")
        current_nationality = data.get("current_nationality","")
                        
        if email:
            self.user.email = email
            
        if first_name:
            self.user.first_name = first_name
            
        if last_name:
            self.user.last_name = last_name
        
        if middle_name:
            self.user.middle_name = middle_name
        
        if description:
            self.user.description = description
        
        if gender:
            self.user.gender = gender
            
        if date_of_birth:
            self.user.date_of_birth = date_of_birth
            
        if image:
            self.user.image = image
            
        if birth_nationality:
            self.user.birth_nationality = birth_nationality
        
        if birth_country:
            self.user.birth_country = birth_country
        
        if current_nationality:
            self.user.current_nationality = current_nationality
                
        self.status = _("Profile data updated")
        
    @form.action(_(u"Save"), name="save",
                 condition=form.haveInputWidgets)
    def handle_edit_save(self, action, data):
        """Saves the document and goes back to edit page"""
        self._do_save(data)

    @form.action(_(u"Save and view"), name="save_and_view",
                 condition=form.haveInputWidgets)
    def handle_edit_save_and_view(self, action, data):
        """Saves the  document and redirects to its view page"""
        self._do_save(data)
        if not self._next_url:
            self._next_url = ui_utils.url.absoluteURL(self.context, self.request) + \
                "?portal_status_message= Saved"
        self.request.response.redirect(self._next_url)

    @form.action(_(u"Cancel"), name="cancel",
                 validator=ui.null_validator)
    def handle_edit_cancel(self, action, data):
        """Cancelling redirects to the listing."""
        if not self._next_url:
            self._next_url = ui_utils.url.absoluteURL(self.context, self.request)
        self.request.response.redirect(self._next_url)
Exemplo n.º 21
0
class AttributesEditViewlet(ui.core.DynamicFields, ui.viewlet.EditFormViewlet):
    mode = "edit"
    template = NamedTemplate('alchemist.subform')
    form_name = _(u"General")
Exemplo n.º 22
0
class Profile(form.FormBase):
    form_fields = form.Fields(IProfileForm)

    form_fields["gender"].custom_widget = widgets.CustomRadioWidget
    form_fields["date_of_birth"].custom_widget = widgets.DateWidget
    form_fields["description"].custom_widget = widgets.RichTextEditor
    form_fields["image"].custom_widget = widgets.ImageInputWidget

    prefix = ""
    form_name = _(u"Profile")

    # !+ only used here [ bungeni.ui.login.Login ] ?
    template = NamedTemplate("alchemist.form")

    def __init__(self, *args, **kwargs):
        super(Profile, self).__init__(*args, **kwargs)
        self.session = Session()
        user_id = get_db_user_id(self.context)
        self.user = self.session.query(User)\
                                .filter(User.user_id==user_id).first()

    def __call__(self):
        if IUnauthenticatedPrincipal.providedBy(self.request.principal):
            self.request.response.redirect(
                ui_utils.url.absoluteURL(getSite(), self.request) + "/login")
        return super(Profile, self).__call__()

    def setUpWidgets(self, ignore_request=False):
        super(Profile, self).setUpWidgets(ignore_request=ignore_request)
        self.widgets["email"].setRenderedValue(self.user.email)
        self.widgets["first_name"].setRenderedValue(self.user.first_name)
        self.widgets["last_name"].setRenderedValue(self.user.last_name)
        self.widgets["middle_name"].setRenderedValue(self.user.middle_name)
        self.widgets["description"].setRenderedValue(self.user.description)
        self.widgets["gender"].setRenderedValue(self.user.gender)
        self.widgets["image"].setRenderedValue(self.user.image)
        self.widgets["date_of_birth"].setRenderedValue(self.user.date_of_birth)
        self.widgets["birth_nationality"].setRenderedValue(
            self.user.birth_nationality)
        self.widgets["birth_country"].setRenderedValue(self.user.birth_country)
        self.widgets["current_nationality"].setRenderedValue(
            self.user.current_nationality)

    @form.action(_(u"Save"))
    def save_profile(self, action, data):
        email = data.get("email", "")
        first_name = data.get("first_name", "")
        last_name = data.get("last_name", "")
        middle_name = data.get("middle_name", "")
        description = data.get("description", "")
        gender = data.get("gender", "")
        image = data.get("image", "")
        date_of_birth = data.get("date_of_birth", "")
        birth_nationality = data.get("birth_nationality", "")
        birth_country = data.get("birth_country", "")
        current_nationality = data.get("current_nationality", "")

        if email:
            users = self.session.query(User).filter(User.email == email)
            if (users.count() == 1 and users.first().user_id == self.user.user_id) or\
                users.count() == 0:
                self.user.email = email
            else:
                self.status = _("Email already taken!")
                return

        if first_name:
            self.user.first_name = first_name

        if last_name:
            self.user.last_name = last_name

        if middle_name:
            self.user.middle_name = middle_name

        if description:
            self.user.description = description

        if gender:
            self.user.gender = gender

        if date_of_birth:
            self.user.date_of_birth = date_of_birth

        if image:
            self.user.image = image

        if birth_nationality:
            self.user.birth_nationality = birth_nationality

        if birth_country:
            self.user.birth_country = birth_country

        if current_nationality:
            self.user.current_nationality = current_nationality

        self.status = _("Profile data updated")