def process_request(self, req):
   if req.path_info == "/auth_server_login":
     self._redirects_for_login(req)
   if req.path_info == "/auth_server_process":
     self._do_process(req)
   else:
     LoginModule.process_request(self, req)
Example #2
0
    def authenticate(self, req):
        """Return the name of the remote user, or `None` if the identity of the
        user is unknown."""

        # check for an authenticated user
        login_module = LoginModule(self.env)
        remote_user = login_module.authenticate(req)
        if remote_user:
            return remote_user

        # authenticate via a CAPTCHA
        if 'captchaauth' in req.args and 'captchaid' in req.args:

            # ensure CAPTCHA identification
            captcha = self.captcha(req)
            if captcha != req.args['captchaauth']:
                return

            # ensure sane identity
            name, email = self.identify(req)
            if name is None:
                return
            if AccountManager and name in AccountManager(self.env).get_users():
                return

            # delete used CAPTCHA on success
            try:
                execute_non_query(self.env, "DELETE FROM captcha WHERE id=%s",
                                  req.args['captchaid'])
            except:
                pass

            # log the user in
            req.environ['REMOTE_USER'] = name
            login_module._do_login(req)
Example #3
0
    def authenticate(self, req):
        """Return the name of the remote user, or `None` if the identity of the
        user is unknown."""

        # check for an authenticated user
        login_module = LoginModule(self.env)
        remote_user = login_module.authenticate(req)
        if remote_user:
            return remote_user

        # authenticate via a CAPTCHA
        if 'captchaauth' in req.args and 'captchaid' in req.args:

            # ensure CAPTCHA identification
            captcha = self.captcha(req)
            if captcha != req.args['captchaauth']:
                return 

            # ensure sane identity
            name, email = self.identify(req)
            if name is None:
                return
            if AccountManager and name in AccountManager(self.env).get_users():
                return

            # delete used CAPTCHA on success
            try:
                execute_non_query(self.env, "DELETE FROM captcha WHERE id=%s", req.args['captchaid'])
            except:
                pass

            # log the user in
            req.environ['REMOTE_USER'] = name
            login_module._do_login(req)
Example #4
0
 def process_request(self, req):
     if req.path_info.startswith("/login"):
         self._do_oauth2_login(req)
     elif req.path_info.startswith("/oauth2callback"):
         self._do_callback(req)
     else:
         LoginModule.process_request(self, req)
     req.redirect(self.env.abs_href())
Example #5
0
    def process_request(self, req):
        req.perm.require('CHANGESET_DELETE')

        rm = RepositoryManager(self.env)
        repos = rm.get_repository(req.args['reponame'], True)
        if not repos:
            raise TracError(_('Repository "%(name)s" does not exist.',
                              name=req.args['reponame']))

        if not (repos.owner == req.authname or
                'REPOSITORY_ADMIN' in req.perm):
            message = _('You (%(user)s) are not the owner of "%(name)s"',
                        user=req.authname, name=repos.reponame)
            raise PermissionError(message)

        if req.args.get('confirm'):
            display_rev = repos.display_rev(req.args['rev'])
            rm.delete_changeset(repos, req.args['rev'], req.args.get('ban'))
            add_notice(req, _('The changeset "%(rev)s" has been removed.',
                              rev=display_rev))
            req.redirect(req.href.log(repos.reponame))
        elif req.args.get('cancel'):
            LoginModule(self.env)._redirect_back(req)

        data = {'repository': repos,
                'rev': req.args['rev'],
                'cannot_ban': not rm.can_ban_changesets(repos.type)}

        add_stylesheet(req, 'common/css/admin.css')
        return 'changeset_delete.html', data, None
