def subscribe_newsletter(request: Request): schema = NewsletterSubscriptionSchema().bind(request=request) form = deform.Form(schema) # User submitted this form if request.method == "POST": if 'subscribe' in request.POST: try: appstruct = form.validate(request.POST.items()) email = appstruct["email"] subscribe_email(request, email) # Thank user and take him/her to the next page messages.add( request, kind="info", html=True, msg= "<strong>{}</strong> has been subscribed to the newsletter." .format(email)) return HTTPFound(request.route_url("home")) except deform.ValidationFailure as e: # Render a form version where errors are visible next to the fields, # and the submitted values are posted back messages.add(request, kind="error", msg="Email was not valid") return HTTPFound(request.route_url("home")) else: # We don't know which control caused form submission return HTTPBadRequest("Unknown form button pressed") return HTTPBadRequest("POST-only endpoint")
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()
def subscribe_newsletter(request: Request): """Newsletter Subscription view.""" schema = NewsletterSubscriptionSchema().bind(request=request) form = deform.Form(schema) # In case of validation error, we return the user to the form came_from = request.referer or request.route_url('home') if request.method != "POST": return HTTPBadRequest("POST-only endpoint") # User submitted this form if 'subscribe' in request.POST: try: appstruct = form.validate(request.POST.items()) email = appstruct["email"] came_from = appstruct["came_from"] subscribe_email(request, email) # Thank user and take them to the next page msg = "<strong>{email}</strong> has been subscribed to the newsletter.".format(email=email) msg_class = 'info' messages.add(request, kind=msg_class, msg=msg, html=True) except deform.ValidationFailure: # Render a form version where errors are visible next to the fields, # and the submitted values are posted back msg = "Email was not valid." msg_class = 'error' messages.add(request, kind=msg_class, msg=msg) return HTTPFound(came_from) else: # We don't know which control caused form submission return HTTPBadRequest("Unknown form button pressed")
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": 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()
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]
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()}
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()
def start_email_login(request: Request, email: str, next_url: Optional[str] = None, extras: Optional[dict] = None): request.session["email"] = email token, data = set_verification_token(request, "email", email, next_url=next_url, extras=extras) verify_link = request.route_url("verify_email_login", token=token) verify_minutes = int( int( request.registry.settings.get( "magiclink.email_token_expiration_seconds", 300)) / 60) logger.info("Sending email login verification email to %s, next url: %s", email, next_url) send_templated_mail( request, [email], "magiclogin/email/verify_email", dict(verify_link=verify_link, verify_minutes=verify_minutes))