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/shared/web/AuthenticationLoginPassword...

617 lines
24 KiB
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 Authentication (Login/Password) Web"""
__version__ = '$Revision$'[11:-2]
import cgi
import glasnost.common.context as context
import glasnost.common.faults as faults
from glasnost.common.ObjectsCommon import *
import glasnost.common.slots as slots
import glasnost.common.translation as translation
import glasnost.common.tools_new as commonTools
from glasnost.proxy.AuthenticationLoginPasswordProxy import *
from ObjectsWeb import register, AdminWithoutWritersMixin, \
AdministrableWebMixin, BaseObjectWebMixin
from tools import *
class AdminAuthenticationLoginPassword(AdminWithoutWritersMixin,
AdminAuthenticationLoginPassword):
stockPasswordsInClearText_kind_stateInEditMode = 'hidden'
stockPasswordsInClearText_kind_stateInViewMode = 'hidden'
stockPasswordsInClearText_kind_widgetName = 'InputCheckBox'
userCanChoosePassword_kind_defaultValue = 0
userCanChoosePassword_kind_widget_fieldLabel = N_('Password')
userCanChoosePassword_kind_widget_labels = {
'0': N_('Automatically Generated'),
'1': N_('User Choice'),
}
userCanChoosePassword_kind_widgetName = 'InputCheckBox'
register(AdminAuthenticationLoginPassword)
class AccountLoginPassword(BaseObjectWebMixin, AccountLoginPassword):
login_kind_balloonHelp = N_('Enter the username you use on this site.')
password_kind_balloonHelp = N_('Enter your password.')
skipPassword = 1
def getEditLayoutSlotNames(self, fields, parentSlot = None):
slotNames = BaseObjectWebMixin.getEditLayoutSlotNames(self,
fields, parentSlot = parentSlot)
if self.skipPassword:
slotNames.remove('password')
return slotNames
register(AccountLoginPassword)
class ChangingPassword(BaseObjectWebMixin, ObjectCommon):
id_kindName = None
language_kindName = None
currentPassword = None
currentPassword_kind_balloonHelp = N_('Enter your current password.')
currentPassword_kind_isRequired = 1
currentPassword_kind_isTranslatable = 0
currentPassword_kind_widget_fieldLabel = N_('Current Password')
currentPassword_kind_widget_size = 15
currentPassword_kind_widgetName = 'InputPassword'
currentPassword_kindName = 'Password'
newPassword = None
newPassword_kind_balloonHelp = N_('Enter your new password.')
newPassword_kind_isRequired = 1
newPassword_kind_isTranslatable = 0
newPassword_kind_widget_fieldLabel = N_('New Password')
newPassword_kind_widget_size = 15
newPassword_kind_widgetName = 'InputPassword'
newPassword_kindName = 'Password'
new2Password = None
new2Password_kind_balloonHelp = N_('Re-enter your new password.')
new2Password_kind_isRequired = 1
new2Password_kind_isTranslatable = 0
new2Password_kind_widget_fieldLabel = N_('New Password (Confirmation)')
new2Password_kind_widget_size = 15
new2Password_kind_widgetName = 'InputPassword'
new2Password_kindName = 'Password'
version_kindName = None
def getOrderedLayoutSlotNames(self, parentSlot = None):
slotNames = ObjectCommon.getOrderedLayoutSlotNames(
self, parentSlot = parentSlot)
slotNames += ['currentPassword', 'newPassword', 'new2Password']
return slotNames
class ChangingUserPassword(BaseObjectWebMixin, ObjectCommon):
id_kindName = None
language_kindName = None
login = None
login_kind_widget_fieldLabel = N_('Username')
login_kind_stateInEditMode = 'read-only'
login_kindName = 'String'
password = None
password_kind_balloonHelp = N_('Enter the password.')
password_kind_isRequired = 1
password_kind_isTranslatable = 0
password_kind_widget_fieldLabel = N_('Password')
password_kind_widget_size = 15
password_kind_widgetName = 'InputPassword'
password_kindName = 'Password'
def getOrderedLayoutSlotNames(self, parentSlot = None):
slotNames = ObjectCommon.getOrderedLayoutSlotNames(
self, parentSlot = parentSlot)
slotNames += ['login', 'password',]
return slotNames
class AuthenticationLoginPasswordWeb(AdministrableWebMixin,
AuthenticationLoginPasswordProxy):
def changePassword(self):
if not self.getAdmin().userCanChoosePassword:
return accessForbidden()
passwordChange = ChangingPassword()
return self.changePasswordObject(passwordChange)
changePassword.isPublicForWeb = 1
def changePasswordObject(self, object):
context.push(_level = 'index', layoutMode = 'edit')
try:
layout = X.array()
if context.getVar('error'):
layout += object.getErrorLayout()
form = X.form(
action = X.actionUrl('changePasswordSubmit'),
enctype= 'multipart/form-data', method = 'post')
layout += form
form += object.getEditLayout(fields = None)
form += X.div(_class = 'buttons-bar')(
X.span(_class = 'action-buttons-bar')(
X.buttonInForm('ok', 'okButton')),
)
return writePageLayout(layout, _('Changing Password'))
finally:
context.pull(_level = 'index')
def changePasswordSubmit(self, **keywords):
if keywords is None:
keywords = {}
if not context.getVar('userToken'):
return accessForbidden()
admin = self.getAdmin()
if not admin.userCanChoosePassword:
return accessForbidden(dontAskForLogin = 1)
passwordChange = ChangingPassword()
passwordChange.submitFields(keywords)
if not context.getVar('error'):
authProxy = getProxyForServerRole('authentication')
authObject = authProxy.getAuthObject()
if authObject.password != passwordChange.currentPassword:
slot = passwordChange.getSlot('currentPassword')
passwordChange.setError(slot.getPath(), faults.BadValue)
context.setVar('error', 1)
if passwordChange.newPassword != passwordChange.new2Password:
context.setVar('error', 1)
if context.getVar('error'):
passwordChange.newPassword = ''
passwordChange.new2Password = ''
return self.changePasswordObject(passwordChange)
authObject.password = passwordChange.newPassword
self.modifyAccount(context.getVar('userId'), authObject)
return success(
_('The password has been modified successfully.'),
X.rootUrl())
changePasswordSubmit.isPublicForWeb = 1
def changeUserPassword(self, account):
if not self.getAdmin().userCanChoosePassword:
return accessForbidden(dontAskForLogin = 1)
if not self.isAdmin():
return accessForbidden()
passwordChange = ChangingUserPassword()
passwordChange.login = account
return self.changeUserPasswordObject(passwordChange)
changeUserPassword.isPublicForWeb = 1
def changeUserPasswordObject(self, object):
context.push(_level = 'index', layoutMode = 'edit')
try:
layout = X.array()
if context.getVar('error'):
layout += object.getErrorLayout()
form = X.form(
action = X.actionUrl('changeUserPasswordSubmit'),
enctype= 'multipart/form-data', method = 'post')
layout += form
form += object.getEditLayout(fields = None)
form += X.div(_class = 'buttons-bar')(
X.span(_class = 'action-buttons-bar')(
X.buttonInForm('ok', 'okButton')),
)
return writePageLayout(layout, _('Changing User Password'))
finally:
context.pull(_level = 'index')
def changeUserPasswordSubmit(self, **keywords):
if keywords is None:
keywords = {}
if not self.getAdmin().userCanChoosePassword:
return accessForbidden(dontAskForLogin = 1)
if not self.isAdmin():
return accessForbidden()
passwordChange = ChangingUserPassword()
passwordChange.submitFields(keywords)
if context.getVar('again'):
return self.changeUserPasswordObject(passwordChange)
authObject = self.newAuthenticationObject()
authObject.login = passwordChange.login
authObject.password = passwordChange.password
self.modifyAccount(
self.getAccountUserId(authObject), authObject)
return success(
_('The password has been modified successfully.'),
X.roleUrl('authentication'))
changeUserPasswordSubmit.isPublicForWeb = 1
def createAccount(self, userId):
authObject = self.newAuthenticationObject()
userCardObject = getObject(userId)
return self.newAccountObject(userCardObject, authObject)
createAccount.isPublicForWeb = 1
def delete(self, account):
if not self.isAdmin():
return accessForbidden()
layout = X.array(
X.p()(_("""Remove both the account and the user card ?""")),
# TODO: note about the use of an user card without account
X.div(_class = 'buttons-bar')(
X.buttonStandalone(_('Remove Both'),
X.actionUrl('deleteAccountAndUser/%s' % account)),
X.buttonStandalone(_('Keep the user card'),
X.actionUrl('deleteAccount/%s' % account)),
X.buttonStandalone(_('Keep both'),
X.roleUrl('authentication'))
)
)
return writePageLayout(layout, _('Delete Account'), canCache = 0)
delete.isPublicForWeb = 1
def deleteAccount(self, account):
if not self.isAdmin():
return accessForbidden()
authObject = self.newAuthenticationObject()
authObject.login = account
try:
AuthenticationLoginPasswordProxy.deleteAccount(self, authObject)
except faults.BaseFault: # FIXME: be more precise
return failure(_('Failed to remove the account.'),
X.roleUrl('authentication'))
return success(
_('The account has been removed successfully.'),
X.roleUrl('authentication'))
deleteAccount.isPublicForWeb = 1
def deleteAccountAndUser(self, account):
if not self.isAdmin():
return accessForbidden()
authObject = self.newAuthenticationObject()
authObject.login = account
try:
userId = self.getAccountUserId(authObject)
AuthenticationLoginPasswordProxy.deleteAccount(self, authObject)
userWeb = getWeb(userId)
userWeb.deleteObject(userId)
except faults.BaseFault: # be more precise
return failure(_('Failed to remove the account or the user card.'),
X.roleUrl('authentication'))
return success(
_('The account and the user card have been removed successfully.'),
X.roleUrl('authentication'))
deleteAccountAndUser.isPublicForWeb = 1
def emailPasswordToUser(self, account):
if not self.isAdmin():
return accessForbidden()
authObject = self.newAuthenticationObject()
authObject.login = account
try:
self.emailPassword(authObject)
except faults.SmtpError:
return failure(_("""\
A SMTP error occured when trying to send the password.
Maybe the Mail Transport Agent on the Glasnost server is not
correctly configured.\
"""), X.rootUrl())
return success(_('The password has been sent successfully.'),
X.rootUrl())
emailPasswordToUser.isPublicForWeb = 1
def getMenuCommands(self):
userToken = context.getVar('userToken')
admin = self.getAdmin()
options = []
usercardWeb = getProxyForServerRole('people')
if (not userToken or self.isAdmin()) and usercardWeb.canAddObject():
options.append(
X.a(href = X.roleUrl(self.serverRole, 'newAccount'))(
_('New Account')))
if userToken and admin.userCanChoosePassword:
options.append(
X.a(href = X.roleUrl(self.serverRole, 'changePassword'))(
_('Change Password')))
if self.isAdmin():
accounts = self.getAccounts()
accountsMenu = X.select(name = 'account')
for userId, account in accounts.items():
try:
label = getObjectLabelTranslated(userId,
context.getVar('readLanguages'))
except faults.MissingItem:
label = _('Missing Object (%s)') % account.login
accountsMenu += X.option(
value = cgi.escape(account.login))(label)
else:
accounts = {}
if self.isAdmin() and admin.userCanChoosePassword and accounts:
options.append(
X.form(
action = X.roleUrl(self.serverRole,
'changeUserPassword'),
method = 'post', enctype = 'multipart/form-data')(
X.asIs(_('Change password for user:')),
accountsMenu,
X.buttonInForm('ok', 'ok')))
if self.isAdmin() and accounts:
options.append(
X.form(
action = X.roleUrl(self.serverRole,
'delete'),
method = 'post', enctype = 'multipart/form-data')(
X.asIs(_('Delete Account:')),
accountsMenu,
X.buttonInForm('ok', 'ok')))
if self.isAdmin() and accounts:
options.append(
X.form(
action = X.roleUrl(self.serverRole,
'emailPasswordToUser'),
method = 'post', enctype = 'multipart/form-data')(
X.asIs(_('Send password to:')),
accountsMenu,
X.buttonInForm('ok', 'ok')))
if self.isAdmin(): # or not userToken
userIds = getProxyForServerRole('people').getObjectIds()
for k in accounts.keys():
userIds.remove(k)
if userIds:
usersMenu = X.select(name = 'userId')
for userId in userIds:
label = getObjectLabelTranslated(userId,
context.getVar('readLanguages'))
usersMenu += X.option(value = userId)(label)
options.append(
X.form(
action = X.roleUrl(self.serverRole,
'createAccount'),
method = 'post', enctype = 'multipart/form-data')(
X.asIs(_('Create Account for user:')),
usersMenu,
X.buttonInForm('ok', 'ok')))
return options
def getViewAllButtonsBarLayout(self):
layout = X.div(_class = 'buttons-bar')
userToken = context.getVar('userToken')
if self.canModifyAdmin() and userToken:
layout += X.buttonStandalone('settings', X.actionUrl('admin'))
return layout
def login(self, access = ''):
authObject = AccountLoginPassword()
return self.loginObject(authObject, access)
login.isPublicForWeb = 1
def loginObject(self, object, access = ''):
req = context.getVar('req')
req.headers_out['Cache-Control'] = 'no-cache, must-revalidate'
req.headers_out['Pragma'] = 'no-cache'
object.skipPassword = 0
context.push(_level = 'index', layoutMode = 'edit')
try:
layout = X.array()
if access == 'forbidden':
layout += X.p(_(
'To access this part of the site, you need to sign in.'))
if context.getVar('error'):
layout += object.getErrorLayout()
submitUrl = X.roleUrl(self.serverRole, 'loginSubmit')
if context.getVar('virtualHost').useHTTPS:
hostNameAndPort = commonTools.makeHttpHostNameAndPort(
context.getVar('httpHostName'),
context.getVar('httpPort'))
submitUrl = 'https://%s%s' % (hostNameAndPort, submitUrl)
form = X.form(action = submitUrl, enctype = 'multipart/form-data',
method = 'post')
layout += form
form += object.getEditLayout(fields = None)
if context.getVar('nextUri'):
form += X.div(X.input(name = 'nextUri', type = 'hidden',
value = context.getVar('nextUri')))
buttonsBar = X.div(_class = 'buttons-bar')
form += buttonsBar
buttonsBar += X.buttonInForm('login', 'loginButton')
if 1: # TODO: check if emailPassword is available
buttonsBar += X.buttonInForm(
'send-password-by-email', 'sendButton')
return writePageLayout(layout, _('Login'))
finally:
context.pull(_level = 'index')
login.isPublicForWeb = 1
def loginSubmit(self, **keywords):
if keywords is None:
keywords = {}
sendPasswordByEmail = isButtonSelected('sendButton', keywords)
authObject = self.newAuthenticationObject()
authObject.submitFields(keywords)
if context.getVar('again'):
return self.loginObject(authObject)
if sendPasswordByEmail:
try:
self.emailPassword(authObject)
except:
return failure(_('An error occured while sending the password.'),
X.rootUrl())
return success(_('The password has been sent successfully.'), X.rootUrl())
authWeb = getWebForServerRole('authentication')
try:
return authWeb.loginSubmitted(
'login-password', authObject)
except faults.WrongLogin, f:
context.getVar('error', 1)
authObject.setError('self.login', f)
return self.loginObject(authObject)
except faults.WrongPassword, f:
context.getVar('error', 1)
authObject.setError('self.password', f)
return self.loginObject(authObject)
except:
if context.getVar('debug'):
raise
return accessForbidden()
loginSubmit.isPublicForWeb = 1
def newAccount(self):
usercardWeb = getProxyForServerRole('people')
if not usercardWeb.canAddObject():
return accessForbidden()
userCardObject = usercardWeb.newObject()
authObject = self.newAuthenticationObject()
return self.newAccountObject(userCardObject, authObject)
def newAccountObject(self, userCardObject, authObject):
userCardSlot = slots.Root(userCardObject, name = 'userCard')
context.push(_level = 'index', layoutMode = 'edit')
try:
layout = X.array()
if context.getVar('error'):
layout += userCardObject.getErrorLayout()
form = X.form(action = X.actionUrl('newAccountSubmit'),
method = 'post')
layout += form
if userCardObject.id:
slot = userCardObject.getSlot('id', parentSlot = userCardSlot)
widget = slot.getKind().getModelWidget(slot)
form += widget.getModelHiddenLayout(slot, None)
form += userCardObject.getViewLayout(
fields = None, parentSlot = userCardSlot)
else:
form += userCardObject.getEditLayout(
fields = None, parentSlot = userCardSlot)
form += authObject.getEditLayout(fields = None)
form += X.div(_class = 'buttons-bar')(
X.span(_class = 'action-buttons-bar')(
X.buttonInForm('create', 'createButton')),
)
return writePageLayout(layout, _('New Account'))
finally:
context.pull(_level = 'index')
newAccount.isPublicForWeb = 1
def newAccountSubmit(self, **keywords):
if keywords is None:
keywords = {}
usercardWeb = getProxyForServerRole('people')
if not usercardWeb.canAddObject():
return accessForbidden()
userCardObject = usercardWeb.newObject()
userCardSlot = slots.Root(userCardObject, name = 'userCard')
userCardObject.submitFields(keywords, parentSlot = userCardSlot)
if userCardObject.id:
context.delVar('again')
userCardObject = getObject(userCardObject.id)
authObject = self.newAuthenticationObject()
authObject.submitFields(keywords)
if context.getVar('again'):
return self.newAccountObject(
userCardObject = userCardObject,
authObject = authObject)
if userCardObject.id:
userId = userCardObject.id
else:
userId = usercardWeb.addObject(userCardObject)
try:
self.addAccount(userId, authObject)
except faults.SmtpError:
return failure(_("""\
The account has successfully been created, but a SMTP error has occurred.
Maybe the Mail Transport Agent on the Glasnost server is badly configured.\
"""), X.rootUrl())
return redirect(X.idUrl(userId))
newAccountSubmit.isPublicForWeb = 1