Пример #1
0
def create_transaction_manager_aware_dbsession(request: Request) -> Session:
    """Defaut database factory for Websauna.

    Looks up database settings from the INI and creates an SQLALchemy session based on the configuration. The session is terminated on the HTTP request finalizer.
    """
    dbsession = create_dbsession(request.registry)

    def terminate_session(request):
        # Close db session at the end of the request and return the db connection back to the pool
        dbsession.close()

    request.add_finished_callback(terminate_session)

    return dbsession
Пример #2
0
def detail(request: Request):

    # Convert base64 encoded UUID string from request path to Python UUID object
    question_uuid = slug_to_uuid(request.matchdict["question_uuid"])

    question = request.dbsession.query(Question).filter_by(uuid=question_uuid).first()
    if not question:
        raise HTTPNotFound()

    if request.method == "POST":

        # Check that CSRF token was good
        check_csrf_token(request)

        question = request.dbsession.query(Question).filter_by(uuid=question_uuid).first()
        if not question:
            raise HTTPNotFound()

        if "choice" in request.POST:
            # Extracts the form choice and turn it to UUID object
            chosen_uuid = slug_to_uuid(request.POST["choice"])
            selected_choice = question.choices.filter_by(uuid=chosen_uuid).first()
            selected_choice.votes += 1
            messages.add(request, msg="Thank you for your vote", kind="success")
            return HTTPFound(request.route_url("results", question_uuid=uuid_to_slug(question.uuid)))
        else:
            error_message = "You did not select any choice."

    return locals()
Пример #3
0
def get_config_route(request: Request, config_key: str) -> str:
    """Route to a given URL from settings file."""
    settings = request.registry.settings

    try:
        return request.route_url(settings[config_key])
    except KeyError:
        return settings[config_key]
Пример #4
0
    def get_widget_css_urls(self, request: Request, form: Form):
        """Generate JS and CSS tags for a widget.

        For demo purposes only - you might have something specific to your application here.

        See http://docs.pylonsproject.org/projects/deform/en/latest/widget.html#the-high-level-deform-field-get-widget-resources-method
        """
        resources = form.get_widget_resources()
        css_resources = resources['css']
        css_links = [request.static_url(r) for r in css_resources]
        return css_links
Пример #5
0
    def __call__(self, request: Request):
        user = request.user

        if user:
            try:
                session_created_at = request.session["created_at"]
                if not user.is_valid_session(session_created_at):
                    request.session.invalidate()
                    messages.add(request, kind="error", msg="Your have been logged out due to authentication changes.   ", msg_id="msg-session-invalidated")
                    return HTTPFound(request.application_url)
            except sqlalchemy.orm.exc.DetachedInstanceError:
                # TODO: pyramid_tm 2.0 needed,
                # now temporary just kill user object instead of failing with an internal error, so that development server doesn't fail with CSS etc. resources
                request.user = None

        response = self.handler(request)
        return response
Пример #6
0
def registration_complete(request: Request) -> dict:
    """After activation initial login screen.

    :param request: Pyramid request.
    :return: Context to be used by the renderer.
    """
    # Create login form schema
    schema = request.registry.getUtility(ILoginSchema)
    schema = schema().bind(request=request)

    # Create login form
    form = request.registry.getUtility(ILoginForm)
    form = form(schema)

    # Make sure we POST to right endpoint
    form.action = request.route_url('login')

    return {"form": form.render()}
Пример #7
0
def login_email(request: Request):
    """Ask user email to start email sign in process."""
    schema = AskEmailSchema().bind(request=request)
    button = deform.Button(name='confirm',
                           title="Email me a link to sign in",
                           css_class="btn btn-primary btn-block")
    form = deform.Form(schema, buttons=[button])

    # User submitted this form
    if request.method == "POST":
        if 'confirm' in request.POST:
            try:

                # Where to go after user clicks the link in the email.
                # This is signaled us through Redis, set by the view that draw Sign in with email link.
                # Set by save_login_state()
                state = get_login_state(request)
                if state:
                    next_url = state.get("next_url")
                    extras = state.get("extras")
                else:
                    next_url = None  # Defaults to the referrer page
                    extras = None

                appstruct = form.validate(request.POST.items())
                start_email_login(request,
                                  appstruct["email"],
                                  next_url=next_url,
                                  extras=extras)
                return httpexceptions.HTTPFound(
                    request.route_url("login_email_sent"))
            except deform.ValidationFailure as e:
                # Render a form version where errors are visible next to the fields,
                # and the submitted values are posted back
                rendered_form = e.render()
        else:
            # We don't know which control caused form submission
            raise httpexceptions.HTTPInternalServerError(
                "Unknown form button pressed")
    else:
        # Render a form with initial values
        rendered_form = form.render()

    return locals()
