Exemple #1
0
def _get_project_index(req, data):

    environ = req.environ

    try:
        #href = Href(req.base_path)
        projects = []
        for env_name, env_path in get_environments(environ).items():
            try:
                env = open_environment(env_path,
                                       use_cache=not environ['wsgi.run_once'])
                proj = {
                    'name': env.project_name,
                    'description': env.project_description,
                    'href': env_name,
                    'info': env.project_info
                }
            except Exception, e:
                proj = {
                    'name': env_name,
                    'description': to_unicode(e),
                    'info': {}
                }
            projects.append(proj)

        projects.sort(lambda x, y: cmp(x['name'].lower(), y['name'].lower()))

        data['projects'] = projects
Exemple #2
0
def get_project_list(environ, href, authname='anonymous', require_auth=True, permission='PROJECT_ACCESS'):
    projects = []
    for env_name, env_path in get_environments(environ).items():
        try:
            # env is 
            #  <class 'trac.env.Environment'>
            env = __open_environment(env_path,
                                    run_once=environ['wsgi.run_once'])

            if require_auth:
                if not is_authorised(authname, PermissionCache(env, authname), env, list_permission=permission):
                    continue

            env.path = env_path
            
            if env_name == 'all':
                env.isall = True
                continue

            env.isall = False
            proj = {
                'name': env.project_name,
                'description': env.project_description,
                'href': href(env_name),
                'env_name': env_name,
                'env':env
            }
            is_target = env.config.get('tram', 'include_project_list') or 'true';
            if is_target == 'true':
                projects.append(proj)
        except Exception, e:
            #proj = {'name': env_name, 'description': to_unicode(e)}
            debug(to_unicode(e))
            pass
Exemple #3
0
def get_allenv(environ, req):

    for env_name, env_path in get_environments(environ).items():
        try:
            env = __open_environment(env_path,
                                    run_once=environ['wsgi.run_once'])

            if env_name == 'all':
                env.isall = True
                if not env.abs_href.base:
                    env._abs_href = req.abs_href
                return env
        except Exception, e:
            continue
