Beispiel #1
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":

        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()
Beispiel #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()
Beispiel #3
0
    def is_id(val):
        """Try guess if the value is valid base64 UUID slug or not.

        Note that some view names can be valid UUID slugs, thus we might hit database in any case for the view lookup.
        """
        try:
            slug.slug_to_uuid(val)
            return True
        except SlugDecodeError:
            # bytes is not 16-char string
            return False
Beispiel #4
0
    def is_id(val):
        """Try guess if the value is valid base64 UUID slug or not.

        Note that some view names can be valid UUID slugs, thus we might hit database in any case for the view lookup.
        """
        try:
            slug.slug_to_uuid(val)
            return True
        except SlugDecodeError:
            # bytes is not 16-char string
            return False
Beispiel #5
0
    def activate(self):
        """View to activate user after clicking email link."""

        code = self.request.matchdict.get('code', None)
        user_id = self.request.matchdict.get('user_id', None)
        User = get_user_class(self.request.registry)
        activation = self.Activation.get_by_code(self.request, code)

        if activation:
            user_uuid = slug_to_uuid(user_id)
            user = self.request.dbsession.query(User).filter_by(uuid=user_uuid).first()

            if not user or (user.activation != activation):
                return HTTPNotFound()

            if user:
                self.db.delete(activation)
                self.db.flush()

                if self.login_after_activation:
                    return authenticated(self.request, user)
                else:
                    self.request.registry.notify(RegistrationActivatedEvent(self.request, user, activation))
                    return HTTPFound(location=self.after_activate_url)

        return HTTPNotFound()
Beispiel #6
0
def test_edit_choice_question(browser: DriverAPI, tutorial_req, web_server, dbsession):
    """Change choice's assigned question in edit."""

    from .tutorial import Question
    from .tutorial import Choice

    with transaction.manager:
        q = Question(question_text="What is love")
        dbsession.add(q)
        dbsession.flush()

        q2 = Question(question_text="Who shot JFK")
        dbsession.add(q2)
        dbsession.flush()
        q2_slug = uuid_to_slug(q2.uuid)

        c = Choice(choice_text="Foobar", question=q)
        dbsession.add(c)
        dbsession.flush()
        c_slug = uuid_to_slug(c.uuid)

    b = browser
    create_logged_in_user(dbsession, tutorial_req.registry, web_server, browser, admin=True)

    b.visit("{}/admin/models/choice/{}/edit".format(web_server, c_slug))
    b.select("question", q2_slug)
    b.find_by_name("save").click()

    assert b.is_element_present_by_css("#msg-changes-saved")

    with transaction.manager:
        c = dbsession.query(Choice).get(1)
        assert c.question.uuid == slug_to_uuid(q2_slug)
Beispiel #7
0
def test_edit_choice_question(browser: DriverAPI, registry, web_server,
                              dbsession):
    """Change choice's assigned question in edit."""

    from .tutorial import Question
    from .tutorial import Choice

    with transaction.manager:
        q = Question(question_text="What is love")
        dbsession.add(q)
        dbsession.flush()

        q2 = Question(question_text="Who shot JFK")
        dbsession.add(q2)
        dbsession.flush()
        q2_slug = uuid_to_slug(q2.uuid)

        c = Choice(choice_text="Foobar", question=q)
        dbsession.add(c)
        dbsession.flush()
        c_slug = uuid_to_slug(c.uuid)

    b = browser
    create_logged_in_user(dbsession, registry, web_server, browser, admin=True)

    b.visit("{}/admin/models/choice/{}/edit".format(web_server, c_slug))
    b.select("question", q2_slug)
    b.find_by_name("save").click()

    assert b.is_element_present_by_css("#msg-changes-saved")

    with transaction.manager:
        c = dbsession.query(Choice).get(1)
        assert c.question.uuid == slug_to_uuid(q2_slug)
Beispiel #8
0
    def __getitem__(self, user_id: str):

        user = self.request.dbsession.query(User).filter_by(
            uuid=slug_to_uuid(user_id)).one_or_none()
        if not user:
            raise KeyError()
        return self.get_user_wallet(user)