Example #6
0
    def _do_callback(self, req):
        trac_base_url = self.config.get('project', 'url', TRAC_BASE_URL)
        api_base_url = self.config.get('rackandpin', 'api_base_url', API_BASE_URL)
        client_id = self.config.get('rackandpin', 'client_id', '')
        client_secret = self.config.get('rackandpin', 'client_secret', '')

        token_url = api_base_url + "/o/token/"
        redirect_uri = trac_base_url + '/oauth2callback'
        session = OAuth2Session(client_id, redirect_uri=redirect_uri,
                                state=req.session['OAUTH_STATE'])

        try:
            code = urlparse.parse_qs(req.query_string)["code"][0]
        except Exception:
            raise Exception("Received invalid query parameters.")
        # add_notice(req, "code:%s", code)
        self.env.log.debug("*** Hey, code is %r ***",
                           code)
        self.env.log.debug("*** Hey, token_url is %r ***",
                           token_url)
        token = session.fetch_token(token_url=token_url,
                                    client_secret=client_secret,
                                    code=code,
                                    verify=False)
        req.environ["oauth_token"] = token

        # add_notice(req, "token: %s", token)
        member_authorization_url = "%s/api/username" % api_base_url

        try:
            r = session.get(member_authorization_url)
            authname = r.content
        except Exception:
            self.env.log.debug("*** Hey, this user not authorized ***")
            add_warning(req, """Authorization failed for this user.
                                Contact your production manager""")

            raise Exception("Authorization failed")

        req.environ["REMOTE_USER"] = authname
        #        req.environ["REMOTE_USER"] = "******"
        LoginModule._do_login(self, req)
Example #7
0
    def _process_remove_request(self, req, data):
        """Remove an existing repository."""
        repo = self._get_checked_repository(req, req.args.get('reponame'))

        open_ticket = None
        with self.env.db_transaction as db:
            tickets = db("""SELECT ticket FROM (
                                SELECT src.ticket,
                                       src.value as srcrepo,
                                      dst.value as dstrepo
                                FROM ticket_custom AS src JOIN
                                     ticket_custom AS dst ON
                                     (src.ticket = dst.ticket)
                                WHERE src.name = 'pr_srcrepo' AND
                                      dst.name = 'pr_dstrepo')
                            WHERE srcrepo = %d OR dstrepo = %d
                            """ % (repo.id, repo.id))
            for values in tickets:
                (id,) = values
                ticket = Ticket(self.env, id)
                if ticket['status'] != 'closed':
                    open_ticket = id
                    break

        if open_ticket:
            link = tag.a(_("pull request"), href=req.href.ticket(open_ticket))
            add_warning(req, tag_('The repository "%(name)s can not be '
                                  'removed as it is referenced by an open '
                                  '%(link)s.', name=repo.reponame, link=link))
            LoginModule(self.env)._redirect_back(req)

        if req.args.get('confirm'):
            RepositoryManager(self.env).remove(repo, req.args.get('delete'))
            add_notice(req, _('The repository "%(name)s" has been removed.',
                              name=repo.reponame))
            req.redirect(req.href.repository())
        elif req.args.get('cancel'):
            LoginModule(self.env)._redirect_back(req)

        data.update({'title': _("Remove Repository"),
                     'repository': repo})
