Ejemplo n.º 1
0
    def on_get(self, req, res, id):
        try:
            # Parse token and get user id
            user_id = parse_token(req)['sub']
            # Get the user
            user = User.get(User.id == int(user_id))
        except Exception as e:
            logger.error("Can't verify user")
            raise falcon.HTTPBadRequest(title="Bad request",
                                        description=e,
                                        href=settings.__docs__)
        try:
            service_obj = Service.get(Service.id == id)
            service = list(service_obj.select(Service.id, Service.name,
                                              Service.username, Service.password,
                                              Service.url, Service.port, Service.extra,
                                              Service.ssh_title, Service.ssh_public,
                                              Service.ssh_private, Service.ssl_title,
                                              Service.ssl_filename, Service.other)
                                      .where(Service.id == id)
                                      .dicts())
            if user not in service_obj.allowed_users:
                raise falcon.HTTPForbidden(title="Permission denied",
                                           description="You don't have access to this resource",
                                           href=settings.__docs__)

            res.status = falcon.HTTP_200
            res.body = json.dumps(service)
        except Exception as e:
            print(e)
            error_msg = ("Unable to get the items. Please try again later")
            raise falcon.HTTPServiceUnavailable(title="{0} failed".format(req.method),
                                                description=error_msg,
                                                retry_after=30,
                                                href=settings.__docs__)
Ejemplo n.º 2
0
    def on_post(self, req, res):
        try:
            # Parse token and get user id
            user_id = parse_token(req)['sub']
            # Get the user
            user = User.get(User.id == int(user_id))
        except Exception as e:
            logger.error("Can't verify user")
            raise falcon.HTTPBadRequest(title="Bad request",
                                        description=e,
                                        href=settings.__docs__)

        try:
            raw_json = req.stream.read()
            logger.debug("Got incoming JSON data")
        except Exception as e:
            logger.error("Can't read incoming data stream")
            raise falcon.HTTPBadRequest(title="Bad request",
                                        description=e,
                                        href=settings.__docs__)

        try:
            result_json = json.loads(raw_json.decode("utf-8"), encoding='utf-8')
            logger.debug(result_json)
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,
                                   'Malformed JSON',
                                   'Could not decode the request body. The '
                                   'JSON was incorrect.')

        try:
            new_share = ShareToken(user=user, token=generate_token(),
                                   resource=int(result_json.get()))
        except:
            pass
Ejemplo n.º 3
0
    def on_delete(self, req, res, id):
        try:
            # Parse token and get user id
            user_id = parse_token(req)['sub']
            # Get the user
            user = User.get(User.id == int(user_id))
        except Exception as e:
            logger.error("Can't verify user")
            raise falcon.HTTPBadRequest(title="Bad request",
                                        description=e,
                                        href=settings.__docs__)
        try:
            category = Category.get(Category.id == int(id))
            category.delete_instance(recursive=True)

            res.status = falcon.HTTP_200
            res.body = json.dumps({"status": "Deletion successful"})

        except Exception as e:
            print(e)
            error_msg = ("Unable to delete category. Please try again later.")
            raise falcon.HTTPServiceUnavailable(title="{0} failed".format(req.method),
                                                description=error_msg,
                                                retry_after=30,
                                                href=settings.__docs__)
Ejemplo n.º 4
0
def login_required(req, res, resource, params):

    """Check the token to validate login state
    Check the JWT token sent by the frontend to see if the following conditions
    are NOT met:
        - Issuer host doesn't match the one specified in the settings file
        - Expiry timestamp is lower than the current timestamp
        - Issued timestamp is lower than the current timestamp minus SESSION_EXPIRES
    :returns: Redirect to the LOGIN_URL or HTTP 200
    """
    if req.auth:
        logger.debug("The user has a token in the header")
        payload = utils.parse_token(req)
        current_time = datetime.datetime.now()
        issue_time = current_time - datetime.timedelta(hours=settings.SESSION_EXPIRES)
        if payload['iss'] != settings.SITE_DOMAIN or \
           payload['exp'] <= int(current_time.timestamp()) or \
           payload['iat'] <= int(issue_time.timestamp()):

            logger.debug("JWT token expired or malformed")
            raise falcon.HTTPError(falcon.HTTP_401, title="Credentials expired",
                                   description="Your crendentials have expired. Please login again.")

        else:
            res.status = falcon.HTTP_200
    else:
        logger.debug("No JWT token found")
        raise falcon.HTTPError(falcon.HTTP_401, title="Credentials not found",
                               description="You don't have the credentials to access this resource")
