#!/usr/bin/env python
# -*- coding: iso-8859-15 -*-


# Glasnost
# By: Odile Bénassy <obenassy@entrouvert.com>
#     Romain Chantereau <rchantereau@entrouvert.com>
#     Nicolas Clapiès <nclapies@easter-eggs.org>
#     Pierre-Antoine Dejace <padejace@entrouvert.be>
#     Thierry Dulieu <tdulieu@easter-eggs.com>
#     Florent Monnier <monnier@codelutin.com>
#     Cédric Musso <cmusso@easter-eggs.org>
#     Frédéric Péters <fpeters@entrouvert.be>
#     Benjamin Poussin <poussin@codelutin.com>
#     Emmanuel Raviart <eraviart@entrouvert.com>
#     Sébastien Régnier <regnier@codelutin.com>
#     Emmanuel Saracco <esaracco@easter-eggs.com>
#
# Copyright (C) 2000, 2001 Easter-eggs & Emmanuel Raviart
# Copyright (C) 2002 Odile Bénassy, Code Lutin, Thierry Dulieu, Easter-eggs,
#     Entr'ouvert, Frédéric Péters, Benjamin Poussin, Emmanuel Raviart,
#     Emmanuel Saracco & Théridion
# Copyright (C) 2003 Odile Bénassy, Romain Chantereau, Nicolas Clapiès,
#     Code Lutin, Pierre-Antoine Dejace, Thierry Dulieu, Easter-eggs,
#     Entr'ouvert, Florent Monnier, Cédric Musso, Ouvaton, Frédéric Péters,
#     Benjamin Poussin, Rodolphe Quiédeville, Emmanuel Raviart, Sébastien
#     Régnier, Emmanuel Saracco, Théridion & Vecam
#
# 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 2
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


__doc__ = """Glasnost Token Accounts Server"""

__version__ = '$Revision$'[11:-2]


import copy
import md5
import sha
import sys
import time
import whrandom

glasnostPythonDir = '/usr/local/lib/glasnost-devel' # changed on make install
sys.path.insert(0, glasnostPythonDir)

import glasnost

import glasnost.common.context as context
import glasnost.common.faults as faults
import glasnost.common.TokenAccountsCommon as commonTokenAccounts
from glasnost.common.tools import iso8859_15, sendMail
import glasnost.common.tools_new as commonTools

import glasnost.server.ObjectsServer as objects

from glasnost.proxy.GroupsProxy import getSetContainedIds
from glasnost.proxy.tools import getObject, getProxy, getProxyForServerRole


applicationName = 'TokenAccountsServer'
applicationRole = 'tokenaccounts'
dispatcher = None


class AdminTokenAccounts(objects.AdminServerMixin,
                         commonTokenAccounts.AdminTokenAccounts):
    pass
objects.register(AdminTokenAccounts)


class TokenAccount(objects.ObjectServerMixin,
                   commonTokenAccounts.TokenAccount):
    pass
objects.register(TokenAccount)


class TokenAccountsVirtualServer(objects.ObjectsVirtualServer):
    objectsByToken = None

    def init(self):
        objects.ObjectsVirtualServer.init(self)
        self.objectsByToken = {}


class TokenAccountsServer(
        commonTokenAccounts.TokenAccountsCommonMixin,
        objects.ObjectsServer):
    VirtualServer = TokenAccountsVirtualServer

    def addObjectXmlRpc(self, objectImport):
        objectId = objects.ObjectsServer.addObjectXmlRpc(self, objectImport)
        virtualServerId = context.getVar('applicationId')
        virtualServer = self.getVirtualServer(virtualServerId)
        object = virtualServer.loadObjectCore(objectId)
        while 1:
            randomSalt = str(self.randomGenerator.uniform(0.1, 1))[2:]
            token = md5.new(randomSalt).hexdigest()[:16].upper()
            token = '%s-%s-%s-%s' % (
                    token[:4], token[4:8], token[8:12], token[12:])
            if not virtualServer.objectsByToken.has_key(token):
                object.token = token
                break
        virtualServer.objectsByToken[object.token] = object

        virtualServer.markCoreAsDirty()
        return objectId

    def checkObjectAuthenticationXmlRpc(self, tokenImport):
        virtualServerId = context.getVar('applicationId')
        virtualServer = self.getVirtualServer(virtualServerId)
        token = iso8859_15(tokenImport)
        if not virtualServer.objectsByToken.has_key(token):
            raise faults.WrongToken(token)
        object = virtualServer.objectsByToken[token]
        if object.expirationTime and time.time() > object.expirationTime:
            del virtualServer.objectsByToken[token]
            virtualServer.markCoreAsDirty()
            raise faults.WrongToken(token)
        identitiesProxy = getProxy(object.identityId)
        del virtualServer.objectsByToken[token]
        virtualServer.markCoreAsDirty()
        userToken = identitiesProxy.getUserToken(object.identityId)
        if object.type == 'universal':
            pass
        elif object.type in ('activation', 'reactivation', 'revocation'):
            context.push(userToken = userToken)
            identitiesProxy.changeStatus(object.identityId, object.type)
            identitiesProxy.deleteUserToken()
            context.pull()
            return ['', 'token']
        else:
            print 'Unknown token type:', object.type
            return ['', 'token']

        return [userToken, 'token']

    def init(self):
        self.randomGenerator = whrandom.whrandom()
        objects.ObjectsServer.init(self)
        
    def registerPublicMethods(self):
        objects.ObjectsServer.registerPublicMethods(self)
        self.registerPublicMethod('checkObjectAuthentication',
                                  self.checkObjectAuthenticationXmlRpc)


tokenAccountsServer = TokenAccountsServer()


if __name__ == "__main__":
    tokenAccountsServer.launch(applicationName, applicationRole)