Exemple #4
0
    def _distribute_auth(self, req, trac_auth, name=None):
        # Single Sign On authentication distribution between multiple
        #   Trac environments managed by AccountManager.
        local_environ = req.environ.get('SCRIPT_NAME', '').lstrip('/')

        for environ, path in get_environments(req.environ).iteritems():
            if environ != local_environ:
                try:
                    # Cache environment for subsequent invocations.
                    env = open_environment(path, use_cache=True)
                    auth_cookie_path = env.config.get('trac',
                                                      'auth_cookie_path')
                    # Consider only Trac environments with equal, non-default
                    #   'auth_cookie_path', which enables cookies to be shared.
                    if auth_cookie_path == self.auth_cookie_path:
                        db = env.get_db_cnx()
                        cursor = db.cursor()
                        # Authentication cookie values must be unique. Ensure,
                        #   there is no other session (or worst: session ID)
                        #   associated to it.
                        cursor.execute(
                            """
                            DELETE FROM auth_cookie
                            WHERE  cookie=%s
                            """, (trac_auth, ))
                        if not name:
                            db.commit()
                            env.log.debug('Auth data revoked from: %s' %
                                          local_environ)
                            continue
                        cursor.execute(
                            """
                            INSERT INTO auth_cookie
                                   (cookie,name,ipnr,time)
                            VALUES (%s,%s,%s,%s)
                            """,
                            (trac_auth, name, req.remote_addr, int(
                                time.time())))
                        db.commit()
                        env.log.debug('Auth data received from: %s' %
                                      local_environ)
                        self.log.debug('Auth distribution success: %s' %
                                       environ)
                except Exception, e:
                    self.log.debug(
                        'Auth distribution skipped for env %s: %s' %
                        (environ, exception_to_unicode(e, traceback=True)))
    def _distribute_auth(self, req, trac_auth, name=None):
        # Single Sign On authentication distribution between multiple
        #   Trac environments managed by AccountManager.
        local_environ = req.environ.get('SCRIPT_NAME', '').lstrip('/')

        for environ, path in get_environments(req.environ).iteritems():
            if environ != local_environ:
                try:
                    # Cache environment for subsequent invocations.
                    env = open_environment(path, use_cache=True)
                    auth_cookie_path = env.config.get('trac',
                                                      'auth_cookie_path')
                    # Consider only Trac environments with equal, non-default
                    #   'auth_cookie_path', which enables cookies to be shared.
                    if auth_cookie_path == self.auth_cookie_path:
                        with env.db_transaction as db:
                            cursor = db.cursor()
                            # Authentication cookie values must be unique. Ensure,
                            #   there is no other session (or worst: session ID)
                            #   associated to it.
                            cursor.execute("""
                                DELETE FROM auth_cookie
                                WHERE  cookie=%s
                                """, (trac_auth,))
                            if not name:
                                env.log.debug('Auth data revoked from: %s'
                                              % local_environ)
                                continue
                            cursor.execute("""
                                INSERT INTO auth_cookie
                                       (cookie,name,ipnr,time)
                                VALUES (%s,%s,%s,%s)
                                """, (trac_auth, name, req.remote_addr,
                                      int(time.time())))
                        env.log.debug('Auth data received from: %s'
                                      % local_environ)
                        self.log.debug('Auth distribution success: %s'
                                       % environ)
                except Exception, e:
                    self.log.debug('Auth distribution skipped for env %s: %s'
                                   % (environ,
                                      exception_to_unicode(e, traceback=True))
                    )
    def _distribute_auth(self, req, trac_auth, name=None):
        # Single Sign On authentication distribution between multiple
        #   Trac environments managed by AccountManager.
        local_env_name = req.base_path.lstrip('/')

        for env_name, env_path in get_environments(req.environ).iteritems():
            if env_name != local_env_name:
                try:
                    # Cache environment for subsequent invocations.
                    env = open_environment(env_path, use_cache=True)
                    auth_cookie_path = env.config.get('trac',
                                                      'auth_cookie_path')
                    # Consider only Trac environments with equal, non-default
                    # 'auth_cookie_path', which enables cookies to be shared.
                    if auth_cookie_path == self.auth_cookie_path:
                        with env.db_transaction as db:
                            # Authentication cookie values must be unique.
                            # Ensure, there is no other session (or worse:
                            # session ID) associated to it.
                            db("""
                                DELETE FROM auth_cookie WHERE cookie=%s
                                """, (trac_auth,))
                            if not name:
                                env.log.debug("Auth data revoked from: %s",
                                              local_env_name)
                                continue

                            db("""
                                INSERT INTO auth_cookie (cookie,name,ipnr,time)
                                VALUES (%s,%s,%s,%s)
                                """, (trac_auth, name, req.remote_addr,
                                      int(time.time())))

                        env.log.debug("Auth data received from: %s",
                                      local_env_name)
                        self.log.debug("Auth distribution success: %s",
                                       env_name)
                except Exception, e:
                    self.log.debug("Auth distribution skipped for env %s: %s",
                                   env_name,
                                   exception_to_unicode(e, traceback=True))
Exemple #7
0
    def _distribute_cookie(self, req, trac_auth):
        # Single Sign On authentication distribution between multiple
        #   Trac environments managed by AccountManager.
        all_envs = get_environments(req.environ)
        local_environ = req.environ.get('SCRIPT_NAME', None)
        self.auth_share_participants = []

        for environ, path in all_envs.iteritems():
            if not environ == local_environ.lstrip('/'):
                # Cache environment for subsequent invocations.
                env = open_environment(path, use_cache=True)
                # Consider only Trac environments with equal, non-default
                #   'auth_cookie_path', which enables cookies to be shared.
                if self._get_cookie_path(req) == self.auth_cookie_path:
                    db = env.get_db_cnx()
                    cursor = db.cursor()
                    # Authentication cookie values must be unique. Ensure,
                    #   there is no other session (or worst: session ID)
                    #   associated to it.
                    cursor.execute(
                        """
                        DELETE FROM auth_cookie
                        WHERE  cookie=%s
                        """, (trac_auth, ))
                    cursor.execute(
                        """
                        INSERT INTO auth_cookie
                               (cookie,name,ipnr,time)
                        VALUES (%s,%s,%s,%s)
                        """, (trac_auth, req.remote_user, req.remote_addr,
                              int(time.time())))
                    db.commit()
                    env.log.debug('Auth data received from: ' + local_environ)
                    # Track env paths for easier auth revocation later on.
                    self.auth_share_participants.append(path)
                    self.log.debug('Auth distribution success: ' + environ)
                else:
                    self.log.debug('Auth distribution skipped: ' + environ)