Ejemplo n.º 5
0
    def on_delete(self, req, res, id):
        try:
            # Parse token and get user id
            user_id = parse_token(req)['sub']
            # Get the user
            user = User.get(User.id == int(user_id))
        except Exception as e:
            logger.error("Can't verify user")
            raise falcon.HTTPBadRequest(title="Bad request",
                                        description=e,
                                        href=settings.__docs__)
        try:
            service = Service.get(Service.id == id)
            if user not in service.allowed_users:
                raise falcon.HTTPForbidden(
                    title="Permission denied",
                    description="You don't have access to this resource",
                    href=settings.__docs__)
            service.delete_instance()
            res.status = falcon.HTTP_200
            res.body = json.dumps({"message": "Deletion successful"})

        except Exception as e:
            print(e)
            error_msg = ("Unable to delete service. Please try again later.")
            raise falcon.HTTPServiceUnavailable(title="{0} failed".format(
                req.method),
                                                description=error_msg,
                                                retry_after=30,
                                                href=settings.__docs__)
Ejemplo n.º 6
0
    def on_delete(self, req, res, id):
        try:
            # Parse token and get user id
            user_id = parse_token(req)['sub']
            # Get the user
            user = User.get(User.id == int(user_id))
        except Exception as e:
            logger.error("Can't verify user")
            raise falcon.HTTPBadRequest(title="Bad request",
                                        description=e,
                                        href=settings.__docs__)
        try:
            item = Item.get(Item.id == int(id))
            if user not in item.allowed_users:
                raise falcon.HTTPForbidden(title="Permission denied",
                                           description="You don't have access to this resource",
                                           href=settings.__docs__)
            item.delete_instance()
            res.status = falcon.HTTP_200
            res.body = json.dumps({"message": "Deletion successful"})

        except Exception as e:
            print(e)
            error_msg = ("Unable to delete category. Please try again later.")
            raise falcon.HTTPServiceUnavailable(title="{0} failed".format(req.method),
                                                description=error_msg,
                                                retry_after=30,
                                                href=settings.__docs__)
Ejemplo n.º 7
0
    def on_delete(self, req, res, id):
        try:
            # Parse token and get user id
            user_id = parse_token(req)['sub']
            # Get the user
            user = User.get(User.id == int(user_id))
        except Exception as e:
            logger.error("Can't verify user")
            raise falcon.HTTPBadRequest(title="Bad request",
                                        description=e,
                                        href=settings.__docs__)
        try:
            category = Category.get(Category.id == int(id))
            category.delete_instance(recursive=True)

            res.status = falcon.HTTP_200
            res.body = json.dumps({"status": "Deletion successful"})

        except Exception as e:
            print(e)
            error_msg = ("Unable to delete category. Please try again later.")
            raise falcon.HTTPServiceUnavailable(title="{0} failed".format(
                req.method),
                                                description=error_msg,
                                                retry_after=30,
                                                href=settings.__docs__)
Ejemplo n.º 8
0
def login_required(req, res, resource, params):
    """Check the token to validate login state
    Check the JWT token sent by the frontend to see if the following conditions
    are NOT met:
        - Issuer host doesn't match the one specified in the settings file
        - Expiry timestamp is lower than the current timestamp
        - Issued timestamp is lower than the current timestamp minus SESSION_EXPIRES
    :returns: Redirect to the LOGIN_URL or HTTP 200
    """
    if req.auth:
        logger.debug("The user has a token in the header")
        payload = utils.parse_token(req)
        current_time = datetime.datetime.now()
        issue_time = current_time - datetime.timedelta(
            hours=settings.SESSION_EXPIRES)
        if payload['iss'] != settings.SITE_DOMAIN or \
           payload['exp'] <= int(current_time.timestamp()) or \
           payload['iat'] <= int(issue_time.timestamp()):

            logger.debug("JWT token expired or malformed")
            raise falcon.HTTPError(
                falcon.HTTP_401,
                title="Credentials expired",
                description=
                "Your crendentials have expired. Please login again.")

        else:
            res.status = falcon.HTTP_200
    else:
        logger.debug("No JWT token found")
        raise falcon.HTTPError(
            falcon.HTTP_401,
            title="Credentials not found",
            description="You don't have the credentials to access this resource"
        )