Пример #8
0
def detail(request: Request):

    # Convert base64 encoded UUID string from request path to Python UUID object
    question_uuid = slug_to_uuid(request.matchdict["question_uuid"])

    question = request.dbsession.query(Question).filter_by(
        uuid=question_uuid).first()
    if not question:
        raise HTTPNotFound()

    if request.method == "POST":

        # Check that CSRF token was good
        check_csrf_token(request)

        question = request.dbsession.query(Question).filter_by(
            uuid=question_uuid).first()
        if not question:
            raise HTTPNotFound()

        if "choice" in request.POST:
            # Extracts the form choice and turn it to UUID object
            chosen_uuid = slug_to_uuid(request.POST['choice'])
            selected_choice = question.choices.filter_by(
                uuid=chosen_uuid).first()
            selected_choice.votes += 1
            messages.add(request,
                         msg="Thank you for your vote",
                         kind="success")
            return HTTPFound(
                request.route_url("results",
                                  question_uuid=uuid_to_slug(question.uuid)))
        else:
            error_message = "You did not select any choice."

    return locals()
Пример #9
0
def newsletter(context: Admin, request: Request):
    """Newsletter admin form."""
    schema = NewsletterSend().bind(request=request)

    # Create a styled button with some extra Bootstrap 3 CSS classes
    b = deform.Button(name='process',
                      title="Send",
                      css_class="btn-block btn-lg btn-primary")
    form = deform.Form(schema,
                       buttons=(b, ),
                       resource_registry=ResourceRegistry(request))

    secrets = get_secrets(request.registry)
    api_key = secrets.get("mailgun.api_key", "")
    domain = secrets.get("mailgun.domain", "")
    mailing_list = secrets.get("mailgun.mailing_list", "")
    preview_url = request.resource_url(context, "newsletter-preview")

    # TODO: Use user registry here
    User = get_user_class(request.registry)
    user_count = request.dbsession.query(User).count()

    state = NewsletterState(request)

    rendered_form = None

    # User submitted this form
    if request.method == "POST":
        if 'process' in request.POST:

            try:
                appstruct = form.validate(request.POST.items())

                if appstruct["preview"]:
                    send_newsletter(
                        request,
                        appstruct["subject"],
                        preview_email=appstruct["email"],
                        import_subscribers=appstruct["import_subscribers"])
                    messages.add(request, "Preview email sent.")
                else:
                    send_newsletter(
                        request,
                        appstruct["subject"],
                        import_subscribers=appstruct["import_subscribers"])
                    messages.add(request, "Newsletter sent.")

                return httpexceptions.HTTPFound(request.url)

            except MailgunError as e:
                # Do a form level error message
                exc = colander.Invalid(form.widget,
                                       "Could not sent newsletter:" + str(e))
                form.widget.handle_error(form, exc)

            except deform.ValidationFailure as e:
                # Render a form version where errors are visible next to the fields,
                # and the submitted values are posted back
                rendered_form = e.render()
        else:
            # We don't know which control caused form submission
            return httpexceptions.HTTPBadRequest("Unknown form button pressed")

    # Render initial form
    # Default values for read only fields
    if rendered_form is None:
        rendered_form = form.render({
            "api_key": api_key,
            "domain": domain,
            "mailing_list": mailing_list,
        })

    # This loads widgets specific CSS/JavaScript in HTML code,
    # if form widgets specify any static assets.
    form.resource_registry.pull_in_resources(request, form)

    return locals()