Example #8
0
File: auth.py Project: zxfly/trac
class LoginModuleTestCase(unittest.TestCase):

    def setUp(self):
        self.env = EnvironmentStub()
        self.module = LoginModule(self.env)

    def tearDown(self):
        self.env.reset_db()

    def test_anonymous_access(self):
        req = MockRequest(self.env, remote_user=None)
        self.assertIsNone(self.module.authenticate(req))

    def test_unknown_cookie_access(self):
        incookie = Cookie()
        incookie['trac_auth'] = '123'
        req = MockRequest(self.env, remote_user=None)
        self.assertIsNone(self.module.authenticate(req))

    def test_known_cookie_access(self):
        self.env.db_transaction("""
            INSERT INTO auth_cookie (cookie, name, ipnr)
            VALUES ('123', 'john', '127.0.0.1')""")
        req = MockRequest(self.env, remote_user=None)
        req.incookie['trac_auth'] = '123'
        self.assertEqual('john', self.module.authenticate(req))
        self.assertNotIn('auth_cookie', req.outcookie)

    def test_known_cookie_ip_check_enabled(self):
        self.env.config.set('trac', 'check_auth_ip', 'yes')
        self.env.db_transaction("""
            INSERT INTO auth_cookie (cookie, name, ipnr)
            VALUES ('123', 'john', '127.0.0.1')""")
        req = MockRequest(self.env, remote_addr='192.168.0.100',
                          remote_user=None)
        req.incookie['trac_auth'] = '123'
        self.assertIsNone(self.module.authenticate(req))
        self.assertIn('trac_auth', req.outcookie)

    def test_known_cookie_ip_check_disabled(self):
        self.env.config.set('trac', 'check_auth_ip', 'no')
        self.env.db_transaction("""
            INSERT INTO auth_cookie (cookie, name, ipnr)
            VALUES ('123', 'john', '127.0.0.1')""")
        req = MockRequest(self.env, remote_addr='192.168.0.100',
                          remote_user=None)
        req.incookie['trac_auth'] = '123'
        self.assertEqual('john', self.module.authenticate(req))
        self.assertNotIn('auth_cookie', req.outcookie)

    def test_login(self):
        # remote_user must be upper case to test that by default, case is
        # preserved.
        req = MockRequest(self.env, authname='john')
        self.module._do_login(req)

        self.assertIn('trac_auth', req.outcookie, '"trac_auth" Cookie not set')
        auth_cookie = req.outcookie['trac_auth'].value

        self.assertEqual([('john', '127.0.0.1')], self.env.db_query(
            "SELECT name, ipnr FROM auth_cookie WHERE cookie=%s",
            (auth_cookie,)))

    def test_login_ignore_case(self):
        """
        Test that login is succesful when the usernames differ in case, but case
        is ignored.
        """
        self.env.config.set('trac', 'ignore_auth_case', 'yes')

        req = MockRequest(self.env, remote_user='******')

        self.module._do_login(req)

        self.assertIn('trac_auth', req.outcookie, '"trac_auth" Cookie not set')
        auth_cookie = req.outcookie['trac_auth'].value
        self.assertEqual([('john', '127.0.0.1')], self.env.db_query(
            "SELECT name, ipnr FROM auth_cookie WHERE cookie=%s",
            (auth_cookie,)))

    def test_login_no_username(self):
        req = MockRequest(self.env, remote_user=None)
        self.assertRaises(TracError, self.module._do_login, req)

    def test_already_logged_in_same_user(self):
        self.env.db_transaction("""
            INSERT INTO auth_cookie (cookie, name, ipnr)
            VALUES ('123', 'john', '127.0.0.1')""")
        req = MockRequest(self.env, authname='john')
        self.module._do_login(req)  # this shouldn't raise an error

    def test_already_logged_in_different_user(self):
        self.env.db_transaction("""
            INSERT INTO auth_cookie (cookie, name, ipnr)
            VALUES ('123', 'john', '127.0.0.1')""")
        req = MockRequest(self.env, authname='john', remote_user='******')
        self.assertRaises(TracError, self.module._do_login, req)

    def test_logout(self):
        self.env.db_transaction("""
            INSERT INTO auth_cookie (cookie, name, ipnr)
            VALUES ('123', 'john', '127.0.0.1')""")
        req = MockRequest(self.env, authname='john', method='POST')
        self.module._do_logout(req)
        self.assertIn('trac_auth', req.outcookie)
        self.assertFalse(self.env.db_query(
            "SELECT name, ipnr FROM auth_cookie WHERE name='john'"))

    def test_logout_not_logged_in(self):
        req = MockRequest(self.env, method='POST')
        self.module._do_logout(req)  # this shouldn't raise an error

    def test_logout_protect(self):
        self.env.db_transaction("""
            INSERT INTO auth_cookie (cookie, name, ipnr)
            VALUES ('123', 'john', '127.0.0.1')""")
        req = MockRequest(self.env, authname='john')
        self.module._do_logout(req)
        self.assertNotIn('trac_auth', req.outcookie)
        self.assertEqual(
            [('john', '127.0.0.1')],
            self.env.db_query("SELECT name, ipnr FROM auth_cookie "
                              "WHERE cookie='123'"))
Example #9
0
 def setUp(self):
     self.env = EnvironmentStub()
     self.module = LoginModule(self.env)