Ejemplo n.º 9
0
    def on_get(self, req, res):
        """Get the items that belong to that user.

        This method contains two behaviours, one returns
        Handle the GET request, returning a list of the items that the user
        has access to.

        First we create an empty dictionary and query the database to get
        all the item objects. After that, we iterate over the objects to
        populate the dictionary. In the end we return a 200 code to the browser
        and return the results dictionary wrapped in a list like the REsT
        standard says.
        """
        payload = {}
        # Parse token and get user id
        user_id = parse_token(req)['sub']

        try:
            # Get the user
            user = User.get(User.id == int(user_id))
            # See if we have to filter by category
            filter_category = req.get_param("category", required=False)
            if filter_category:
                # Get the category
                category = (Category.select(Category.name, Category.id)
                                  .where(Category.id == int(filter_category))
                                  .get())
                payload["category_name"] = str(category.name)
                payload["category_id"] = int(category.id)
                items = list(user.allowed_items
                                 .select(Item.name, Item.description, Item.id)
                                 .where(Item.category == int(filter_category))
                                 .dicts())
                logger.debug("Got items filtered by category and user")
            else:
                payload["category_name"] = "All"
                items = list(user.allowed_items
                             .select(Item.name, Item.description, Item.id)
                             .dicts())
                logger.debug("Got all items")
            for item in items:
                services = list(user.allowed_services
                                    .select(Service.id, Service.name)
                                    .where(Service.item == item["id"])
                                    .dicts())
                item["services"] = services
            payload["items"] = items
            res.status = falcon.HTTP_200
            res.body = json.dumps(payload)
            logger.debug("Items request succesful")
        except Exception as e:
            print(e)
            logger.error(e)
            error_msg = ("Unable to get the items. Please try again later")
            raise falcon.HTTPServiceUnavailable(title=req.method + " failed",
                                                description=error_msg,
                                                retry_after=30,
                                                href=settings.__docs__)
Ejemplo n.º 10
0
    def on_get(self, req, res):
        """Get the items that belong to that user.

        This method contains two behaviours, one returns
        Handle the GET request, returning a list of the items that the user
        has access to.

        First we create an empty dictionary and query the database to get
        all the item objects. After that, we iterate over the objects to
        populate the dictionary. In the end we return a 200 code to the browser
        and return the results dictionary wrapped in a list like the REsT
        standard says.
        """
        payload = {}
        # Parse token and get user id
        user_id = parse_token(req)['sub']

        try:
            # Get the user
            user = User.get(User.id == int(user_id))
            # See if we have to filter by category
            filter_category = req.get_param("category", required=False)
            if filter_category:
                # Get the category
                category = (Category.select(Category.name, Category.id)
                                  .where(Category.id == int(filter_category))
                                  .get())
                payload["category_name"] = str(category.name)
                payload["category_id"] = int(category.id)
                items = list(user.allowed_items
                                 .select(Item.name, Item.description, Item.id)
                                 .where(Item.category == int(filter_category))
                                 .dicts())
                logger.debug("Got items filtered by category and user")
            else:
                payload["category_name"] = "All"
                items = list(user.allowed_items
                             .select(Item.name, Item.description, Item.id)
                             .dicts())
                logger.debug("Got all items")
            for item in items:
                services = list(user.allowed_services
                                    .select(Service.id, Service.name)
                                    .where(Service.item == item["id"])
                                    .dicts())
                item["services"] = services
            payload["items"] = items
            res.status = falcon.HTTP_200
            res.body = json.dumps(payload)
            logger.debug("Items request succesful")
        except Exception as e:
            print(e)
            logger.error(e)
            error_msg = ("Unable to get the items. Please try again later")
            raise falcon.HTTPServiceUnavailable(title=req.method + " failed",
                                                description=error_msg,
                                                retry_after=30,
                                                href=settings.__docs__)
