decorators.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. import functools
  18. import logging
  19. from typing import Optional
  20. from flask import g
  21. from flask_babel import lazy_gettext as _
  22. from superset.models.core import Database
  23. from superset.utils.core import parse_js_uri_path_item
  24. logger = logging.getLogger(__name__)
  25. def check_datasource_access(f):
  26. """
  27. A Decorator that checks if a user has datasource access
  28. """
  29. def wraps(
  30. self, pk: int, table_name: str, schema_name: Optional[str] = None
  31. ): # pylint: disable=invalid-name
  32. schema_name_parsed = parse_js_uri_path_item(schema_name, eval_undefined=True)
  33. table_name_parsed = parse_js_uri_path_item(table_name)
  34. if not table_name_parsed:
  35. return self.response_422(message=_("Table name undefined"))
  36. database: Database = self.datamodel.get(pk)
  37. if not database:
  38. self.stats_logger.incr(
  39. f"database_not_found_{self.__class__.__name__}.select_star"
  40. )
  41. return self.response_404()
  42. # Check that the user can access the datasource
  43. if not self.appbuilder.sm.can_access_datasource(
  44. database, table_name_parsed, schema_name_parsed
  45. ):
  46. self.stats_logger.incr(
  47. f"permisssion_denied_{self.__class__.__name__}.select_star"
  48. )
  49. logger.warning(
  50. f"Permission denied for user {g.user} on table: {table_name_parsed} "
  51. f"schema: {schema_name_parsed}"
  52. )
  53. return self.response_404()
  54. return f(self, database, table_name_parsed, schema_name_parsed)
  55. return functools.update_wrapper(wraps, f)