Example #10
0
class LoginModuleTestCase(unittest.TestCase):

    def setUp(self):
        self.env = EnvironmentStub()
        self.module = LoginModule(self.env)

    def tearDown(self):
        self.env.reset_db()

    def test_anonymous_access(self):
        req = Mock(incookie=Cookie(), href=Href('/trac.cgi'),
                   remote_addr='127.0.0.1', remote_user=None,
                   base_path='/trac.cgi')
        self.assertEqual(None, self.module.authenticate(req))

    def test_unknown_cookie_access(self):
        incookie = Cookie()
        incookie['trac_auth'] = '123'
        req = Mock(cgi_location='/trac', href=Href('/trac.cgi'),
                   incookie=incookie, outcookie=Cookie(),
                   remote_addr='127.0.0.1', remote_user=None,
                   base_path='/trac.cgi')
        self.assertEqual(None, self.module.authenticate(req))

    def test_known_cookie_access(self):
        self.env.db_transaction("""
            INSERT INTO auth_cookie (cookie, name, ipnr)
            VALUES ('123', 'john', '127.0.0.1')""")
        incookie = Cookie()
        incookie['trac_auth'] = '123'
        outcookie = Cookie()
        req = Mock(incookie=incookie, outcookie=outcookie,
                   href=Href('/trac.cgi'), base_path='/trac.cgi',
                   remote_addr='127.0.0.1', remote_user=None)
        self.assertEqual('john', self.module.authenticate(req))
        self.failIf('auth_cookie' in req.outcookie)

    def test_known_cookie_ip_check_enabled(self):
        self.env.config.set('trac', 'check_auth_ip', 'yes')
        self.env.db_transaction("""
            INSERT INTO auth_cookie (cookie, name, ipnr)
            VALUES ('123', 'john', '127.0.0.1')""")
        incookie = Cookie()
        incookie['trac_auth'] = '123'
        outcookie = Cookie()
        req = Mock(cgi_location='/trac', href=Href('/trac.cgi'),
                   incookie=incookie, outcookie=outcookie,
                   remote_addr='192.168.0.100', remote_user=None,
                   base_path='/trac.cgi')
        self.assertEqual(None, self.module.authenticate(req))
        self.failIf('trac_auth' not in req.outcookie)

    def test_known_cookie_ip_check_disabled(self):
        self.env.config.set('trac', 'check_auth_ip', 'no')
        self.env.db_transaction("""
            INSERT INTO auth_cookie (cookie, name, ipnr)
            VALUES ('123', 'john', '127.0.0.1')""")
        incookie = Cookie()
        incookie['trac_auth'] = '123'
        outcookie = Cookie()
        req = Mock(incookie=incookie, outcookie=outcookie,
                   href=Href('/trac.cgi'), base_path='/trac.cgi',
                   remote_addr='192.168.0.100', remote_user=None)
        self.assertEqual('john', self.module.authenticate(req))
        self.failIf('auth_cookie' in req.outcookie)

    def test_login(self):
        outcookie = Cookie()
        # remote_user must be upper case to test that by default, case is
        # preserved.
        req = Mock(cgi_location='/trac', href=Href('/trac.cgi'),
                   incookie=Cookie(), outcookie=outcookie,
                   remote_addr='127.0.0.1', remote_user='******',
                   authname='john', base_path='/trac.cgi')
        self.module._do_login(req)

        assert outcookie.has_key('trac_auth'), '"trac_auth" Cookie not set'
        auth_cookie = outcookie['trac_auth'].value

        self.assertEquals([('john', '127.0.0.1')], self.env.db_query(
            "SELECT name, ipnr FROM auth_cookie WHERE cookie=%s",
            (auth_cookie,)))

    def test_login_ignore_case(self):
        """
        Test that login is succesful when the usernames differ in case, but case
        is ignored.
        """
        self.env.config.set('trac', 'ignore_auth_case', 'yes')

        outcookie = Cookie()
        req = Mock(cgi_location='/trac', href=Href('/trac.cgi'),
                   incookie=Cookie(), outcookie=outcookie,
                   remote_addr='127.0.0.1', remote_user='******',
                   authname='anonymous', base_path='/trac.cgi')
        self.module._do_login(req)

        assert outcookie.has_key('trac_auth'), '"trac_auth" Cookie not set'
        auth_cookie = outcookie['trac_auth'].value
        self.assertEquals([('john', '127.0.0.1')], self.env.db_query(
            "SELECT name, ipnr FROM auth_cookie WHERE cookie=%s",
            (auth_cookie,)))

    def test_login_no_username(self):
        req = Mock(incookie=Cookie(), href=Href('/trac.cgi'),
                   remote_addr='127.0.0.1', remote_user=None,
                   base_path='/trac.cgi')
        self.assertRaises(TracError, self.module._do_login, req)

    def test_already_logged_in_same_user(self):
        self.env.db_transaction("""
            INSERT INTO auth_cookie (cookie, name, ipnr)
            VALUES ('123', 'john', '127.0.0.1')""")
        incookie = Cookie()
        incookie['trac_auth'] = '123'
        req = Mock(incookie=incookie, outcookie=Cookie(),
                   href=Href('/trac.cgi'), base_path='/trac.cgi',
                   remote_addr='127.0.0.1', remote_user='******', authname='john')
        self.module._do_login(req) # this shouldn't raise an error

    def test_already_logged_in_different_user(self):
        self.env.db_transaction("""
            INSERT INTO auth_cookie (cookie, name, ipnr)
            VALUES ('123', 'john', '127.0.0.1')""")
        incookie = Cookie()
        incookie['trac_auth'] = '123'
        req = Mock(incookie=incookie, authname='john',
                   href=Href('/trac.cgi'), base_path='/trac.cgi',
                   remote_addr='127.0.0.1', remote_user='******')
        self.assertRaises(AssertionError, self.module._do_login, req)

    def test_logout(self):
        self.env.db_transaction("""
            INSERT INTO auth_cookie (cookie, name, ipnr)
            VALUES ('123', 'john', '127.0.0.1')""")
        incookie = Cookie()
        incookie['trac_auth'] = '123'
        outcookie = Cookie()
        req = Mock(cgi_location='/trac', href=Href('/trac.cgi'),
                   incookie=incookie, outcookie=outcookie,
                   remote_addr='127.0.0.1', remote_user=None, authname='john',
                   base_path='/trac.cgi')
        self.module._do_logout(req)
        self.failIf('trac_auth' not in outcookie)
        self.failIf(self.env.db_query(
            "SELECT name, ipnr FROM auth_cookie WHERE name='john'"))

    def test_logout_not_logged_in(self):
        req = Mock(cgi_location='/trac', href=Href('/trac.cgi'),
                   incookie=Cookie(), outcookie=Cookie(),
                   remote_addr='127.0.0.1', remote_user=None,
                   authname='anonymous', base_path='/trac.cgi')
        self.module._do_logout(req) # this shouldn't raise an error