Ejemplo n.º 11
0
    def on_post(self, req, res):
        try:
            # Parse token and get user id
            user_id = parse_token(req)['sub']
            # Get the user
            user = User.get(User.id == int(user_id))
        except Exception as e:
            logger.error("Can't verify user")
            raise falcon.HTTPBadRequest(title="Bad request",
                                        description=e,
                                        href=settings.__docs__)

        try:
            raw_json = req.stream.read()
            logger.debug("Got incoming JSON data")
        except Exception as e:
            logger.error("Can't read incoming data stream")
            raise falcon.HTTPBadRequest(title="Bad request",
                                        description=e,
                                        href=settings.__docs__)

        try:
            result_json = json.loads(raw_json.decode("utf-8"),
                                     encoding='utf-8')
            logger.debug(result_json)
        except ValueError:
            raise falcon.HTTPError(
                falcon.HTTP_400, 'Malformed JSON',
                'Could not decode the request body. The '
                'JSON was incorrect.')

        try:
            new_service = Service.create(
                name=result_json.get("name"),
                item=result_json.get("item"),
                username=result_json.get("username", ''),
                password=result_json.get("password", ''),
                url=result_json.get("url", ''),
                port=result_json.get("port", 0),
                extra=result_json.get("extra", ''),
                ssh_title=result_json.get("ssh_title", ''),
                ssh_public=result_json.get("ssh_public", ''),
                ssh_private=result_json.get("ssh_private", ''),
                ssl_title=result_json.get("ssl_title", ''),
                ssl_filename=result_json.get("ssh_title", ''),
                other=result_json.get("other", ''))
            new_service.save()
            new_service.allowed_users.add(user)
        except Exception as e:
            raise falcon.HTTPInternalServerError(
                title="Error while saving the item",
                description=e,
                href=settings.__docs__)
Ejemplo n.º 12
0
    def on_post(self, req, res):
        try:
            # Parse token and get user id
            user_id = parse_token(req)['sub']
            # Get the user
            user = User.get(User.id == int(user_id))
        except Exception as e:
            logger.error("Can't verify user")
            raise falcon.HTTPBadRequest(title="Bad request",
                                        description=e,
                                        href=settings.__docs__)

        try:
            raw_json = req.stream.read()
            logger.debug("Got incoming JSON data")
        except Exception as e:
            logger.error("Can't read incoming data stream")
            raise falcon.HTTPBadRequest(title="Bad request",
                                        description=e,
                                        href=settings.__docs__)

        try:
            result_json = json.loads(raw_json.decode("utf-8"), encoding='utf-8')
            logger.debug(result_json)
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,
                                   'Malformed JSON',
                                   'Could not decode the request body. The '
                                   'JSON was incorrect.')

        try:
            new_service = Service.create(name=result_json.get("name"),
                                         item=result_json.get("item"),
                                         username=result_json.get("username", ''),
                                         password=result_json.get("password", ''),
                                         url=result_json.get("url", ''),
                                         port=result_json.get("port", 0),
                                         extra=result_json.get("extra", ''),
                                         ssh_title=result_json.get("ssh_title", ''),
                                         ssh_public=result_json.get("ssh_public", ''),
                                         ssh_private=result_json.get("ssh_private", ''),
                                         ssl_title=result_json.get("ssl_title", ''),
                                         ssl_filename=result_json.get("ssh_title", ''),
                                         other=result_json.get("other", ''))
            new_service.save()
            new_service.allowed_users.add(user)
        except Exception as e:
            raise falcon.HTTPInternalServerError(title="Error while saving the item",
                                                 description=e,
                                                 href=settings.__docs__)
Ejemplo n.º 13
0
 def on_put(self, req, res, id):
     try:
         # Parse token and get user id
         user_id = parse_token(req)['sub']
         # Get the user
         user = User.get(User.id == int(user_id))
     except Exception as e:
         logger.error("Can't verify user")
         raise falcon.HTTPBadRequest(title="Bad request",
                                     description=e,
                                     href=settings.__docs__)
     try:
         raw_json = req.stream.read()
         logger.debug("Got incoming JSON data")
     except Exception as e:
         logger.error("Can't read incoming data stream")
         raise falcon.HTTPBadRequest(title="Bad request",
                                     description=e,
                                     href=settings.__docs__)
     try:
         result_json = json.loads(raw_json.decode("utf-8"), encoding='utf-8')
     except ValueError:
         raise falcon.HTTPError(falcon.HTTP_400,
                                'Malformed JSON',
                                'Could not decode the request body. The '
                                'JSON was incorrect.')
     try:
         item = Item.get(Item.id == int(id))
         if user not in item.allowed_users:
             raise falcon.HTTPForbidden(title="Permission denied",
                                        description="You don't have access to this resource",
                                        href=settings.__docs__)
         item.name = result_json.get("name", item.name)
         item.description = result_json.get("description", item.description)
         item.category = result_json.get("category", item.category)
         item.tags = result_json.get("tags", item.tags)
         item.save()
         res.status = falcon.HTTP_200
         res.body = json.dumps({"message": "Item updated"})
     except Exception as e:
         print(e)
         error_msg = ("Unable to get the item. Please try again later.")
         raise falcon.HTTPServiceUnavailable(req.method + " failed",
                                             description=error_msg,
                                             retry_after=30,
                                             href=settings.__docs__)