def _get_project_index(req, data):

    environ = req.environ

    try:
        #href = Href(req.base_path)
        projects = []
        for env_name, env_path in get_environments(environ).items():
            try:
                env = open_environment(env_path, use_cache=not environ['wsgi.run_once'])
                proj = {
                    'name': env.project_name,
                    'description': env.project_description,
                    'href': env_name,
                    'info': env.project_info
                }
            except Exception, e:
                proj = {'name': env_name, 'description': to_unicode(e), 'info': {}}
            projects.append(proj)

        projects.sort(lambda x, y: cmp(x['name'].lower(), y['name'].lower()))

        data['projects'] = projects
Exemple #9
0
    def _distribute_cookie(self, req, trac_auth):
        # Single Sign On authentication distribution between multiple
        #   Trac environments managed by AccountManager.
        all_envs = get_environments(req.environ)
        local_environ = req.environ.get('SCRIPT_NAME', None)
        self.auth_share_participants = []

        for environ, path in all_envs.iteritems():
            if not environ == local_environ.lstrip('/'):
                # Cache environment for subsequent invocations.
                env = open_environment(path, use_cache=True)
                # Consider only Trac environments with equal, non-default
                #   'auth_cookie_path', which enables cookies to be shared.
                if self._get_cookie_path(req) == env.config.get('trac',
                                                     'auth_cookie_path'):
                    db = env.get_db_cnx()
                    cursor = db.cursor()
                    # Authentication cookie values must be unique. Ensure,
                    #   there is no other session (or worst: session ID)
                    #   associated to it.
                    cursor.execute("""
                        DELETE FROM auth_cookie
                        WHERE  cookie=%s
                        """, (trac_auth,))
                    cursor.execute("""
                        INSERT INTO auth_cookie
                               (cookie,name,ipnr,time)
                        VALUES (%s,%s,%s,%s)
                        """, (trac_auth, req.remote_user, req.remote_addr,
                              int(time.time())))
                    db.commit()
                    env.log.debug('Auth data received from: ' + local_environ)
                    # Track env paths for easier auth revocation later on.
                    self.auth_share_participants.append(path)
                    self.log.debug('Auth distribution success: ' + environ)
                else:
                    self.log.debug('Auth distribution skipped: ' + environ)
Exemple #10
0
 def test_qmark_pattern_tracignore(self):
     create_file(self.tracignore, 'mydir?')
     self.assertEquals(self.env_paths(['.hidden_dir']),
                       get_environments(self.environ))
Exemple #11
0
 def test_empty_tracignore(self):
     create_file(self.tracignore)
     self.assertEquals(self.env_paths(['mydir1', 'mydir2', '.hidden_dir']),
                       get_environments(self.environ))
Exemple #12
0
 def test_default_tracignore(self):
     self.assertEquals(self.env_paths(['mydir1', 'mydir2']),
                       get_environments(self.environ))