Example #11
0
    def pre_process_request(self, req, handler):
        """Called after initial handler selection, and can be used to change
        the selected handler or redirect request.
        
        Always returns the request handler, even if unchanged.
        """

        if req.method == 'GET':
            if req.path_info.strip('/') in ['register', 'login'
                                            ] and req.authname != 'anonymous':
                login_module = LoginModule(self.env)
                login_module._do_logout(req)
                req.redirect(req.href(req.path_info))

        if req.method == 'POST':

            realm = self.realm(req)

            # set the session data for name and email if CAPTCHA-authenticated
            if 'captchaauth' in req.args:
                name, email = self.identify(req)
                for field in 'name', 'email':
                    value = locals()[field]
                    if value:
                        req.session[field] = value
                req.session.save()
                if req.authname != 'anonymous' and realm == 'newticket':
                    req.args['author'] = name
                    if email:
                        req.args['author'] += ' <%s>' % email

            # redirect anonymous user posts that are not CAPTCHA-identified
            if req.authname == 'anonymous' and realm in self.realms:

                if 'captchaauth' in req.args and 'captchaid' in req.args:
                    # add warnings from CAPTCHA authentication
                    captcha = self.captcha(req)
                    if req.args['captchaauth'] != captcha:
                        add_warning(
                            req, "You typed the wrong word. Please try again.")
                        try:
                            # delete used CAPTCHA
                            execute_non_query(
                                self.env, "DELETE FROM captcha WHERE id=%s",
                                req.args['captchaid'])
                        except:
                            pass

                    name, email = self.identify(req)
                    if not name:
                        add_warning(req, 'Please provide your name')
                    if AccountManager and name in AccountManager(
                            self.env).get_users():
                        add_warning(
                            req,
                            '%s is already taken as by a registered user.  Please login or use a different name'
                            % name)

                # redirect to previous location
                location = req.get_header('referer')
                if location:
                    location, query = urllib.splitquery(location)

                    if realm == 'newticket':
                        args = [(key.split('field_', 1)[-1], value)
                                for key, value in req.args.items()
                                if key.startswith('field_')]
                        location += '?%s' % urllib.urlencode(args)
                else:
                    location = req.href()
                req.redirect(location)

        return handler
Example #12
0
 def setUp(self):
     self.env = EnvironmentStub()
     self.db = self.env.get_db_cnx()
     self.module = LoginModule(self.env)
Example #13
0
  def _do_process(self, req):
    """Process grant returned by user.
    """
    code = req.args.get('code')
    next = req.args.get('state') or req.base_path or "/"
    if not code: 
      raise HTTPBadRequest('"code" parameter is missing.')

    try:
      access_token = oauth2.process_code(code)
    except ValueError, err:
      raise HTTPBadRequest('Bad request. %s' % err)
    except AssertionError, err:
      raise HTTPUnauthorized("You are not authorized. %s" % err)

    try:
      info = oauth2.get_authorizations(access_token)
    except ValueError, err:
      raise HTTPInternalError(str(err))

    print "info:", info
    # TODO: 403 if not good authorizations

    # We cannot directly write into req.remote_user, so write in environ
    # and let LoginModule set cookie stuff as needed...
    req.environ['REMOTE_USER'] = info.get('userid')
    LoginModule._do_login(self, req)
    req.redirect(next)