Ejemplo n.º 14
0
 def on_put(self, req, res, id):
     try:
         # Parse token and get user id
         user_id = parse_token(req)['sub']
         # Get the user
         user = User.get(User.id == int(user_id))
     except Exception as e:
         logger.error("Can't verify user")
         raise falcon.HTTPBadRequest(title="Bad request",
                                     description=e,
                                     href=settings.__docs__)
     try:
         raw_json = req.stream.read()
         logger.debug("Got incoming JSON data")
     except Exception as e:
         logger.error("Can't read incoming data stream")
         raise falcon.HTTPBadRequest(title="Bad request",
                                     description=e,
                                     href=settings.__docs__)
     try:
         result_json = json.loads(raw_json.decode("utf-8"), encoding='utf-8')
     except ValueError:
         raise falcon.HTTPError(falcon.HTTP_400,
                                'Malformed JSON',
                                'Could not decode the request body. The '
                                'JSON was incorrect.')
     try:
         item = Item.get(Item.id == int(id))
         if user not in item.allowed_users:
             raise falcon.HTTPForbidden(title="Permission denied",
                                        description="You don't have access to this resource",
                                        href=settings.__docs__)
         item.name = result_json.get("name", item.name)
         item.description = result_json.get("description", item.description)
         item.category = result_json.get("category", item.category)
         item.tags = result_json.get("tags", item.tags)
         item.save()
         res.status = falcon.HTTP_200
         res.body = json.dumps({"message": "Item updated"})
     except Exception as e:
         print(e)
         error_msg = ("Unable to get the item. Please try again later.")
         raise falcon.HTTPServiceUnavailable(req.method + " failed",
                                             description=error_msg,
                                             retry_after=30,
                                             href=settings.__docs__)
Ejemplo n.º 15
0
    def on_post(self, req, res):

        """Save a new item
        """
        try:
            # Parse token and get user id
            user_id = parse_token(req)['sub']
            # Get the user
            user = User.get(User.id == int(user_id))
            logger.debug("Got user data")
        except Exception as e:
            logger.error("Can't verify user")
            raise falcon.HTTPBadRequest(title="Bad request",
                                        description=e,
                                        href=settings.__docs__)

        try:
            raw_json = req.stream.read()
            logger.debug("Got incoming JSON data")
        except Exception as e:
            logger.error("Can't read incoming data stream")
            raise falcon.HTTPBadRequest(title="Bad request",
                                        description=e,
                                        href=settings.__docs__)

        try:
            result_json = json.loads(raw_json.decode("utf-8"), encoding='utf-8')
            logger.debug("Parsed JSON data")
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,
                                   'Malformed JSON',
                                   'Could not decode the request body. The '
                                   'JSON was incorrect.')

        try:
            new_item = Item.create(name=result_json.get('name'),
                                   description=result_json.get("description", ''),
                                   category=result_json.get("category"),
                                   tags=result_json.get("tags", ''))
            new_item.save()
            new_item.allowed_users.add(user)
            logger.debug("Saved new item into the database")
        except Exception as e:
            raise falcon.HTTPInternalServerError(title="Error while saving the item",
                                                 description=e,
                                                 href=settings.__docs__)
Ejemplo n.º 16
0
Archivo: items.py Proyecto: gnef/sikr
    def on_post(self, req, res):

        """Save a new item
        """
        try:
            # Parse token and get user id
            user_id = parse_token(req)['sub']
            # Get the user
            user = User.get(User.id == int(user_id))
            logger.debug("Got user data")
        except Exception as e:
            logger.error("Can't verify user")
            raise falcon.HTTPBadRequest(title="Bad request",
                                        description=e,
                                        href=settings.__docs__)

        try:
            raw_json = req.stream.read()
            logger.debug("Got incoming JSON data")
        except Exception as e:
            logger.error("Can't read incoming data stream")
            raise falcon.HTTPBadRequest(title="Bad request",
                                        description=e,
                                        href=settings.__docs__)

        try:
            result_json = json.loads(raw_json.decode("utf-8"), encoding='utf-8')
            logger.debug("Parsed JSON data")
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400,
                                   'Malformed JSON',
                                   'Could not decode the request body. The '
                                   'JSON was incorrect.')

        try:
            new_item = Item.create(name=result_json.get('name'),
                                   description=result_json.get("description", ''),
                                   category=result_json.get("category"),
                                   tags=result_json.get("tags", ''))
            new_item.save()
            new_item.allowed_users.add(user)
            logger.debug("Saved new item into the database")
        except Exception as e:
            raise falcon.HTTPInternalServerError(title="Error while saving the item",
                                                 description=e,
                                                 href=settings.__docs__)
