This repository has been archived on 2023-02-21. You can view files and clone it, but cannot push or open issues or pull requests.
glasnost/servers/AuthenticationLoginPassword.../AuthenticationLoginPassword...

367 lines
14 KiB
Python
Executable File

#! /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 Login/Password Authentication Server"""
__version__ = '$Revision$'[11:-2]
import cPickle
import sys
import time
import whrandom
glasnostPythonDir = '/usr/local/lib/glasnost-devel' # changed on make install
sys.path.insert(0, glasnostPythonDir)
import glasnost
from glasnost.common.AuthenticationLoginPasswordCommon import *
import glasnost.common.faults as faults
import glasnost.common.tools_new as commonTools
from glasnost.proxy.DispatcherProxy import getApplicationId, \
getApplicationToken, registerServer, registerVirtualServer
from glasnost.server.ObjectsServer import register, AdministrableServerMixin, \
AdminServerMixin, Server, VirtualServer, AdministrableVirtualServer
from glasnost.server.tools import *
from glasnost.proxy.GroupsProxy import setContains
import glasnost.server.kinds as kinds
applicationName = 'AuthenticationLoginPasswordServer'
applicationRole = 'authentication-login-password'
def getEmailForObject(object):
for slotName in object.getSlotNames():
kind = object.getSlot(slotName).getKind()
if kind.__class__.__name__ == 'Email':
break
else:
return None
return object.getSlot(slotName).getValue()
class AdminAuthenticationLoginPassword(AdminServerMixin,
AdminAuthenticationLoginPasswordCommon):
pass
register(AdminAuthenticationLoginPassword)
class AuthenticationLoginPasswordVirtualServer(AdministrableVirtualServer):
authentications = None
def addAccount(self, userId, tupleInfo):
if not self.getServer().isAdmin():
print 'addAccount(): not admin; TODO should check if allowed'
object = getObject(userId) # can explode; that's ok
if len(tupleInfo) == 2:
authTuple = tupleInfo
elif len(tupleInfo) == 1:
authTuple = (tupleInfo[0], commonTools.makepassword())
else:
raise "FIXME: should not happen"
if self.authentications is None:
self.authentications = {}
self.authentications[userId] = tuple(authTuple)
self.emailPasswordToUser(object, authTuple)
self.emailAdminsForNewUser(object, authTuple)
def checkAuthentication(self, tupleInfo):
if self.authentications is None:
raise faults.WrongLogin(tupleInfo[0])
for userId, authTuple in self.authentications.items():
if authTuple == tuple(tupleInfo):
return userId
if tupleInfo[0] not in [x[0] for x in self.authentications.values()]:
raise faults.WrongLogin(tupleInfo[0])
raise faults.WrongPassword('****')
def deleteAccount(self, partialAccount):
if not self.getServer().isAdmin():
# FIXME: may a user remove its account ?
raise faults.UserAccessDenied()
partialAccount = tuple(partialAccount)
if self.authentications is not None:
for userId, authTuple in self.authentications.items():
if authTuple[:len(partialAccount)] == partialAccount:
del self.authentications[userId]
if not self.authentications:
del self.authentications
return
raise faults.WrongLogin(partialAccount[0])
def emailAdminsForNewUser(self, object, authTuple):
# FIXME: complete this method :)
message = """\
Dear Glasnost administrators,
A new user has been registered with username "%(userName)s".
For more information about this user, please see:
<FIXME (insert URL to user object)>
""" % {
'userName': authTuple[0],
}
def emailPasswordToUser(self, object, authTuple):
email = getEmailForObject(object)
if not email:
return
toAddresses = [email]
fromAddress = 'root@localhost' # FIXME: get admin email
password = authTuple[1]
try:
preferencesProxy = getProxyForServerRole('preferences')
preference = preferencesProxy.getPreferenceByUserId(object.id)
language = preference.language
if language == 'None':
language = None
except: # TODO: less generic except
language = None
if not language:
# TODO: if no preferences set; get language from virtualhost
pass
if not language:
language = 'en'
messageFileName = commonTools.getConfig(
commonTools.extractDispatcherId(object.id),
'WelcomeEmail-%s' % language)
messageSubject = commonTools.getConfig(
commonTools.extractDispatcherId(object.id),
'WelcomeEmailSubject',
default = '[Glasnost] login & password')
message = """\
Here are the Glasnost login & password you have requested.
Web Site: %(hostName)s
User: %(user)s
Login: %(login)s
Password: %(password)s
The Glasnost administrator - %(fromAddress)s
"""
print 'messageFileName:', messageFileName
if messageFileName:
message = open(messageFileName).read()
virtualServerId = context.getVar('applicationId')
hostName = getProxyForServerRole('virtualhosts').getHostName(
virtualServerId)
message = message % {
'user': object.getLabel(),
'fromAddress': fromAddress,
'hostName': hostName,
'login': authTuple[0],
'password': authTuple[1],
}
sendMail(
mailFrom = fromAddress,
mailTo = toAddresses,
mailSubject = messageSubject,
mailMessage = message,
)
def getAccounts(self):
if not self.getServer().isAdmin():
# FIXME: should be a bit more lax about permissions ?
raise faults.UserAccessDenied()
if self.authentications is None:
return []
return [ (x, (y[0],)) for x,y in self.authentications.items() ]
def getAccountUserId(self, partialAccount):
if not self.getServer().isAdmin():
print 'FIXME: getAccountUserId(): check that user is allowed.'
if self.authentications is not None:
for userId, authTuple in self.authentications.items():
if authTuple[:len(partialAccount)] == partialAccount:
return userId
raise faults.WrongLogin(partialAccount[0])
def getServer(self): # FIXME: should come from somewhere
"""Return the server string."""
return context.getVar('server')
def hasAccount(self, partialAccount):
if not self.getServer().isAdmin():
print 'FIXME: hasAccount(): TODO: check that user is allowed.'
if self.authentications is None:
return 0
for userId, authTuple in self.authentications.items():
if authTuple[:len(partialAccount)] == partialAccount:
return 1
return 0
class AuthenticationLoginPasswordServer(
AuthenticationLoginPasswordCommonMixin,
AdministrableServerMixin, Server):
authenticationMethodName = 'login-password'
VirtualServer = AuthenticationLoginPasswordVirtualServer
def addAccount(self, userId, tupleInfo):
virtualServerId = context.getVar('applicationId')
virtualServer = self.getVirtualServer(virtualServerId)
result = virtualServer.addAccount(userId, tupleInfo)
return result
def checkAuthentication(self, tupleInfo):
virtualServerId = context.getVar('applicationId')
print 'virtualServerId', virtualServerId
print self.virtualServers[virtualServerId].virtualServerId
virtualServer = self.getVirtualServer(virtualServerId)
return virtualServer.checkAuthentication(tupleInfo)
def deleteAccount(self, partialAccount):
virtualServerId = context.getVar('applicationId')
virtualServer = self.getVirtualServer(virtualServerId)
virtualServer.deleteAccount(partialAccount)
def getAccounts(self):
virtualServerId = context.getVar('applicationId')
virtualServer = self.getVirtualServer(virtualServerId)
return virtualServer.getAccounts()
def getAccountUserId(self, partialAccount):
virtualServerId = context.getVar('applicationId')
virtualServer = self.getVirtualServer(virtualServerId)
return virtualServer.getAccountUserId(partialAccount)
def getSlotNamesAndKindsXmlRpc(self, action):
login = kinds.String()
login.isRequired = 1
login.isTranslatable = 0
login.label = N_('Username')
if action != 'login':
return [('login', login.exportToXmlRpc())]
password = kinds.Password()
password.widgetName = 'InputPassword'
password.isRequired = 1
password.label = N_('Password')
return [('login', login.exportToXmlRpc()),
('password', password.exportToXmlRpc())]
def hasAccount(self, partialAccount):
virtualServerId = context.getVar('applicationId')
virtualServer = self.getVirtualServer(virtualServerId)
return virtualServer.hasAccount(partialAccount)
def loadVirtualServer(self, virtualServerId):
dispatcherId = commonTools.extractDispatcherId(virtualServerId)
virtualServer = Server.loadVirtualServer(self, virtualServerId)
if virtualServer.authentications is None:
print 'Converting PeopleServer data for', virtualServerId
# no authentication; let's look into PeopleServer data if it has
# interesting informations about login/password
pickleFilePath = os.path.join(
virtualServer.dataDirectoryPath, 'PeopleServer.pickle')
if not os.access(pickleFilePath, os.F_OK):
return virtualServer
rcFile = open(pickleFilePath, 'rb')
version = self.readFileVersion(rcFile)
peopleData = cPickle.load(rcFile)
rcFile.close()
virtualServer.authentications = {}
for object in peopleData.objects.values():
if not (hasattr(object, 'login') and
hasattr(object, 'password')):
continue
virtualServer.authentications[object.id] = (
object.login, object.password)
del object.login
del object.password
rcFile = open(pickleFilePath, 'wb')
rcFile.write('%s\n' % version)
cPickle.dump(peopleData, rcFile, 1)
rcFile.close()
self.saveVirtualServer(virtualServer)
return virtualServer
def registerPublicMethods(self):
Server.registerPublicMethods(self)
AdministrableServerMixin.registerPublicMethods(self)
self.registerPublicMethod('addAccount')
self.registerPublicMethod('checkAuthentication')
self.registerPublicMethod('deleteAccount')
self.registerPublicMethod('getAccounts')
self.registerPublicMethod('getAccountUserId')
self.registerPublicMethod('hasAccount')
self.registerPublicMethod('getSlotNamesAndKinds',
self.getSlotNamesAndKindsXmlRpc)
def startRpcServer(self):
Server.startRpcServer(self)
authenticationProxy = getProxyForServerRole('authentication')
while 1:
try:
authenticationProxy.registerAuthenticationMethod(
self.authenticationMethodName)
except faults.UnknownServerId:
time.sleep(1)
continue
break
if __name__ == '__main__':
sys.modules['LoginPassword'] = sys.modules['__main__']
AuthenticationLoginPasswordServer().launch(applicationName, applicationRole)