Beispiel #9
0
def results(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()
    choices = question.choices.order_by(Choice.votes.desc())
    return locals()
Beispiel #10
0
def results(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()
    choices = question.choices.order_by(Choice.votes.desc())
    return locals()
Beispiel #11
0
    def __getitem__(self, item):
        uuid = slug_to_uuid(item)
        uop = self.request.dbsession.query(UserCryptoOperation).get(uuid)

        if not uop:
            raise KeyError()

        if uop.user != self.wallet.user:
            raise httpexceptions.HTTPForbidden()

        return Resource.make_lineage(self, UserOperation(self.request, uop), uuid_to_slug(uop.id))
Beispiel #12
0
 def __getitem__(self, item):
     dbsession = self.request.dbsession
     crypto_account = (
         dbsession.query(CryptoAddressAccount)
         .filter_by(address=self.address.address)
         .filter_by(id=slug_to_uuid(item))
         .one_or_none()
     )
     if crypto_account:
         return self.get_user_address_asset(crypto_account)
     raise KeyError()
Beispiel #13
0
    def __getitem__(self, item):
        uuid = slug_to_uuid(item)
        uop = self.request.dbsession.query(UserCryptoOperation).get(uuid)

        if not uop:
            raise KeyError()

        if uop.user != self.wallet.user:
            raise httpexceptions.HTTPForbidden()

        return Resource.make_lineage(self, UserOperation(self.request, uop),
                                     uuid_to_slug(uop.id))
Beispiel #14
0
    def __getitem__(self, item):
        dbsession = self.request.dbsession

        try:
            crypto_account = dbsession.query(CryptoAddressAccount).filter_by(
                address=self.address.address).filter_by(
                    id=slug_to_uuid(item)).one_or_none()
            if crypto_account:
                return self.get_user_address_asset(crypto_account)
        except SlugDecodeError:
            # A view
            pass
        raise KeyError()
Beispiel #15
0
 def preprocess_cstruct_values(self, node, cstruct):
     """Decode tag's slug to uuid, in case if can't decode create a new Tag."""
     dbsession = self.get_dbsession(node)
     items = []
     for value in cstruct:
         try:
             uuid = slug_to_uuid(value)
         except SlugDecodeError:
             tag = Tag(title=value)
             dbsession.add(tag)
             dbsession.flush()
             uuid = tag.id
         items.append(uuid)
     return items
Beispiel #16
0
def decode_uuid(info: dict, request: Request, marker_string="uuid") -> bool:
    """If there is a match argument with uuid in its name convert it from Base64 encoding to UUID object.

    Example usage::

        @simple_route("/{question_uuid}", route_name="detail", custom_predicates=(decode_uuid,))
        def results(request: Request, question_uuid: UUID):
            response = "You're looking at the results of question {}."
            return Response(response.format(question_uuid))

    """
    # TODO: Make this use the view function type annotations instead of guessing type from the name.
    match = info['match']

    for key, value in match.items():
        if marker_string in key:
            try:
                match[key] = slug_to_uuid(value)
            except SlugDecodeError as e:
                raise DecodeUUIDException("Tried to decode segment name {} value {} from base64 to UUID. Not possible.".format(key, value)) from e

    return True
Beispiel #17
0
def decode_uuid(info: dict, request: Request, marker_string="uuid") -> bool:
    """If there is a match argument with uuid in its name convert it from Base64 encoding to UUID object.

    Example usage::

        @simple_route("/{question_uuid}", route_name="detail", custom_predicates=(decode_uuid,))
        def results(request: Request, question_uuid: UUID):
            response = "You're looking at the results of question {}."
            return Response(response.format(question_uuid))

    """
    # TODO: Make this use the view function type annotations instead of guessing type from the name.
    match = info['match']

    for key, value in match.items():
        if marker_string in key:
            try:
                match[key] = slug_to_uuid(value)
            except SlugDecodeError as e:
                raise DecodeUUIDException(
                    "Tried to decode segment name {} value {} from base64 to UUID. Not possible."
                    .format(key, value)) from e

    return True
Beispiel #18
0
def test_uuid_slug():
    """Make short slugs for 64-bit UUID ids."""
    _uuid = uuid.uuid4()

    _uuid2 = slug_to_uuid(uuid_to_slug(_uuid))
    assert _uuid == _uuid2
Beispiel #19
0
 def __getitem__(self, item):
     uuid = slug_to_uuid(item)
     for addr in self.get_addresses():
         if addr.address.id == uuid:
             return addr
     raise KeyError()
Beispiel #20
0
 def __getitem__(self, item):
     uuid = slug_to_uuid(item)
     for addr in self.get_addresses():
         if addr.address.id == uuid:
             return addr
     raise KeyError()
Beispiel #21
0
    def __getitem__(self, user_id: str):

        user = self.request.dbsession.query(User).filter_by(uuid=slug_to_uuid(user_id)).one_or_none()
        if not user:
            raise KeyError()
        return self.get_user_wallet(user)
Beispiel #22
0
 def preprocess_cstruct_values(self, node, cstruct):
     """Parse incoming form values to Python objects if needed.
     """
     return [slug_to_uuid(v) for v in cstruct]