Ejemplo n.º 17
0
 def on_get(self, req, res, id):
     user_id = parse_token(req)['sub']
     try:
         user = User.get(User.id == int(user_id))
         item = Item.get(Item.id == int(id))
         if user not in item.allowed_users:
             raise falcon.HTTPForbidden(title="Permission denied",
                                        description="You don't have access to this resource",
                                        href=settings.__docs__)
         res.status = falcon.HTTP_200
         res.body = json.dumps(item)
         logger.debug("Items request succesful")
     except Exception as e:
         print(e)
         error_msg = ("Unable to get the item. Please try again later.")
         raise falcon.HTTPServiceUnavailable(req.method + " failed",
                                             description=error_msg,
                                             retry_after=30,
                                             href=settings.__docs__)
Ejemplo n.º 18
0
 def on_get(self, req, res, id):
     user_id = parse_token(req)['sub']
     try:
         user = User.get(User.id == int(user_id))
         group = Category.get(Category.id == int(id))
         if user not in group.allowed_users:
             raise falcon.HTTPForbidden(title="Permission denied",
                                        description="You don't have access to this resource",
                                        href=settings.__docs__)
         res.status = falcon.HTTP_200
         res.body = json.dumps(group)
         logger.debug("Items request succesful")
     except Exception as e:
         print(e)
         error_msg = ("Unable to get the group. Please try again later.")
         raise falcon.HTTPServiceUnavailable(req.method + " failed",
                                             description=error_msg,
                                             retry_after=30,
                                             href=settings.__docs__)
Ejemplo n.º 19
0
    def on_get(self, req, res):
        # Parse token and get user id
        user_id = parse_token(req)['sub']

        try:
            # Get the user
            user = User.get(User.id == int(user_id))

            groups = list(user.allowed_categories
                              .select(Category.id, Category.name)
                              .dicts())
            res.status = falcon.HTTP_200
            res.body = json.dumps(groups)
        except Exception as e:
            print(e)
            error_msg = ("Unable to get the groups. Please try again later")
            raise falcon.HTTPServiceUnavailable(title="{0} failed".format(req.method),
                                                description=error_msg,
                                                retry_after=30,
                                                href=settings.__docs__)
Ejemplo n.º 20
0
    def on_get(self, req, res):
        """
        """
        # Parse token and get user id
        user_id = parse_token(req)['sub']
        # See if we have to filter by item
        filter_item = req.get_param("item", required=False)

        try:
            # Get the user
            user = User.get(User.id == int(user_id))
            if filter_item:
                services = list(user.allowed_services
                                    .select(Service.id, Service.name,
                                            Service.username, Service.password,
                                            Service.url, Service.port, Service.extra,
                                            Service.ssh_title, Service.ssh_public,
                                            Service.ssh_private, Service.ssl_title,
                                            Service.ssl_filename, Service.other)
                                    .where(Service.item == int(filter_item))
                                    .dicts())
                logger.debug("Got services filtered by item")
            else:
                services = list(user.allowed_services
                                    .select(Service.id, Service.name,
                                            Service.username, Service.password,
                                            Service.url, Service.port, Service.extra,
                                            Service.ssh_title, Service.ssh_public,
                                            Service.ssh_private, Service.ssl_title,
                                            Service.ssl_filename, Service.other)
                                    .dicts())
                logger.debug("Got all the items")
            res.status = falcon.HTTP_200
            res.body = json.dumps(services)
        except Exception as e:
            logger.error(e)
            error_msg = ("Unable to get the services. Please try again later")
            raise falcon.HTTPServiceUnavailable(title=req.method + " failed",
                                                description=error_msg,
                                                retry_after=30,
                                                href=settings.__docs__)
Ejemplo n.º 21
0
    def on_get(self, req, res):
        # Parse token and get user id
        user_id = parse_token(req)['sub']

        try:
            # Get the user
            user = User.get(User.id == int(user_id))

            groups = list(
                user.allowed_categories.select(Category.id,
                                               Category.name).dicts())
            res.status = falcon.HTTP_200
            res.body = json.dumps(groups)
        except Exception as e:
            print(e)
            error_msg = ("Unable to get the groups. Please try again later")
            raise falcon.HTTPServiceUnavailable(title="{0} failed".format(
                req.method),
                                                description=error_msg,
                                                retry_after=30,
                                                href=settings.__docs__)
