示例#1
0
    def __init__(self, config_file, grant_all=None):
        self.config_file = config_file
        self.config = configparser.ConfigParser(interpolation=None)

        if not self.config.read(config_file, encoding='utf-8'):
            print('[permissions] Permissions file not found, copying example_permissions.ini')

            try:
                shutil.copy('config/example_permissions.ini', config_file)
                self.config.read(config_file, encoding='utf-8')

            except Exception as e:
                traceback.print_exc()
                raise RuntimeError("Unable to copy config/example_permissions.ini to %s: %s" % (config_file, e))

        self.default_group = PermissionGroup('Default', self.config['Default'])
        self.groups = set()

        for section in self.config.sections():
            self.groups.add(PermissionGroup(section, self.config[section]))

        # Create a fake section to fallback onto the permissive default values to grant to the owner
        # noinspection PyTypeChecker
        owner_group = PermissionGroup("Owner (auto)", configparser.SectionProxy(self.config, None))
        if hasattr(grant_all, '__iter__'):
            owner_group.user_list = set(grant_all)

        self.groups.add(owner_group)
示例#2
0
    def __init__(self, config_file, grant_all=None):
        self.config_file = config_file
        self.config = configparser.ConfigParser(interpolation=None)

        if not self.config.read(config_file, encoding='utf-8'):
            log.info("許可ファイルが見つからない、example_permissions.iniをコピーする")

            try:
                shutil.copy('config/example_permissions.ini', config_file)
                self.config.read(config_file, encoding='utf-8')

            except Exception as e:
                traceback.print_exc()
                raise RuntimeError("config/example_permissions.iniを{}にコピーできません:{}".format(config_file, e))

        self.default_group = PermissionGroup('Default', self.config['Default'])
        self.groups = set()

        for section in self.config.sections():
            self.groups.add(PermissionGroup(section, self.config[section]))

        # Create a fake section to fallback onto the permissive default values to grant to the owner
        # noinspection PyTypeChecker
        owner_group = PermissionGroup("Owner (auto)", configparser.SectionProxy(self.config, None))
        if hasattr(grant_all, '__iter__'):
            owner_group.user_list = set(grant_all)

        self.groups.add(owner_group)
    def __init__(self, config_file, grant_all=None):
        self.config_file = config_file
        self.config = configparser.ConfigParser(interpolation=None)

        if not self.config.read(config_file, encoding="utf-8"):
            print("[permissions] Permissions file not found, copying example_permissions.ini")

            try:
                shutil.copy("config/example_permissions.ini", config_file)
                self.config.read(config_file, encoding="utf-8")

            except Exception as e:
                traceback.print_exc()
                raise RuntimeError("Unable to copy config/example_permissions.ini to %s: %s" % (config_file, e))

        self.default_group = PermissionGroup("Default", self.config["Default"])
        self.groups = set()

        for section in self.config.sections():
            self.groups.add(PermissionGroup(section, self.config[section]))

        owner_group = PermissionGroup("Owner (auto)", configparser.SectionProxy(self.config, None))
        if hasattr(grant_all, "__iter__"):
            owner_group.user_list = set(grant_all)

        self.groups.add(owner_group)
示例#4
0
    def __init__(self, config_file, grant_all=None):        
        self.config_file = config_file
        self.config = configparser.ConfigParser(interpolation=None)

        if not self.config.read(config_file, encoding='utf-8'):
            log.info("Permissions file not found, copying example_permissions.ini")

            try:
                shutil.copy('config/example_permissions.ini', config_file)
                self.config.read(config_file, encoding='utf-8')

            except Exception as e:
                traceback.print_exc()
                raise RuntimeError("Unable to copy config/example_permissions.ini to {}: {}".format(config_file, e))

        self.default_group = PermissionGroup('Default', self.config['Default'])
        self.groups = set()

        for section in self.config.sections():
            if section != 'Owner (auto)':
                self.groups.add(PermissionGroup(section, self.config[section]))
                
        if self.config.has_section('Owner (auto)'):
            owner_group = PermissionGroup('Owner (auto)', self.config['Owner (auto)'], fallback=Permissive)
            
        else:
            log.info("[Owner (auto)] section not found, falling back to permissive default")
            # Create a fake section to fallback onto the default permissive values to grant to the owner
            # noinspection PyTypeChecker
            owner_group = PermissionGroup("Owner (auto)", configparser.SectionProxy(self.config, "Owner (auto)"), fallback=Permissive)
            
        if hasattr(grant_all, '__iter__'):
            owner_group.user_list = set(grant_all)

        self.groups.add(owner_group)
