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...

497 lines
20 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 sha
import sys
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
import glasnost.common.xhtmlgenerator as X
from glasnost.proxy.GroupsProxy import getSetContainedIds
from glasnost.server.ObjectsServer import register, Server, \
AdministrableVirtualServer, ObjectServerMixin, AdminServerMixin
from glasnost.server.AuthenticationMethodServer import \
AuthenticationMethodServer
from glasnost.server.tools import *
import glasnost.server.kinds as kinds
applicationName = 'AuthenticationLoginPasswordServer'
applicationRole = 'authentication-login-password'
# FIXME: those are necessary to get access to PeopleServer.pickle; they should
# be removed at the time it is no longer necessary to access this file.
class PeopleVirtualServer: pass
class Person: pass
class AdminPeople: pass
class AccountLoginPassword(ObjectServerMixin, AccountLoginPasswordCommon):
def __repr__(self):
return '<AccountLoginPassword login:%s password:%s>' % (
repr(self.login), repr(self.password))
pass
register(AccountLoginPassword)
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):
def checkModifyIsPossible(self, changes, givenSlotNames = None):
# this change is irreversible
if self.stockPasswordsInClearText == 0 and \
changes.stockPasswordsInClearText == 1:
return 0
return AdminServerMixin.checkModifyIsPossible(self,
changes, givenSlotNames = givenSlotNames)
pass
register(AdminAuthenticationLoginPassword)
class AuthenticationLoginPasswordVirtualServer(AdministrableVirtualServer):
authentications = None
def addAccount(self, userId, authenticationObject):
if not self.getServer().isAdmin():
print 'addAccount(): not admin; TODO should check if allowed'
object = getObject(userId) # can explode; that's ok
virtualServerId = context.getVar('applicationId')
dispatcherId = commonTools.extractDispatcherId(virtualServerId)
if not authenticationObject.login:
raise faults.MissingSlotValue(
authenticationObject.getSlot('login'))
if not self.getServer().getAdminCore().userCanChoosePassword or \
not authenticationObject.password:
authenticationObject.password = commonTools.makepassword()
if not authenticationObject.password:
raise faults.MissingSlotValue(
authenticationObject.getSlot('password'))
if self.authentications is None:
self.authentications = {}
if not self.getServer().getAdminCore().stockPasswordsInClearText:
authenticationObject.password = sha.new(
authenticationObject.password).hexdigest()
self.authentications[userId] = authenticationObject
self.markCoreAsDirty()
try:
self.emailPasswordToUser(object, authenticationObject)
except faults.BadEmailAddress:
pass
try:
self.emailAdminsForNewUser(object, authenticationObject)
except faults.SmtpError:
pass
def checkAuthentication(self, authenticationObject):
if self.authentications is None:
raise faults.WrongLogin(authenticationObject.login)
if not self.getServer().getAdminCore().stockPasswordsInClearText:
authenticationObject.password = sha.new(
authenticationObject.password).hexdigest()
for userId, authObject in self.authentications.items():
if authenticationObject == authObject:
return userId
if authenticationObject.login not in \
[x.login for x in self.authentications.values()]:
raise faults.WrongLogin(authenticationObject.login)
raise faults.WrongPassword('****')
def deleteAccount(self, authenticationObject):
authenticationProxy = getProxyForServerRole('authentication')
if self.authentications is not None:
for userId, authObject in self.authentications.items():
if authObject.login == authenticationObject.login:
if not authenticationProxy.getUserId() == userId and \
not self.getServer().isAdmin():
raise faults.UserAccessDenied()
del self.authentications[userId]
if not self.authentications:
del self.authentications
self.markCoreAsDirty()
return
raise faults.WrongLogin(authenticationObject.login)
def emailAdminsForNewUser(self, object, authenticationObject):
virtualServerId = context.getVar('applicationId')
hostName = getProxyForServerRole('virtualhosts').getHostName(
virtualServerId)
context.setVar('httpHostName', hostName)
message = """\
Dear Glasnost administrators,
A new user (%(userLabel)s) has been registered with username "%(userName)s"
For more information about this user, please see:
%(urlObject)s
"""
messageFileName = commonTools.getConfig(
commonTools.extractDispatcherId(object.id),
'EmailAboutNewUserToAdmins')
messageSubject = commonTools.getConfig(
commonTools.extractDispatcherId(object.id),
'EmailAboutNewUserToAdmins-Subject',
default = '[Glasnost] new user')
if messageFileName:
message = open(messageFileName).read()
message = message % {
'userName': authenticationObject.login,
'urlObject': X.idUrl(object.id).getAsAbsoluteUrl(),
'userLabel': object.getLabel(),
}
toAddresses = self.getAdminEmailAddresses()
sendMail(
mailFrom = toAddresses[0],
mailTo = toAddresses,
mailSubject = messageSubject,
mailMessage = message,
)
def emailPasswordToUser(self, object, authenticationObject):
emailAddress = getEmailForObject(object)
if not emailAddress:
raise faults.BadEmailAddress('')
if not self.getServer().getAdminCore().stockPasswordsInClearText:
# TODO: mail user explaining we can generate a new password for
# him and provide him with an url with a token (so that others
# can't force password changes)
print 'Not sending because passwords are not in plain text'
return
for userId, authObject in self.authentications.items():
if authenticationObject.login == authObject.login:
authenticationObject = authObject
break
else:
raise faults.WrongLogin(authenticationObject.login)
toAddress = [emailAddress]
password = authenticationObject.password
try:
preferencesProxy = getProxyForServerRole('preferences')
preference = preferencesProxy.getPreferenceByUserId(object.id)
language = preference.language
if language == 'None':
language = None
except: # TODO: less generic except
language = None
admin = self.getServer().getAdminCore()
admin.acquireNonCore()
translationsProxy = getProxyForServerRole('translations')
if admin.welcomeEmailSubject:
messageSubject = admin.welcomeEmailSubject
if translationsProxy:
message = translationsProxy.getTranslation(
messageSubject, admin.id, 'self.welcomeEmailSubject',
admin.getLanguage(), [language] )
else:
messageSubject = '[Glasnost] login & password'
if admin.welcomeEmailBody:
message = admin.welcomeEmailBody
if translationsProxy:
message = translationsProxy.getTranslation(
message, admin.id, 'self.welcomeEmailBody',
admin.getLanguage(), [language])
else:
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
"""
virtualServerId = context.getVar('applicationId')
hostName = getProxyForServerRole('virtualhosts').getHostName(
virtualServerId)
message = message % {
'user': object.getLabel(),
'fromAddress': self.adminEmailAddress,
'hostName': hostName,
'login': authenticationObject.login,
'password': authenticationObject.password,
}
fromAddresses = self.getAdminEmailAddresses(stopAsap = 1)
sendMail(
mailFrom = fromAddresses[0],
mailTo = toAddress,
mailSubject = messageSubject,
mailMessage = message,
)
def getAccounts(self):
if not self.getServer().isAdmin():
# TODO: should be a bit more lax about permissions ?
raise faults.UserAccessDenied()
if self.authentications is None:
return []
result = []
for userId, authObject in self.authentications.items():
cleanedAuthObject = AccountLoginPassword()
cleanedAuthObject.login = authObject.login
result.append((userId, cleanedAuthObject.exportToXmlRpc()))
return result
def getAccountUserIdPrivate(self, authenticationObject):
if self.authentications is not None:
for userId, authObject in self.authentications.items():
if authObject.login == authenticationObject.login:
return userId
return ''
def getAccountUserId(self, authenticationObject):
if not self.getServer().isAdmin():
raise faults.UserAccessDenied()
userId = self.getAccountUserIdPrivate(authenticationObject)
if not userId:
raise faults.WrongLogin(authenticationObject.login)
return userId
def getAdminEmailAddresses(self, stopAsap = 0):
virtualServerId = context.getVar('applicationId')
try:
adminIds = getSetContainedIds(
self.admin.adminsSet, ['people'],
raiseWhenUncountable = 1)
except faults.UncountableGroup:
adminIds = []
toAddresses = []
for adminId in adminIds:
try:
administrator = getObject(adminId)
except: # whatever
continue
emailAddress = getEmailForObject(administrator)
if emailAddress:
toAddresses.append(emailAddress)
if stopAsap:
return toAddresses
if not toAddresses:
toAddresses.append(self.adminEmailAddress)
return toAddresses
def getServer(self):
# FIXME: should come from somewhere
"""Return the server string."""
return context.getVar('server')
def hasAccount(self, authenticationObject):
if not self.getServer().isAdmin():
raise faults.UserAccessDenied()
if self.authentications is None:
return 0
for userId, authObject in self.authentications.items():
if authenticationObject.login == authObject.login:
return 1
return 0
def modifyAccount(self, userId, authenticationObject):
authenticationProxy = getProxyForServerRole('authentication')
if not self.getServer().isAdmin() and \
authenticationProxy.getUserId() != userId:
raise faults.UserAccessDenied()
object = getObject(userId) # can explode; that's ok
virtualServerId = context.getVar('applicationId')
dispatcherId = commonTools.extractDispatcherId(virtualServerId)
if not self.getServer().getAdminCore().userCanChoosePassword:
authenticationObject.password = commonTools.makepassword()
if self.authentications is None:
self.authentications = {}
if not self.getServer().getAdminCore().stockPasswordsInClearText:
authenticationObject.password = sha.new(
authenticationObject.password).hexdigest()
self.emailPasswordToUser(getObject(userId), authenticationObject)
self.authentications[userId] = authenticationObject
self.markCoreAsDirty()
class AuthenticationLoginPasswordServer(
AuthenticationLoginPasswordCommonMixin,
AuthenticationMethodServer):
authenticationMethodName = 'login-password'
VirtualServer = AuthenticationLoginPasswordVirtualServer
def emailPassword(self, authenticationDict):
authenticationObject = commonTools.importThing(authenticationDict)
virtualServerId = context.getVar('applicationId')
virtualServer = self.getVirtualServer(virtualServerId)
userId = virtualServer.getAccountUserIdPrivate(authenticationObject)
userObject = getObject(userId)
virtualServer.emailPasswordToUser(userObject, authenticationObject)
def loadVirtualServer(self, virtualServerId):
dispatcherId = commonTools.extractDispatcherId(virtualServerId)
virtualServer = AuthenticationMethodServer.loadVirtualServer(self,
virtualServerId)
if virtualServer.authentications is None:
# 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
print 'Converting PeopleServer data for', virtualServerId
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
authObject = AccountLoginPassword()
authObject.login = object.login
authObject.password = object.password
virtualServer.authentications[object.id] = authObject
del object.login
del object.password
rcFile = open(pickleFilePath, 'wb')
rcFile.write('%s\n' % version)
cPickle.dump(peopleData, rcFile, 1)
rcFile.close()
try:
virtualServer.admin.adminsSet = peopleData.admin.adminsSet
except AttributeError:
pass
try:
virtualServer.admin.userCanChoosePassword = \
peopleData.admin.userCanChoosePassword
except AttributeError:
pass
self.saveVirtualServer(virtualServer)
return virtualServer
def registerPublicMethods(self):
AuthenticationMethodServer.registerPublicMethods(self)
self.registerPublicMethod('emailPassword')
def upgradeVirtualServer_0001_0022(self, virtualServer):
if not hasattr(virtualServer, 'authentications'):
return
if not virtualServer.authentications:
return
for userId in virtualServer.authentications.keys():
login, password = virtualServer.authentications[userId]
authObject = AccountLoginPassword()
authObject.login = login
authObject.password = password
virtualServer.authentications[userId] = authObject
virtualServer.markCoreAsDirty()
def convertVirtualServersIds(self, sourceDispatcherId,
destinationDispatcherId):
exitCode = Server.convertVirtualServersIds(self,
sourceDispatcherId, destinationDispatcherId)
if exitCode is not None:
return exitCode
print 'Converting PeopleServer data from %s to %s' \
% (sourceDispatcherId, destinationDispatcherId)
virtualServerId = commonTools.makeApplicationId(
destinationDispatcherId, self.applicationRole)
virtualServer = self.virtualServers[virtualServerId]
newAuthentications = {}
for (key,object) in virtualServer.authentications.items():
nkey=key.replace(commonTools.extractDispatcherId(sourceDispatcherId),
commonTools.extractDispatcherId(destinationDispatcherId))
newAuthentications[nkey] = object
virtualServer.authentications = newAuthentications
return None
if __name__ == '__main__':
sys.modules['LoginPassword'] = sys.modules['__main__']
AuthenticationLoginPasswordServer().launch(applicationName, applicationRole)