Ejemplo n.º 22
0
    def on_get(self, req, res):
        """
        """
        # Parse token and get user id
        user_id = parse_token(req)['sub']
        # See if we have to filter by item
        filter_item = req.get_param("item", required=False)

        try:
            # Get the user
            user = User.get(User.id == int(user_id))
            if filter_item:
                services = list(
                    user.allowed_services.select(
                        Service.id, Service.name, Service.username,
                        Service.password, Service.url, Service.port,
                        Service.extra, Service.ssh_title, Service.ssh_public,
                        Service.ssh_private, Service.ssl_title,
                        Service.ssl_filename, Service.other).where(
                            Service.item == int(filter_item)).dicts())
                logger.debug("Got services filtered by item")
            else:
                services = list(
                    user.allowed_services.select(
                        Service.id, Service.name, Service.username,
                        Service.password, Service.url, Service.port,
                        Service.extra, Service.ssh_title, Service.ssh_public,
                        Service.ssh_private, Service.ssl_title,
                        Service.ssl_filename, Service.other).dicts())
                logger.debug("Got all the items")
            res.status = falcon.HTTP_200
            res.body = json.dumps(services)
        except Exception as e:
            logger.error(e)
            error_msg = ("Unable to get the services. Please try again later")
            raise falcon.HTTPServiceUnavailable(title=req.method + " failed",
                                                description=error_msg,
                                                retry_after=30,
                                                href=settings.__docs__)
Ejemplo n.º 23
0
    def on_post(self, req, res):
        try:
            # Parse token and get user id
            user_id = parse_token(req)['sub']
            # Get the user
            user = User.get(User.id == int(user_id))
        except Exception as e:
            logger.error("Can't verify user")
            raise falcon.HTTPBadRequest(title="Bad request",
                                        description=e,
                                        href=settings.__docs__)

        try:
            raw_json = req.stream.read()
            logger.debug("Got incoming JSON data")
        except Exception as e:
            logger.error("Can't read incoming data stream")
            raise falcon.HTTPBadRequest(title="Bad request",
                                        description=e,
                                        href=settings.__docs__)

        try:
            result_json = json.loads(raw_json.decode("utf-8"),
                                     encoding='utf-8')
            logger.debug(result_json)
        except ValueError:
            raise falcon.HTTPError(
                falcon.HTTP_400, 'Malformed JSON',
                'Could not decode the request body. The '
                'JSON was incorrect.')

        try:
            new_share = ShareToken(user=user,
                                   token=generate_token(),
                                   resource=int(result_json.get()))
        except:
            pass
Ejemplo n.º 24
0
    def on_get(self, req, res, id):
        try:
            # Parse token and get user id
            user_id = parse_token(req)['sub']
            # Get the user
            user = User.get(User.id == int(user_id))
        except Exception as e:
            logger.error("Can't verify user")
            raise falcon.HTTPBadRequest(title="Bad request",
                                        description=e,
                                        href=settings.__docs__)
        try:
            service_obj = Service.get(Service.id == id)
            service = list(
                service_obj.select(
                    Service.id, Service.name, Service.username,
                    Service.password, Service.url, Service.port, Service.extra,
                    Service.ssh_title, Service.ssh_public, Service.ssh_private,
                    Service.ssl_title, Service.ssl_filename,
                    Service.other).where(Service.id == id).dicts())
            if user not in service_obj.allowed_users:
                raise falcon.HTTPForbidden(
                    title="Permission denied",
                    description="You don't have access to this resource",
                    href=settings.__docs__)

            res.status = falcon.HTTP_200
            res.body = json.dumps(service)
        except Exception as e:
            print(e)
            error_msg = ("Unable to get the items. Please try again later")
            raise falcon.HTTPServiceUnavailable(title="{0} failed".format(
                req.method),
                                                description=error_msg,
                                                retry_after=30,
                                                href=settings.__docs__)