Example #14
0
    def pre_process_request(self, req, handler):
        """Called after initial handler selection, and can be used to change
        the selected handler or redirect request.
        
        Always returns the request handler, even if unchanged.
        """

        if req.method == 'GET':
            if req.path_info.strip('/') in ['register', 'login'] and req.authname != 'anonymous':
                login_module = LoginModule(self.env)
                login_module._do_logout(req)
                req.redirect(req.href(req.path_info))


        if req.method == 'POST':

            realm = self.realm(req)

            # set the session data for name and email if CAPTCHA-authenticated
            if 'captchaauth' in req.args:
                name, email = self.identify(req)
                for field in 'name', 'email':
                    value = locals()[field]
                    if value:
                        req.session[field] = value
                req.session.save()
                if req.authname != 'anonymous' and realm == 'newticket':
                    req.args['author'] = name
                    if email:
                        req.args['author'] += ' <%s>' % email

            # redirect anonymous user posts that are not CAPTCHA-identified
            if req.authname == 'anonymous' and realm in self.realms:
                
                if 'captchaauth' in req.args and 'captchaid' in req.args:
                    # add warnings from CAPTCHA authentication
                    captcha = self.captcha(req)
                    if req.args['captchaauth'] != captcha:
                        add_warning(req, "You typed the wrong word. Please try again.")
                        try:
                            # delete used CAPTCHA
                            execute_non_query(self.env, "DELETE FROM captcha WHERE id=%s", req.args['captchaid'])
                        except:
                            pass

                    name, email = self.identify(req)
                    if not name:
                        add_warning(req, 'Please provide your name')
                    if AccountManager and name in AccountManager(self.env).get_users():
                        add_warning(req, '%s is already taken as by a registered user.  Please login or use a different name' % name)

                # redirect to previous location
                location = req.get_header('referer')
                if location:
                    location, query = urllib.splitquery(location)
                    
                    if realm == 'newticket':
                        args = [(key.split('field_',1)[-1], value)
                                for key, value in req.args.items()
                                if key.startswith('field_')]
                        location += '?%s' % urllib.urlencode(args)
                else:
                    location =  req.href()
                req.redirect(location)

        return handler
Example #15
0
File: auth.py Project: zxfly/trac
 def setUp(self):
     self.env = EnvironmentStub()
     self.module = LoginModule(self.env)
Example #16
0
    def _process_modify_request(self, req, data):
        """Modify an existing repository."""
        repo = self._get_checked_repository(req, req.args.get('reponame'))

        restrict_modifications = False
        if self.restrict_forks and not 'REPOSITORY_ADMIN' in req.perm:
            restrict_modifications = repo.is_fork

        rm = RepositoryManager(self.env)
        base_directory = rm.get_base_directory(repo.type)
        prefix_length = len(base_directory)
        if prefix_length > 0:
            prefix_length += 1

        req.args['name'] = req.args.get('name', repo.reponame)
        req.args['type'] = repo.type
        req.args['dir'] = req.args.get('dir', repo.directory[prefix_length:])
        req.args['owner'] = req.args.get('owner', repo.owner)
        if repo.is_fork:
            req.args['inherit_readers'] = req.args.get('inherit_readers',
                                                       repo.inherit_readers)
        new = self._get_repository_data_from_request(req)

        if req.args.get('modify'):
            if self._check_and_update_repository(req, new, repo):
                rm.modify(repo, new)
                link = tag.a(repo.reponame, href=req.href.browser(new['name']))
                add_notice(req, tag_('The repository "%(link)s" has been '
                                     'modified.', link=link))
                req.redirect(req.href.repository('modify', new['name']))
        elif self._process_role_adding(req, repo):
            req.redirect(req.href(req.path_info))
        elif req.args.get('revoke'):
            selection = req.args.get('selection')
            if selection:
                if not isinstance(selection, list):
                    selection = [selection]
                roles = [role.split(':') for role in selection]
                decode = unicode_from_base64
                roles = [(decode(role[0]), decode(role[1])) for role in roles]
                rm.revoke_roles(repo, roles)
                rm.update_auth_files()
                req.redirect(req.href(req.path_info))
        elif req.args.get('cancel'):
            LoginModule(self.env)._redirect_back(req)

        if repo.is_fork:
            if new['inherit_readers'] != repo.inherit_readers:
                new['dir'] = repo.directory
                rm.modify(repo, new)
                req.redirect(req.href(req.path_info))

        repo_link = tag.a(repo.reponame, href=req.href.browser(repo.reponame))
        possible_maintainers = self._get_possible_maintainers(req)
        data.update({'title': tag_("Modify Repository %(link)s",
                                   link=repo_link),
                     'repository': repo,
                     'new': new,
                     'users': self._get_users(),
                     'groups': self._get_groups(),
                     'possible_maintainers': possible_maintainers,
                     'restrict_modifications': restrict_modifications})
