예제 #1
0
    def on_post(self, req, resp):
        """
        Creates new snack if user has not already suggested a snack
        """
        snack = req.media
        token = req.auth.split("Bearer ")[-1]

        if not snack or (not snack.get("name") or not snack.get("location")):
            resp.status = falcon.HTTP_400
            resp.body = json.dumps({
                "status": "error",
                "error": "json body containing 'name' and 'location' required"
            })
            return

        try:
            user_info = validate_token(token)
            can_suggest = check_user_suggestion(user_info["userid"])

            if can_suggest:
                # set snack expiration
                new_snack: Snack = add_snack(snack["name"], snack["location"])
                set_user_suggestion(user_info["userid"])
                resp.body = json.dumps({
                    "status": "ok",
                    "data": new_snack.to_dict()
                }, cls=DateTimeEncoder)

            else:
                resp.body = json.dumps({
                    "status": "error",
                    "error": "can only suggest one snack per month"
                })
                resp.status = falcon.HTTP_400

        except AuthorizationError:
            resp.status = falcon.HTTP_503
            resp.body = json.dumps({
                "status": "error",
                "error": [
                    "Cannot authenticate with snacks API."
                    "API key may have expired"
                ]
            })

        except BadRequestError as e:
            resp.status = falcon.HTTP_400
            resp.body = json.dumps({
                "status": "error",
                "error": str(e)
            })

        except UserNotFoundException:
            resp.status = falcon.HTTP_401
            resp.body = json.dumps({
                "status": "error",
                "error": "token not tied to user"
            })
예제 #2
0
def test_bad_token():
    fake_token = 'plookjojijijjij'

    decoded_token = validate_token(fake_token)

    assert not decoded_token

    yesterday = datetime.datetime.now() - datetime.timedelta(days=1)

    expired_token = jwt.encode(
        {
            "username": "******",
            "exp": yesterday.timestamp()
        }, properties.secret_key)

    decoded_token = validate_token(expired_token)

    assert not decoded_token
예제 #3
0
    def process_resource(self, req, resp, resource, params):
        if req.path not in self.blacklist_auth and req.method != "OPTIONS":
            if req.auth:
                token = req.auth.split("Bearer ")[-1]
                valid = validate_token(token)

                if not valid:
                    raise falcon.HTTPForbidden({
                        "status": "error",
                        "error": "Invalid bearer token"
                    })

            else:
                raise falcon.HTTPUnauthorized(json.dumps({
                    "status": "error",
                    "error": "Authorization header missing"
                }))
예제 #4
0
    def on_get(self, req, resp):
        """
        returns remaining votes for user
        """
        token = req.auth.split("Bearer ")[-1]
        try:
            user_info = validate_token(token)
            total_votes = get_user_votes(user_info["userid"])
            remaining_votes = properties.max_votes - total_votes

            resp.body = json.dumps({
                "status": "ok",
                "data": {"remaining_votes": remaining_votes}
            })
        except UserNotFoundException:
            resp.status = falcon.HTTP_401
            resp.body = json.dumps({
                "status": "error",
                "error": "token not tied to user"
            })
예제 #5
0
    def on_post(self, req, resp):
        """
        creates vote
        """
        vote = req.media

        if not vote or not vote.get("snack_id"):
            resp.status = falcon.HTTP_400
            resp.body = json.dumps({
                "status": "error",
                "error": "json body containing 'snack_id' is required"
            })

        try:
            # get user id from token
            token = req.auth.split("Bearer ")[-1]
            user_info = validate_token(token)

            total_votes = add_vote(user_info["userid"], vote["snack_id"])
            remaining_votes = properties.max_votes - total_votes

            resp.body = json.dumps({
                "status": "ok",
                "data": {
                    "remaining_votes": remaining_votes
                }
            })

        except UserNotFoundException:
            resp.status = falcon.HTTP_401
            resp.body = json.dumps({
                "status": "error",
                "error": "token not tied to user"
            })

        except VotesExceededException:
            resp.status = falcon.HTTP_400
            resp.body = json.dumps({
                "status": "error",
                "error": "Maximum votes for period exceeded"
            })
예제 #6
0
def test_round_trip_token():
    token = generate_token('test_user')
    print(token)
    decoded_token = validate_token(token)
    assert decoded_token["userid"] == "test_user"