Ejemplo n.º 25
0
    def on_post(self, req, res):
        """Create the JWT token for the user
        """
        access_token_url = 'https://graph.facebook.com/oauth/access_token'
        graph_api_url = 'https://graph.facebook.com/me'

        # Read the incoming data
        stream = req.stream.read()
        data = json.loads(stream.decode('utf-8'))
        logger.debug("Facebook OAuth: Incoming data read successfully")

        params = {
            'client_id': data['clientId'],
            'redirect_uri': data['redirectUri'] + '/',
            'client_secret': settings.FACEBOOK_SECRET,
            'code': data['code']
        }
        logger.debug("Facebook OAuth: Built the code response correctly")

        # Step 1. Exchange authorization code for access token.
        r = requests.get(access_token_url, params=params)
        access_token = dict(parse_qsl(r.text))
        logger.debug("Facebook OAuth: Auth code exchange for token success")

        # Step 2. Retrieve information about the current user.
        r = requests.get(graph_api_url, params=access_token)
        profile = json.loads(r.text)
        logger.debug("Facebook OAuth: Retrieve user information success")

        # Step 3. (optional) Link accounts.
        if req.auth:
            payload = utils.parse_token(req)
            try:
                user = User.select().where(
                    (User.facebook == profile['id'])
                    | (User.id == payload['sub'])
                    | (User.email == profile['email'])).get()
                # Set the facebook code again. This is a failsafe.
                user.facebook = profile['id']
                user.save()
                logger.debug(
                    "Facebook OAuth: Account {0} already exists".format(
                        profile["id"]))
            except User.DoesNotExist:
                logger.debug("Facebook OAuth: User does not exist")
                user = User.create(facebook=profile['id'],
                                   username=profile['name'],
                                   email=profile["email"])
                user.save()
                logger.debug("Facebook OAuth: Created user {0}".format(
                    profile["name"]))
        else:
            try:
                user = User.select().where((User.facebook == profile['id']) | (
                    User.email == profile['email'])).get()
                # Set the github code again. This is a failsafe.
                user.facebook = profile['id']
                user.save()
            except User.DoesNotExist:
                logger.debug("Facebook OAuth: User does not exist")
                user = User.create(facebook=profile['id'],
                                   username=profile['name'],
                                   email=profile["email"])
                user.save()
                logger.debug("Facebook OAuth: Created user {0}".format(
                    profile["name"]))
        token = utils.create_jwt_token(user)
        res.body = json.dumps({"token": token})
        res.status = falcon.HTTP_200
Ejemplo n.º 26
0
    def on_post(self, req, res):

        """Create the JWT token for the user
        """
        access_token_url = 'https://graph.facebook.com/oauth/access_token'
        graph_api_url = 'https://graph.facebook.com/me'

        # Read the incoming data
        stream = req.stream.read()
        data = json.loads(stream.decode('utf-8'))
        logger.debug("Facebook OAuth: Incoming data read successfully")

        params = {
            'client_id': data['clientId'],
            'redirect_uri': data['redirectUri'] + '/',
            'client_secret': settings.FACEBOOK_SECRET,
            'code': data['code']
        }
        logger.debug("Facebook OAuth: Built the code response correctly")

        # Step 1. Exchange authorization code for access token.
        r = requests.get(access_token_url, params=params)
        access_token = dict(parse_qsl(r.text))
        logger.debug("Facebook OAuth: Auth code exchange for token success")

        # Step 2. Retrieve information about the current user.
        r = requests.get(graph_api_url, params=access_token)
        profile = json.loads(r.text)
        logger.debug("Facebook OAuth: Retrieve user information success")

        # Step 3. (optional) Link accounts.
        if req.auth:
            payload = utils.parse_token(req)
            try:
                user = User.select().where(
                    (User.facebook == profile['id']) |
                    (User.id == payload['sub']) |
                    (User.email == profile['email'])
                ).get()
                # Set the facebook code again. This is a failsafe.
                user.facebook = profile['id']
                user.save()
                logger.debug("Facebook OAuth: Account {0} already exists".format(profile["id"]))
            except User.DoesNotExist:
                logger.debug("Facebook OAuth: User does not exist")
                user = User.create(facebook=profile['id'], username=profile['name'], email=profile["email"])
                user.save()
                logger.debug("Facebook OAuth: Created user {0}".format(profile["name"]))
        else:
            try:
                user = User.select().where(
                    (User.facebook == profile['id']) |
                    (User.email == profile['email'])
                ).get()
                # Set the github code again. This is a failsafe.
                user.facebook = profile['id']
                user.save()
            except User.DoesNotExist:
                logger.debug("Facebook OAuth: User does not exist")
                user = User.create(facebook=profile['id'], username=profile['name'], email=profile["email"])
                user.save()
                logger.debug("Facebook OAuth: Created user {0}".format(profile["name"]))
        token = utils.create_jwt_token(user)
        res.body = json.dumps({"token": token})
        res.status = falcon.HTTP_200