Exemple #13
0
    def open_environment(self, environ, start_response):
        env_path = environ.get('trac.env_path')
        if env_path:
            environ['trac.env_name'] = os.path.basename(env_path)
        else:
            env_parent_dir = environ.get('trac.env_parent_dir')
            env_paths = environ.get('trac.env_paths')
            if env_parent_dir or env_paths:
                # The first component of the path is the base name of the
                # environment
                path_info = environ.get('PATH_INFO', '').lstrip('/').split('/')
                env_name = path_info.pop(0)
    
                if not env_name:
                    # No specific environment requested, so render an environment
                    # index page
                    send_project_index(environ, start_response, env_parent_dir,
                                       env_paths)
                    raise RequestDone

                environ['trac.env_name'] = env_name
                errmsg = None
    
                # To make the matching patterns of request handlers work, we append
                # the environment name to the `SCRIPT_NAME` variable, and keep only
                # the remaining path in the `PATH_INFO` variable.
                script_name = environ.get('SCRIPT_NAME', '')
                try:
                    script_name = unicode(script_name, 'utf-8')
                    # (as Href expects unicode parameters)
                    environ['SCRIPT_NAME'] = Href(script_name)(env_name)
                    environ['PATH_INFO'] = '/' + '/'.join(path_info)
    
                    if env_parent_dir:
                        env_path = os.path.join(env_parent_dir, env_name)
                    else:
                        env_path = get_environments(environ).get(env_name)
    
                    if not env_path or not os.path.isdir(env_path):
                        errmsg = 'Environment not found'
                except UnicodeDecodeError:
                    errmsg = 'Invalid URL encoding (was %r)' % script_name
    
                if errmsg:
                    write = start_response('404 Not Found',
                                   [('Content-Type', 'text/plain'),
                                    ('Content-Length', str(len(errmsg)))])
                    write(errmsg)
                    raise RequestDone
    
        if not env_path:
            raise EnvironmentError('The environment options "TRAC_ENV" or '
                                   '"TRAC_ENV_PARENT_DIR" or the mod_python '
                                   'options "TracEnv" or "TracEnvParentDir" are '
                                   'missing. Trac requires one of these options '
                                   'to locate the Trac environment(s).')
        run_once = environ['wsgi.run_once']
    
        env = None
        self.global_env = global_env = None
        try:
            self.global_env = global_env = open_environment(env_path, use_cache=not run_once)
            factory = environment_factory(global_env)
            factory_env = factory().open_environment(environ, env_path, global_env, use_cache=not run_once) if factory \
                            else None
            env = factory_env if factory_env else global_env
        except Exception:
            raise
        return env
Exemple #14
0
 def test_combined_tracignore(self):
     create_file(self.tracignore, 'my*i?1\n\n#mydir2')
     self.assertEqual(self.env_paths(['mydir2', '.hidden_dir']),
                      get_environments(self.environ))
Exemple #15
0
 def test_star_pattern_tracignore(self):
     create_file(self.tracignore, 'my*\n.hidden_dir')
     self.assertEqual({}, get_environments(self.environ))
Exemple #16
0
 def test_qmark_pattern_tracignore(self):
     create_file(self.tracignore, 'mydir?')
     self.assertEqual(self.env_paths(['.hidden_dir']),
                      get_environments(self.environ))
Exemple #17
0
 def test_empty_tracignore(self):
     create_file(self.tracignore)
     self.assertEqual(self.env_paths(['mydir1', 'mydir2', '.hidden_dir']),
                      get_environments(self.environ))
Exemple #18
0
 def test_default_tracignore(self):
     self.assertEqual(self.env_paths(['mydir1', 'mydir2']),
                      get_environments(self.environ))
Exemple #19
0
 def test_star_pattern_tracignore(self):
     create_file(self.tracignore, 'my*\n.hidden_dir')
     self.assertEquals({}, get_environments(self.environ))
