Commit 03390bac authored by Sylvain Thénault's avatar Sylvain Thénault
Browse files

backport stable

......@@ -12,3 +12,5 @@ ade2c366ddf2ce503d868d2cb1bd43b060afa365 cubicweb-registration-debian-version-0.
58e5dd448321d5652dd2d76a293046f53a70589a cubicweb-registration-version-0.3.2
7cf047ac4b03bc6803f19c43b20425cbcffb20b7 cubicweb-registration-debian-version-0.3.2-1
0e0542387b2596041da896dfbd549526e55809a5 cubicweb-registration-debian-version-0.3.2-1
0f0967ed816d3f72f588a2737f696816fcb1d4cc cubicweb-registration-version-0.4.0
b57032accd10ae5fc7c47c24a989993b6bfb3dfd cubicweb-registration-debian-version-0.4.0-1
This CubicWeb component provides a public registration feature (users
can register and create an account without the need for admin
intervention).
......@@ -4,24 +4,14 @@
modname = 'registration'
distname = 'cubicweb-registration'
numversion = (0, 3, 2)
numversion = (0, 4, 0)
version = '.'.join(str(num) for num in numversion)
license = 'LGPL'
description = 'public registration component for the CubicWeb framework'
author = 'LOGILAB S.A. (Paris, FRANCE)'
author_email = 'contact@logilab.fr'
web = 'http://www.cubicweb.org/project/%s' % distname
short_desc = 'public registration component for the CubicWeb framework'
long_desc = """\
This cube provides a public registration feature (anonymous users can register
and create an account without the need for admin intervention).
It is non-obstrusive and easy to plug.
"""
classifiers = [
'Environment :: Web Environment',
'Framework :: CubicWeb',
......@@ -29,43 +19,32 @@ classifiers = [
'Programming Language :: JavaScript',
]
__depends_cubes__ = {}
__depends__ = {'cubicweb': '>= 3.7.4',
__depends__ = {'cubicweb': '>= 3.8.0',
'python-crypto': None,
'PIL': None,
}
__use__ = tuple(__depends_cubes__)
__recommend__ = ()
# packaging ###
from os import listdir as _listdir
from os.path import join, isdir
from glob import glob
pyversions = ['2.4']
CUBES_DIR = join('share', 'cubicweb', 'cubes')
THIS_CUBE_DIR = join(CUBES_DIR, 'registration')
THIS_CUBE_DIR = join('share', 'cubicweb', 'cubes', modname)
def listdir(dirpath):
return [join(dirpath, fname) for fname in _listdir(dirpath)
if fname[0] != '.' and not fname.endswith('.pyc')
and not fname.endswith('~')]
and not fname.endswith('~')
and not isdir(join(dirpath, fname))]
from glob import glob
try:
data_files = [
# common files
[THIS_CUBE_DIR, [fname for fname in glob('*.py') if fname != 'setup.py']],
]
# check for possible extended cube layout
for dirname in ('entities', 'views', 'sobjects', 'hooks', 'schema', 'data', 'i18n', 'migration'):
if isdir(dirname):
data_files.append([join(THIS_CUBE_DIR, dirname), listdir(dirname)])
# Note: here, you'll need to add subdirectories if you want
# them to be included in the debian package
except OSError:
# we are in an installed directory
pass
cube_eid = None # <=== FIXME if you need direct bug-subscription
data_files = [
# common files
[THIS_CUBE_DIR, [fname for fname in glob('*.py') if fname != 'setup.py']],
]
# check for possible extended cube layout
for dirname in ('entities', 'views', 'sobjects', 'hooks', 'schema', 'data', 'i18n', 'migration', 'wdoc'):
if isdir(dirname):
data_files.append([join(THIS_CUBE_DIR, dirname), listdir(dirname)])
# Note: here, you'll need to add subdirectories if you want
# them to be included in the debian package
cubicweb-registration (0.4.0-1) unstable; urgency=low
* new upstream release
-- Sylvain Thénault <sylvain.thenault@logilab.fr> Mon, 11 Oct 2010 15:25:41 +0200
cubicweb-registration (0.3.3-1) unstable; urgency=low
* new upstream release
-- Adrien Di Mascio <Adrien.DiMascio@logilab.fr> Thu, 06 May 2010 17:17:05 +0200
cubicweb-registration (0.3.2-1) unstable; urgency=low
* new upstream release
......
......@@ -8,7 +8,7 @@ Homepage: http://www.cubicweb.org/project/cubicweb-registration
Package: cubicweb-registration
Architecture: all
Depends: cubicweb-common (>= 3.7.4), python-crypto, python-imaging
Depends: cubicweb-common (>= 3.8.0), python-crypto, python-imaging
Description: public registration component for the CubicWeb framework
This CubicWeb component provides a public registration feature (users
can register and create an account without the need for admin
......
......@@ -5,12 +5,12 @@
# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1
build: build-stamp
build-stamp:
build-stamp:
dh_testdir
python setup.py -q build
NO_SETUPTOOLS=1 python setup.py -q build
touch build-stamp
clean:
clean:
dh_testdir
dh_testroot
rm -f build-stamp configure-stamp
......@@ -23,7 +23,7 @@ install: build
dh_testroot
dh_clean -k
dh_installdirs -i
python setup.py -q install --no-compile --prefix=debian/cubicweb-registration/usr/
NO_SETUPTOOLS=1 python setup.py -q install --no-compile --prefix=debian/cubicweb-registration/usr/
# Build architecture-independent files here.
......@@ -39,13 +39,13 @@ binary-indep: build install
dh_compress -i -X.py -X.ini -X.xml -Xtest
dh_fixperms -i
dh_installdeb -i
dh_gencontrol -i
dh_gencontrol -i
dh_md5sums -i
dh_builddeb -i
# Build architecture-dependent files here.
binary-arch:
binary-arch:
binary: binary-indep
binary: binary-indep
.PHONY: build clean binary-arch binary-indep binary
......@@ -14,7 +14,7 @@ msgid ""
"thanks for registering on %(base_url)s.\n"
"\n"
"Please click on the link below to activate your account :\n"
"%(url)s.\n"
"%(url)s\n"
"\n"
"See you soon on %(base_url)s !\n"
msgstr ""
......@@ -24,9 +24,7 @@ msgid "Confirm your registration on %(base_url)s"
msgstr ""
#, python-format
msgid ""
"Congratulations, your registration is complete. Welcome %(firstname-subject)"
"s %(surname-subject)s !"
msgid "Congratulations, your registration is complete. Welcome %s !"
msgstr ""
msgid "Invalid registration data. Please try registering again."
......
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR Free Software Foundation, Inc.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: 0\n"
"PO-Revision-Date: 2010-05-05 16:39+0200\n"
"Last-Translator: Nicolas Chauvat <nicolas.chauvat@logilab.fr>\n"
"Language-Team: fr <nicolas.chauvat@logilab.fr>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: pygettext.py 1.5\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
#, python-format
#, fuzzy, python-format
msgid ""
"\n"
"Hello %(firstname-subject)s %(surname-subject)s,\n"
......@@ -14,17 +23,17 @@ msgid ""
"thanks for registering on %(base_url)s.\n"
"\n"
"Please click on the link below to activate your account :\n"
"%(url)s.\n"
"%(url)s\n"
"\n"
"See you soon on %(base_url)s !\n"
msgstr ""
"\n"
"Bonjour %(firstname-subject)s %-subject(surname)s,\n"
"Bonjour %(firstname-subject)s %(surname-subject)s,\n"
"\n"
"Merci de vous être enregistré sur %(base_url)s.\n"
"\n"
"Veuillez clickez sur le lien ci-dessous pour activer votre compte :\n"
"%(url)s.\n"
"%(url)s\n"
"\n"
"À bientôt sur %(base_url)s !\n"
......@@ -33,12 +42,8 @@ msgid "Confirm your registration on %(base_url)s"
msgstr "Confirmez votre enregistrement sur %(base_url)s"
#, python-format
msgid ""
"Congratulations, your registration is complete. Welcome %(firstname-subject)"
"s %(surname-subject)s !"
msgstr ""
"Félicitations, vote compte est maintenant activé. Bienvenue %(firstname-"
"subject)s %(surname-subject)s !"
msgid "Congratulations, your registration is complete. Welcome %s !"
msgstr "Félicitations, vote compte est maintenant activé. Bienvenue %s !"
msgid "Invalid registration data. Please try registering again."
msgstr ""
......
#!/usr/bin/env python
# pylint: disable-msg=W0404,W0622,W0704,W0613,W0152
# Copyright (c) 2003-2004 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# 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.
""" Generic Setup script, takes package info from __pkginfo__.py file """
from distutils.core import setup
# pylint: disable=W0404,W0622,W0704,W0613
# copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
__docformat__ = "restructuredtext en"
import os
import sys
import shutil
from os.path import isdir, exists, join, walk
try:
if os.environ.get('NO_SETUPTOOLS'):
raise ImportError()
from setuptools import setup
from setuptools.command import install_lib
USE_SETUPTOOLS = 1
except ImportError:
from distutils.core import setup
from distutils.command import install_lib
USE_SETUPTOOLS = 0
sys.modules.pop('__pkginfo__', None)
# import required features
from __pkginfo__ import distname, version, license, short_desc, long_desc, \
from __pkginfo__ import modname, version, license, description, \
web, author, author_email
# import optional features
try:
from __pkginfo__ import data_files
except ImportError:
data_files = None
try:
from __pkginfo__ import include_dirs
except ImportError:
include_dirs = []
import __pkginfo__
distname = getattr(__pkginfo__, 'distname', modname)
scripts = getattr(__pkginfo__, 'scripts', [])
data_files = getattr(__pkginfo__, 'data_files', None)
include_dirs = getattr(__pkginfo__, 'include_dirs', [])
ext_modules = getattr(__pkginfo__, 'ext_modules', None)
dependency_links = getattr(__pkginfo__, 'dependency_links', [])
STD_BLACKLIST = ('CVS', '.svn', '.hg', 'debian', 'dist', 'build')
IGNORED_EXTENSIONS = ('.pyc', '.pyo', '.elc', '~')
if exists('README'):
long_description = file('README').read()
else:
long_description = ''
if USE_SETUPTOOLS:
requires = {}
for entry in ("__depends__", "__recommends__"):
requires.update(getattr(__pkginfo__, entry, {}))
install_requires = [("%s %s" % (d, v and v or "")).strip()
for d, v in requires.iteritems()]
else:
install_requires = []
def ensure_scripts(linux_scripts):
"""Creates the proper script names required for each platform
(taken from 4Suite)
"""
from distutils import util
if util.get_platform()[:3] == 'win':
scripts_ = [script + '.bat' for script in linux_scripts]
else:
scripts_ = linux_scripts
return scripts_
def get_packages(directory, prefix):
"""return a list of subpackages for the given directory"""
result = []
for package in os.listdir(directory):
absfile = join(directory, package)
if isdir(absfile):
if exists(join(absfile, '__init__.py')) or \
package in ('test', 'tests'):
if prefix:
result.append('%s.%s' % (prefix, package))
else:
result.append(package)
result += get_packages(absfile, result[-1])
return result
def export(from_dir, to_dir,
blacklist=STD_BLACKLIST,
ignore_ext=IGNORED_EXTENSIONS,
verbose=True):
"""make a mirror of from_dir in to_dir, omitting directories and files
listed in the black list
"""
def make_mirror(arg, directory, fnames):
"""walk handler"""
for norecurs in blacklist:
try:
fnames.remove(norecurs)
except ValueError:
pass
for filename in fnames:
# don't include binary files
if filename[-4:] in ignore_ext:
continue
if filename[-1] == '~':
continue
src = join(directory, filename)
dest = to_dir + src[len(from_dir):]
if verbose:
print >> sys.stderr, src, '->', dest
if os.path.isdir(src):
if not exists(dest):
os.mkdir(dest)
else:
if exists(dest):
os.remove(dest)
shutil.copy2(src, dest)
try:
os.mkdir(to_dir)
except OSError, ex:
# file exists ?
import errno
if ex.errno != errno.EEXIST:
raise
walk(from_dir, make_mirror, None)
class MyInstallLib(install_lib.install_lib):
"""extend install_lib command to handle package __init__.py and
include_dirs variable if necessary
"""
def run(self):
"""overridden from install_lib class"""
install_lib.install_lib.run(self)
# manually install included directories if any
if include_dirs:
base = modname
for directory in include_dirs:
dest = join(self.install_dir, base, directory)
export(directory, dest, verbose=False)
def install(**kwargs):
"""setup entry point"""
#kwargs['distname'] = modname
return setup(name=distname,
version=version,
license=license,
description=short_desc,
long_description=long_desc,
author=author,
author_email=author_email,
url=web,
data_files=data_files,
**kwargs)
if USE_SETUPTOOLS:
if '--force-manifest' in sys.argv:
sys.argv.remove('--force-manifest')
# install-layout option was introduced in 2.5.3-1~exp1
elif sys.version_info < (2, 5, 4) and '--install-layout=deb' in sys.argv:
sys.argv.remove('--install-layout=deb')
if USE_SETUPTOOLS and install_requires:
kwargs['install_requires'] = install_requires
kwargs['dependency_links'] = dependency_links
return setup(name = distname,
version = version,
license = license,
description = description,
long_description = long_description,
author = author,
author_email = author_email,
url = web,
scripts = ensure_scripts(scripts),
data_files = data_files,
ext_modules = ext_modules,
cmdclass = {'install_lib': MyInstallLib},
**kwargs
)
if __name__ == '__main__' :
install()
......@@ -4,6 +4,6 @@ options = (
{'type' : 'string',
'default': u"this is my dummy registration cypher seed",
'help': 'seed used to cypher registration data in confirmation email link',
'group': 'registration', 'inputlevel': 2,
'group': 'registration', 'level': 2,
}),
)
......@@ -35,17 +35,17 @@ class RegistrationTC(CubicWebTC):
expected_params=None,
expected_formvalues=None):
path, params = self.expect_redirect_publish(req, path)
self.assertEquals(path, expected_path)
self.assertEquals(params, expected_params or {})
self.assertEqual(path, expected_path)
self.assertEqual(params, expected_params or {})
forminfo = req.get_session_data('registration')
if forminfo is None:
self.failIf(expected_errors or expected_formvalues)
else:
self.assertEquals(forminfo['eidmap'], {})
self.assertEquals(forminfo['values'], expected_formvalues or {})
self.assertEqual(forminfo['eidmap'], {})
self.assertEqual(forminfo['values'], expected_formvalues or {})
error = forminfo['error']
self.assertEquals(error.entity, None)
self.assertEquals(error.errors, expected_errors or {})
self.assertEqual(error.entity, None)
self.assertEqual(error.errors, expected_errors or {})
def _posted_form(self, *skipkeys):
data = self.data.copy()
......@@ -63,20 +63,20 @@ class RegistrationTC(CubicWebTC):
# check form field names
names = pageinfo.etree.xpath('//ns:form[@id="registrationForm"]//ns:input[@type!="hidden"]/@name',
namespaces=ns)
self.assertEquals(set(names), set(self.data))
self.assertEqual(set(names), set(self.data))
# check form field value
firstname = pageinfo.etree.xpath('//ns:input[@name="firstname-subject"]/@value',
namespaces=ns)
self.assertEquals(firstname, [req.form['firstname-subject']])
self.assertEqual(firstname, [req.form['firstname-subject']])
def test_send_mail_ok(self):
self.login('anon')
req = self.request()
req.form = self._posted_form()
req.set_session_data('captcha', self.captcha_value)
req.session.data['captcha'] = self.captcha_value
path, params = self.expect_redirect_publish(req, 'registration_sendmail')
self.assertEquals(path, '')
self.assertEquals(params, {'__message': 'Your registration email has been sent. Follow instructions in there to activate your account.'})
self.assertEqual(path, '')
self.assertEqual(params, {'__message': 'Your registration email has been sent. Follow instructions in there to activate your account.'})
# check email contains activation url...
URL_RE = re.compile('(%s[^.]+)\.' % self.config['base-url'])
text = MAILBOX[-1].message.get_payload(decode=True)
......@@ -84,7 +84,7 @@ class RegistrationTC(CubicWebTC):
# ... and the registration key contains all data
key = dict(cgi.parse_qsl(urlparse.urlsplit(url)[3]))['key']
d = self._posted_form('upassword-subject-confirm')
self.assertDictEquals(decrypt(key, self.config['registration-cypher-seed']), d)
self.assertDictEqual(decrypt(key, self.config['registration-cypher-seed']), d)
def test_send_mail_failure(self):
for param, msg, val in (('login-subject', 'required field', None),
......@@ -96,17 +96,18 @@ class RegistrationTC(CubicWebTC):
else:
req.form = self._posted_form()
req.form[param] = val
req.set_session_data('captcha', self.captcha_value)
req.session.data['captcha'] = self.captcha_value
#expected
self._check_error(req, 'registration_sendmail',
expected_formvalues=req.form,
expected_errors={param: msg})
self.assertEquals(req.get_session_data('captcha'), None)
self.assertEqual(req.session.data.get('captcha'), None)
def _confirm_req(self, key=None):
def _confirm_req(self, key=None, overriden={}):
self.login('anon')
req = self.request()
data = self._posted_form('upassword-subject-confirm')
data.update(overriden)
if key is None:
key = encrypt(data, self.config['registration-cypher-seed'])
req.form = {'key': key}
......@@ -117,8 +118,8 @@ class RegistrationTC(CubicWebTC):
def test_confirm_ok(self):
req = self._confirm_req()
path, params = self.expect_redirect_publish(req, 'registration_confirm')
self.assertEquals(path, '')
self.assertEquals(params, {'__message': u'Congratulations, your registration is complete. Welcome %(firstname-subject)s %(surname-subject)s !' % self.data})
self.assertEqual(path, '')
self.assertEqual(params, {'__message': u'Congratulations, your registration is complete. Welcome %(firstname-subject)s %(surname-subject)s !' % self.data})
self.restore_connection()
rset = self.execute('Any U WHERE U login %(login)s, U firstname %(firstname)s, '
'U surname %(surname)s, U use_email M, M address %(address)s',
......@@ -126,14 +127,33 @@ class RegistrationTC(CubicWebTC):
for k, v in self.data.items()))
self.failUnless(rset.rowcount)
def _check_error(self, req, path,
expected_path='registration',
expected_errors=None,
expected_params=None,
expected_formvalues=None):
path, params = self.expect_redirect_publish(req, path)
self.assertEqual(path, expected_path)
self.assertEqual(params, expected_params or {})
forminfo = req.session.data.get('registration')
if forminfo is None:
self.failIf(expected_errors or expected_formvalues)
else:
self.assertEqual(forminfo['eidmap'], {})
self.assertEqual(forminfo['values'], expected_formvalues or {})
error = forminfo['error']
self.assertEqual(error.entity, None)
self.assertEqual(error.errors, expected_errors or {})
def test_confirm_failure_login_already_used(self):
self.create_user(self.data['login-subject'])
self.commit()
req = self._confirm_req()
# try to recreate a 'admin' user.
req = self._confirm_req(overriden={'login-subject': 'admin'})
formvalues = self._posted_form('upassword-subject',
'upassword-subject-confirm')
formvalues['login-subject'] = 'admin'
self._check_error(req, 'registration_confirm',
expected_formvalues=self._posted_form('upassword-subject',
'upassword-subject-confirm'),
expected_errors={'login-subject': 'the value "%(login-subject)s" is already used, use another one' % self.data})
expected_formvalues=formvalues,
expected_errors={'login-subject': 'the value "admin" is already used, use another one'})
def test_confirm_failure_invalid_data(self):
req = self._confirm_req('dummykey')
......
......@@ -13,6 +13,7 @@ from yams.schema import role_name
from cubicweb import mail, crypto
from cubicweb.view import StartupView
from cubicweb.selectors import anonymous_user
from cubicweb.web import Redirect, ValidationError, ProcessFormError
from cubicweb.web import controller, form, captcha
from cubicweb.web import formwidgets as fw, formfields as ff
......@@ -53,7 +54,7 @@ class RegistrationFormView(form.FormViewMixIn, StartupView):
def call(self):
form = self._cw.vreg['forms'].select('registration', self._cw)
self.w(form.render(display_progress_div=False))
form.render(w=self.w, display_progress_div=False)
class RegistrationSendMailController(controller.Controller):
__regid__ = 'registration_sendmail'
......@@ -63,7 +64,7 @@ Hello %(firstname-subject)s %(surname-subject)s,
thanks for registering on %(base_url)s.
Please click on the link below to activate your account :
%(url)s.
%(url)s
See you soon on %(base_url)s !
''')
......@@ -132,11 +133,25 @@ class RegistrationConfirmController(controller.Controller):
except:
msg = req._(u'Invalid registration data. Please try registering again.')
raise Redirect(req.build_url(u'register', __message=msg))
if self._cw.user.login == login:
# already logged in (e.g. regstration link replayed twice in the browser)
raise Redirect(self.success_redirect_url())
req.form = data # hijack for proper validation error handling
self.appli.repo.register_user(login, password,
email=data.get(qname('address')),
firstname=data.get(qname('firstname')),