コード例 #1
0
ファイル: sharing.py プロジェクト: daimagine/sikre
    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
コード例 #2
0
ファイル: email.py プロジェクト: daimagine/sikre
def send_email(subject='', to_address=[], from_address=from_addr, content=''):

    """Send an email to a specified user or users

    This is a basic wrapper around python's STMPLIB library that allows us to
    send emails to the users in case it's necessary. Any failure of this
    script is considered fatal.
    """
    try:
        msg = MIMEText(content)
        msg['Subject'] = "[{0}] {1} {2}".format(site_domain, subject, date.today().strftime("%Y%m%d"))
        msg['To'] = EMAIL_SPACE.join(to_address)
        msg['From'] = from_address
        logger.debug("All parameters set")
        mail = smtplib.SMTP(settings.SMTP_SERVER, settings.SMTP_PORT)
        logger.debug("Instantiated the SMTP")
        if settings.SMTP_TLS:
            mail.starttls()
            logger.debug("Started SMTP TLS connection")
        mail.login(settings.SMTP_USER, settings.SMTP_PASSWORD)
        logger.debug("Login success")
        mail.sendmail(from_addr, to_address, msg.as_string())
        logger.debug("Sent email")
        mail.quit()
    except Exception as e:
        logger.error("Email send failed. Error: {0}".format(e))
コード例 #3
0
ファイル: items.py プロジェクト: daimagine/sikre
    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__)
コード例 #4
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__)
コード例 #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:
            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__)
コード例 #6
0
ファイル: services.py プロジェクト: daimagine/sikre
    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__)
コード例 #7
0
ファイル: categories.py プロジェクト: daimagine/sikre
    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__)
コード例 #8
0
ファイル: email.py プロジェクト: aalexandru/sikr
def send_email(subject='', to_address=[], from_address=from_addr, content=''):
    """Send an email to a specified user or users.

    This is a basic wrapper around python's STMPLIB library that allows us to
    send emails to the users in case it's necessary. Any failure of this
    script is considered fatal.
    """
    try:
        msg = MIMEText(content)
        msg['Subject'] = "[{0}] {1} {2}".format(
            site_domain, subject,
            date.today().strftime("%Y%m%d"))
        msg['To'] = EMAIL_SPACE.join(to_address)
        msg['From'] = from_address
        logger.debug("All parameters set")
        mail = smtplib.SMTP(settings.SMTP_SERVER, settings.SMTP_PORT)
        logger.debug("Instantiated the SMTP")
        if settings.SMTP_TLS:
            mail.starttls()
            logger.debug("Started SMTP TLS connection")
        mail.login(settings.SMTP_USER, settings.SMTP_PASSWORD)
        logger.debug("Login success")
        mail.sendmail(from_addr, to_address, msg.as_string())
        logger.debug("Sent email")
        mail.quit()
    except Exception as e:
        logger.error("Email send failed. Error: {0}".format(e))
コード例 #9
0
ファイル: items.py プロジェクト: daimagine/sikre
    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__)
コード例 #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__)
コード例 #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__)
コード例 #12
0
ファイル: services.py プロジェクト: daimagine/sikre
    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__)
コード例 #13
0
ファイル: items.py プロジェクト: 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__)
コード例 #14
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__)
コード例 #15
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__)
コード例 #16
0
ファイル: items.py プロジェクト: daimagine/sikre
 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__)
コード例 #17
0
ファイル: services.py プロジェクト: daimagine/sikre
    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__)
コード例 #18
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__)
コード例 #19
0
def generate_db_schema():
    # Try to create the database tables, don't do anything if they fail
    try:
        print(" * Syncing database tables...")
        # First set the m2m models
        logger.info("Attempting to create the tables")
        db.create_tables([
            users.User,
            users.Group,
            users.UserGroup,
            items.Category,
            items.UserCategory,
            items.UserItem,
            items.Item,
            services.Service,
            services.UserService,
            shares.ShareToken,
        ])
        print(" * Database tables created")
    except Exception as e:
        logger.error(e)
        print(e)
コード例 #20
0
ファイル: sharing.py プロジェクト: aalexandru/sikr
    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
コード例 #21
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__)