# Copyright (C) 2005 JanRain, Inc.
# Copyright (C) 2009, 2010 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from apache_openid import logging
from apache_openid.handlers.openid.authenticator import Authenticator
from apache_openid.handlers.openidteams.mixins import CookiedTeamsMixin

class TeamsAuthenticator(Authenticator, CookiedTeamsMixin):
    def __init__(self, request, options, session):
        super(TeamsAuthenticator, self).__init__(request, options)
        self.session = session

    def authenticate(self, openid):
        """Check to see if any of the cookied teams are authorized."""
        if openid is None:
            return False
        elif len(self.authorized_teams) > 0:
            return self.check_team_entitlement(self.authorized_teams,
                self.cookied_teams)
        else:
            logging.debug('Team support disabled, or no authorized teams '
                'configured.')
            return super(TeamsAuthenticator, self).authenticate(openid)

    def check_team_entitlement(self, allowed_teams, user_teams):
        logging.debug("Authorized Teams: %r", ', '.join(allowed_teams))
        logging.debug("Cookied Teams: %r", ', '.join(user_teams))
        for team in user_teams:
            if team in allowed_teams:
                logging.debug('Allowed user %r - team %r',
                    self.request.cookied_user, team)
                return True
        logging.error('Access denied to %r for %r (teams: %r)',
            self.request.uri, self.request.cookied_user, user_teams)
        return False