Exemple #20
0
    def open_environment(self, environ, start_response):
        env_path = environ.get('trac.env_path')
        if env_path:
            environ['trac.env_name'] = os.path.basename(env_path)
        else:
            env_parent_dir = environ.get('trac.env_parent_dir')
            env_paths = environ.get('trac.env_paths')
            if env_parent_dir or env_paths:
                # The first component of the path is the base name of the
                # environment
                path_info = environ.get('PATH_INFO', '').lstrip('/').split('/')
                env_name = path_info.pop(0)
    
                if not env_name:
                    # No specific environment requested, so render an environment
                    # index page
                    send_project_index(environ, start_response, env_parent_dir,
                                       env_paths)
                    raise RequestDone

                environ['trac.env_name'] = env_name
                errmsg = None
    
                # To make the matching patterns of request handlers work, we append
                # the environment name to the `SCRIPT_NAME` variable, and keep only
                # the remaining path in the `PATH_INFO` variable.
                script_name = environ.get('SCRIPT_NAME', '')
                try:
                    script_name = unicode(script_name, 'utf-8')
                    # (as Href expects unicode parameters)
                    environ['SCRIPT_NAME'] = Href(script_name)(env_name)
                    environ['PATH_INFO'] = '/' + '/'.join(path_info)
    
                    if env_parent_dir:
                        env_path = os.path.join(env_parent_dir, env_name)
                    else:
                        env_path = get_environments(environ).get(env_name)
    
                    if not env_path or not os.path.isdir(env_path):
                        errmsg = 'Environment not found'
                except UnicodeDecodeError:
                    errmsg = 'Invalid URL encoding (was %r)' % script_name
    
                if errmsg:
                    write = start_response('404 Not Found',
                                   [('Content-Type', 'text/plain'),
                                    ('Content-Length', str(len(errmsg)))])
                    write(errmsg)
                    raise RequestDone
    
        if not env_path:
            raise EnvironmentError('The environment options "TRAC_ENV" or '
                                   '"TRAC_ENV_PARENT_DIR" or the mod_python '
                                   'options "TracEnv" or "TracEnvParentDir" are '
                                   'missing. Trac requires one of these options '
                                   'to locate the Trac environment(s).')
        run_once = environ['wsgi.run_once']
    
        env = None
        self.global_env = global_env = None
        try:
            self.global_env = global_env = open_environment(env_path, use_cache=not run_once)
            factory = environment_factory(global_env)
            factory_env = factory().open_environment(environ, env_path, global_env, use_cache=not run_once) if factory \
                            else None
            env = factory_env if factory_env else global_env
        except Exception:
            raise
        return env
Exemple #21
0
 def test_combined_tracignore(self):
     create_file(self.tracignore, "my*i?1\n\n#mydir2")
     self.assertEquals(self.env_paths(["mydir2", ".hidden_dir"]), get_environments(self.environ))
Exemple #22
0
 def test_empty_tracignore(self):
     create_file(self.tracignore)
     self.assertEquals(self.env_paths(["mydir1", "mydir2", ".hidden_dir"]), get_environments(self.environ))
Exemple #23
0
 def test_combined_tracignore(self):
     create_file(self.tracignore, 'my*i?1\n\n#mydir2')
     self.assertEquals(self.env_paths(['mydir2', '.hidden_dir']),
                       get_environments(self.environ))
Exemple #24
0
                    req.send_error(sys.exc_info(), status=500, data=data)
                except RequestDone, e:
                    #debug(to_unicode(e))
                    return []


            # To make the matching patterns of request handlers work, we append
            # the environment name to the `SCRIPT_NAME` variable, and keep only
            # the remaining path in the `PATH_INFO` variable.
            environ['SCRIPT_NAME'] = Href(environ['SCRIPT_NAME'])(env_name)
            environ['PATH_INFO'] = '/'.join([''] + path_info)

            if env_parent_dir:
                env_path = os.path.join(env_parent_dir, env_name)
            else:
                env_path = get_environments(environ).get(env_name)

            if not env_path or not os.path.isdir(env_path):
                start_response('404 Not Found', [])
                return ['Environment not found']

    if not env_path:
        raise EnvironmentError('The environment options "TRAC_ENV" or '
                               '"TRAC_ENV_PARENT_DIR" or the mod_python '
                               'options "TracEnv" or "TracEnvParentDir" are '
                               'missing. Trac requires one of these options '
                               'to locate the Trac environment(s).')
    try:
        env = __open_environment(env_path, run_once=environ['wsgi.run_once'])
    except Exception, e:
        prepare_request(req, environ)