Example #17
0
 def match_request(self, req):
   return req.path_info in ['/auth_server_login', '/auth_server_process'] or \
          LoginModule.match_request(self, req)
Example #18
0
 def setUp(self):
     self.env = EnvironmentStub()
     self.db = self.env.get_db_cnx()
     self.module = LoginModule(self.env)
Example #19
0
class LoginModuleTestCase(unittest.TestCase):
    def setUp(self):
        self.env = EnvironmentStub()
        self.module = LoginModule(self.env)

    def tearDown(self):
        self.env.reset_db()

    def test_anonymous_access(self):
        req = Mock(incookie=Cookie(),
                   href=Href('/trac.cgi'),
                   remote_addr='127.0.0.1',
                   remote_user=None,
                   base_path='/trac.cgi')
        self.assertEqual(None, self.module.authenticate(req))

    def test_unknown_cookie_access(self):
        incookie = Cookie()
        incookie['trac_auth'] = '123'
        req = Mock(cgi_location='/trac',
                   href=Href('/trac.cgi'),
                   incookie=incookie,
                   outcookie=Cookie(),
                   remote_addr='127.0.0.1',
                   remote_user=None,
                   base_path='/trac.cgi')
        self.assertEqual(None, self.module.authenticate(req))

    def test_known_cookie_access(self):
        self.env.db_transaction("""
            INSERT INTO auth_cookie (cookie, name, ipnr)
            VALUES ('123', 'john', '127.0.0.1')""")
        incookie = Cookie()
        incookie['trac_auth'] = '123'
        outcookie = Cookie()
        req = Mock(incookie=incookie,
                   outcookie=outcookie,
                   href=Href('/trac.cgi'),
                   base_path='/trac.cgi',
                   remote_addr='127.0.0.1',
                   remote_user=None)
        self.assertEqual('john', self.module.authenticate(req))
        self.failIf('auth_cookie' in req.outcookie)

    def test_known_cookie_ip_check_enabled(self):
        self.env.config.set('trac', 'check_auth_ip', 'yes')
        self.env.db_transaction("""
            INSERT INTO auth_cookie (cookie, name, ipnr)
            VALUES ('123', 'john', '127.0.0.1')""")
        incookie = Cookie()
        incookie['trac_auth'] = '123'
        outcookie = Cookie()
        req = Mock(cgi_location='/trac',
                   href=Href('/trac.cgi'),
                   incookie=incookie,
                   outcookie=outcookie,
                   remote_addr='192.168.0.100',
                   remote_user=None,
                   base_path='/trac.cgi')
        self.assertEqual(None, self.module.authenticate(req))
        self.failIf('trac_auth' not in req.outcookie)

    def test_known_cookie_ip_check_disabled(self):
        self.env.config.set('trac', 'check_auth_ip', 'no')
        self.env.db_transaction("""
            INSERT INTO auth_cookie (cookie, name, ipnr)
            VALUES ('123', 'john', '127.0.0.1')""")
        incookie = Cookie()
        incookie['trac_auth'] = '123'
        outcookie = Cookie()
        req = Mock(incookie=incookie,
                   outcookie=outcookie,
                   href=Href('/trac.cgi'),
                   base_path='/trac.cgi',
                   remote_addr='192.168.0.100',
                   remote_user=None)
        self.assertEqual('john', self.module.authenticate(req))
        self.failIf('auth_cookie' in req.outcookie)

    def test_login(self):
        outcookie = Cookie()
        # remote_user must be upper case to test that by default, case is
        # preserved.
        req = Mock(cgi_location='/trac',
                   href=Href('/trac.cgi'),
                   incookie=Cookie(),
                   outcookie=outcookie,
                   remote_addr='127.0.0.1',
                   remote_user='******',
                   authname='john',
                   base_path='/trac.cgi')
        self.module._do_login(req)

        assert outcookie.has_key('trac_auth'), '"trac_auth" Cookie not set'
        auth_cookie = outcookie['trac_auth'].value

        self.assertEquals(
            [('john', '127.0.0.1')],
            self.env.db_query(
                "SELECT name, ipnr FROM auth_cookie WHERE cookie=%s",
                (auth_cookie, )))

    def test_login_ignore_case(self):
        """
        Test that login is succesful when the usernames differ in case, but case
        is ignored.
        """
        self.env.config.set('trac', 'ignore_auth_case', 'yes')

        outcookie = Cookie()
        req = Mock(cgi_location='/trac',
                   href=Href('/trac.cgi'),
                   incookie=Cookie(),
                   outcookie=outcookie,
                   remote_addr='127.0.0.1',
                   remote_user='******',
                   authname='anonymous',
                   base_path='/trac.cgi')
        self.module._do_login(req)

        assert outcookie.has_key('trac_auth'), '"trac_auth" Cookie not set'
        auth_cookie = outcookie['trac_auth'].value
        self.assertEquals(
            [('john', '127.0.0.1')],
            self.env.db_query(
                "SELECT name, ipnr FROM auth_cookie WHERE cookie=%s",
                (auth_cookie, )))

    def test_login_no_username(self):
        req = Mock(incookie=Cookie(),
                   href=Href('/trac.cgi'),
                   remote_addr='127.0.0.1',
                   remote_user=None,
                   base_path='/trac.cgi')
        self.assertRaises(TracError, self.module._do_login, req)

    def test_already_logged_in_same_user(self):
        self.env.db_transaction("""
            INSERT INTO auth_cookie (cookie, name, ipnr)
            VALUES ('123', 'john', '127.0.0.1')""")
        incookie = Cookie()
        incookie['trac_auth'] = '123'
        req = Mock(incookie=incookie,
                   outcookie=Cookie(),
                   href=Href('/trac.cgi'),
                   base_path='/trac.cgi',
                   remote_addr='127.0.0.1',
                   remote_user='******',
                   authname='john')
        self.module._do_login(req)  # this shouldn't raise an error

    def test_already_logged_in_different_user(self):
        self.env.db_transaction("""
            INSERT INTO auth_cookie (cookie, name, ipnr)
            VALUES ('123', 'john', '127.0.0.1')""")
        incookie = Cookie()
        incookie['trac_auth'] = '123'
        req = Mock(incookie=incookie,
                   authname='john',
                   href=Href('/trac.cgi'),
                   base_path='/trac.cgi',
                   remote_addr='127.0.0.1',
                   remote_user='******')
        self.assertRaises(AssertionError, self.module._do_login, req)

    def test_logout(self):
        self.env.db_transaction("""
            INSERT INTO auth_cookie (cookie, name, ipnr)
            VALUES ('123', 'john', '127.0.0.1')""")
        incookie = Cookie()
        incookie['trac_auth'] = '123'
        outcookie = Cookie()
        req = Mock(cgi_location='/trac',
                   href=Href('/trac.cgi'),
                   incookie=incookie,
                   outcookie=outcookie,
                   remote_addr='127.0.0.1',
                   remote_user=None,
                   authname='john',
                   base_path='/trac.cgi')
        self.module._do_logout(req)
        self.failIf('trac_auth' not in outcookie)
        self.failIf(
            self.env.db_query(
                "SELECT name, ipnr FROM auth_cookie WHERE name='john'"))

    def test_logout_not_logged_in(self):
        req = Mock(cgi_location='/trac',
                   href=Href('/trac.cgi'),
                   incookie=Cookie(),
                   outcookie=Cookie(),
                   remote_addr='127.0.0.1',
                   remote_user=None,
                   authname='anonymous',
                   base_path='/trac.cgi')
        self.module._do_logout(req)  # this shouldn't raise an error
Example #20
0
 def _get_name_for_cookie(self, req, cookie):
     return LoginModule(self.master_env)._get_name_for_cookie(req, cookie)
Example #21
0
 def match_request(self, req):
     return re.match("/oauth2callback\??.*", req.path_info) or \
         LoginModule.match_request(self, req)