示例#5
0
  def _read(self, fp, fpname):
    """Parse a sectioned configuration file.

    Each section in a configuration file contains a header, indicated by
    a name in square brackets (`[]'), plus key/value options, indicated by
    `name' and `value' delimited with a specific substring (`=' or `:' by
    default).

    Values can span multiple lines, as long as they are indented deeper
    than the first line of the value. Depending on the parser's mode, blank
    lines may be treated as parts of multiline values or ignored.

    Configuration files may include comments, prefixed by specific
    characters (`#' and `;' by default). Comments may appear on their own
    in an otherwise empty line or may be entered in lines holding values or
    section names.
    """
    elements_added = set()
    cursect = None                        # None, or a dictionary
    sectname = None
    optname = None
    lineno = 0
    indent_level = 0
    e = None                              # None, or an exception
    for lineno, line in enumerate(fp, start=1):
      comment_start = None
      # strip inline comments
      for prefix in self._inline_comment_prefixes:
        index = line.find(prefix)
        if index == 0 or (index > 0 and line[index-1].isspace()):
          comment_start = index
          break
      # strip full line comments
      for prefix in self._comment_prefixes:
        if line.strip().startswith(prefix):
          comment_start = 0
          break
      value = line[:comment_start].strip()
      if not value:
        if self._empty_lines_in_values:
          # add empty line to the value, but only if there was no
          # comment on the line
          if (comment_start is None and
              cursect is not None and
              optname and
              cursect[optname] is not None):
              cursect[optname].append('') # newlines added at join
        else:
          # empty line marks end of value
          indent_level = sys.maxsize
        continue
      # continuation line?
      first_nonspace = self.NONSPACECRE.search(line)
      cur_indent_level = first_nonspace.start() if first_nonspace else 0
      if (cursect is not None and optname and
          cur_indent_level > indent_level):
          cursect[optname].append(value)
      # a section header or option header?
      else:
        indent_level = cur_indent_level
        # is it a section header?
        mo = self.SECTCRE.match(value)
        if mo:
          sectname = mo.group('header')
          if sectname in self._sections:
            if self._strict and sectname in elements_added:
              raise DuplicateSectionError(sectname, fpname,
                                          lineno)
            cursect = self._sections[sectname]
            elements_added.add(sectname)
          elif sectname == self.default_section:
            cursect = self._defaults
          else:
            cursect = self._dict()
            self._sections[sectname] = cursect
            self._proxies[sectname] = configparser.SectionProxy(self, sectname)
            elements_added.add(sectname)
          # So sections can't start with a continuation line
          optname = None
        # no section header in the file?
        elif cursect is None:
          raise MissingSectionHeaderError(fpname, lineno, line)
        # an option line?
        else:
          mo = self._optcre.match(value)
          if mo:
            optname, vi, optval = mo.group('option', 'vi', 'value')
            if not optname:
              e = self._handle_error(e, fpname, lineno, line)
            optname = self.optionxform(optname.rstrip())
            if (self._strict and
              (sectname, optname) in elements_added):
              raise configparser.DuplicateOptionError(sectname, optname, fpname, lineno)
            elements_added.add((sectname, optname))
            # This check is fine because the OPTCRE cannot
            # match if it would set optval to None
            if optval is not None:
              optval = optval.strip()
              # Check if this optname already exists
              if (optname in cursect) and (cursect[optname] is not None):
                # If it does, convert it to a tuple if it isn't already one
                if not isinstance(cursect[optname], tuple):
                  cursect[optname] = tuple(cursect[optname])
                cursect[optname] = cursect[optname] + tuple([optval])
              else:
                cursect[optname] = [optval]
            else:
                # valueless option handling
                cursect[optname] = None
          else:
            # a non-fatal parsing error occurred. set up the
            # exception but keep going. the exception will be
            # raised at the end of the file and will contain a
            # list of all bogus lines
            e = self._handle_error(e, fpname, lineno, line)
    # if any parsing errors occurred, raise an exception
    if e:
        raise e
    self._join_multiline_values()
示例#6
0
 def _set_proxies(self, sectname):
     """set proxies"""
     self._proxies[sectname] = configparser.SectionProxy(self, sectname)