Commit 8b085ab1 authored by David Douard's avatar David Douard
Browse files

migrate to a new-style cube

also several minor py3k compat fixes
parent d9e5c6f9a016
include *.py
include */*.py
recursive-include data *.gif *.png *.ico *.css *.js
recursive-include i18n *.po
recursive-include wdoc *
include setup.py
include README
include *.ini
recursive-include test *
recursive-include cubicweb_oauth *
recursive-include cubicweb_oauth/i18n *.po
# pylint: disable=W0622
"""cubicweb-oauth application packaging information"""
modname = 'oauth'
modname = 'cubicweb_oauth'
distname = 'cubicweb-oauth'
numversion = (0, 3, 1)
......@@ -10,12 +10,14 @@ version = '.'.join(str(num) for num in numversion)
license = 'LGPL'
author = 'LOGILAB S.A. (Paris, FRANCE)'
author_email = 'contact@logilab.fr'
description = 'External service (Facebook, Twitter, Google+, etc) Authentication'
description = ('External service (Facebook, Twitter, Google+, etc) '
'Authentication')
web = 'http://www.cubicweb.org/project/%s' % distname
__depends__ = {
'cubicweb': '>= 3.19.0',
'rauth': '>= 0.6.1',
'six': None,
}
__recommends__ = {}
......@@ -25,27 +27,3 @@ classifiers = [
'Programming Language :: Python',
'Programming Language :: JavaScript',
]
from os import listdir as _listdir
from os.path import join, isdir
from glob import glob
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 isdir(join(dirpath, fname))]
data_files = [
# common files
[THIS_CUBE_DIR, [fname for fname in glob('*.py') if fname != 'setup.py']],
]
# check for possible extended cube layout
for dname in ('entities', 'views', 'sobjects', 'hooks', 'schema', 'data', 'wdoc', 'i18n', 'migration'):
if isdir(dname):
data_files.append([join(THIS_CUBE_DIR, dname), listdir(dname)])
# Note: here, you'll need to add subdirectories if you want
# them to be included in the debian package
"""
Special authentifiers.
"""Special authentifiers.
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses
"""
__docformat__ = "restructuredtext en"
from cubicweb import AuthenticationError
from cubicweb.server.sources import native
class Token(object): pass
class Token(object):
pass
EXT_TOKEN = Token()
class DirectAuthentifier(native.BaseAuthentifier):
"""return CWUser eid for the given login.
......@@ -41,8 +43,7 @@ class DirectAuthentifier(native.BaseAuthentifier):
if rset:
session.debug('Successfully identified %s', login)
return rset[0][0]
except Exception, exc:
except Exception as exc:
session.debug('authentication failure (%s)', exc)
raise AuthenticationError('user is not registered')
# -*- coding: utf-8 -*-
#
# copyright 2013-2014 Unlish (Montpellier, FRANCE), all rights reserved.
# copyright 2018 Logilab (Paris, FRANCE), all rights reserved.
# contact 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 Lesser General Public License as published by the Free
# Software Foundation, either version 2.1 of the License, or (at your option)
......
# -*- coding: utf-8 -*-
#
# copyright 2013 Unlish (Montpellier, FRANCE), all rights reserved.
# contact http://www.unlish.com -- mailto:contact@unlish.com
# copyright 2013-2014 Unlish (Montpellier, FRANCE), all rights reserved.
# copyright 2018 Logilab (Paris, FRANCE), all rights reserved.
# contact 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 Lesser General Public License as published by the Free
......@@ -20,7 +21,7 @@
from cubicweb.server import hook
from cubes.oauth.authplugin import DirectAuthentifier
from cubicweb_oauth.authplugin import DirectAuthentifier
class ServerStartupHook(hook.Hook):
......@@ -34,7 +35,6 @@ class ServerStartupHook(hook.Hook):
self.debug('registering externalauth authentifier')
self.repo.system_source.add_authentifier(DirectAuthentifier())
def cleanup_negostates():
import cubes.oauth.views as oviews
......
......@@ -10,8 +10,8 @@
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""cubicweb-oauth postcreate script, executed at instance creation time or when
the cube is added to an existing instance.
......@@ -19,7 +19,6 @@ the cube is added to an existing instance.
You could setup site properties or a workflow here for example.
"""
# Example of site property change
#set_property('ui.site-title', "<sitename>")
create_entity('ExternalAuthProvider', spid=u'facebook', name=u'Facebook')
# create external auth providers
create_entity('ExternalAuthProvider', # noqa
spid=u'facebook', name=u'Facebook')
......@@ -22,12 +22,13 @@ from yams.buildobjs import (
String, EntityType, SubjectRelation, Datetime, Boolean
)
from cubicweb.schema import ERQLExpression, RRQLExpression
from cubicweb.schema import ERQLExpression
# TODO set the maxsize of the String attributes.
sp_attrs_perms = {
'add': ('managers',),
'read': ('managers', 'users', 'guests'),
'update': ('managers',),
}
......@@ -112,6 +113,7 @@ class ExternalIdentity(EntityType):
uid = String(
required=True,
__permissions__={
'add': ('managers',),
'read': ('managers', 'users',),
'update': ('managers',),
}
......@@ -119,6 +121,7 @@ class ExternalIdentity(EntityType):
autologin = Boolean(
required=True, default=False,
__permissions__={
'add': ('managers',),
'read': ('managers', 'users'),
'update': ('managers', ERQLExpression('X identity_of U')),
}
......
# -*- coding: utf-8 -*-
#
# copyright 2013-2014 Unlish (Montpellier, FRANCE), all rights reserved.
# copyright 2018 Logilab (Paris, FRANCE), all rights reserved.
# contact 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 Lesser General Public License as published by the Free
# Software Foundation, either version 2.1 of the License, or (at your option)
......@@ -17,10 +21,11 @@
import json
import re
import urllib
import urlparse
import unicodedata
from six import text_type, PY3
from six.moves import urllib
from cubicweb.utils import make_uid
from cubicweb.predicates import (
anonymous_user, configuration_values, match_form_params)
......@@ -33,11 +38,10 @@ from cubicweb.web import Redirect, formfields, formwidgets, LogOut
from cubicweb.web import InvalidSession
from cubicweb import NoResultError, MultipleResultsError
from cubicweb import _, NoResultError, MultipleResultsError
from cubes.oauth.authplugin import EXT_TOKEN
from cubicweb_oauth.authplugin import EXT_TOKEN
_ = unicode
# XXX replace with multi-instance safe mechanism
NEGOSTATE = {} # negoid -> service coordinates
......@@ -61,12 +65,13 @@ class ExternalAuthMixin(object):
try:
return cnx.execute(
'ExternalAuthService S WHERE S provider P, P spid %(spid)s',
{'spid': providername}
{'spid': text_type(providername)}
).one()
except (NoResultError, MultipleResultsError):
self.exception('no service for provider: %s' % providername)
raise Redirect(req.build_url(
__message='no service for provider %s' % providername
__message=text_type(
'no service for provider %s' % providername)
))
......@@ -152,13 +157,13 @@ class ExternalAuthRetrieverStart(
# Remove the 'vid' parameter if the selected view is 'loggedout'
if '?' in path:
path, query = path.split('?', 1)
params = urlparse.parse_qs(query)
params = urllib.parse.parse_qs(query)
if params.get('vid') == ['loggedout']:
del params['vid']
params.pop('__externalauthprovider', None)
if params:
path = '?'.join(
(path, urllib.urlencode(params, doseq=True)))
(path, urllib.parse.urlencode(params, doseq=True)))
negoid = make_uid('nego')
nego = {'service': service.eid,
......@@ -211,14 +216,14 @@ class ExternalAuthRetrieverMixin(ExternalAuthMixin):
oauth2_session = cnx.create_entity(
'OAuth2Session', service=service,
external_identity=external_identity,
access_token=oauth2_session.access_token,
access_token=text_type(oauth2_session.access_token),
active=True
)
cnx.commit(free_cnxset=False)
cnx.commit()
except authentication.NoAuthInfo:
raise
except Exception, e:
except Exception as e:
self.exception("Cannot get the oauth2_session")
raise authentication.NoAuthInfo(str(e))
......@@ -263,7 +268,7 @@ class ExternalAuthRetrieverMixin(ExternalAuthMixin):
cnx.commit()
self.info('created user %s on %s as %s' % (
user.login, service.provider[0].name, infos['uid']))
except:
except Exception as exc: # noqa
self.exception("Cannot create user %s" % login)
raise
......@@ -288,7 +293,6 @@ class ExternalAuthRetrieverDirect(
def authentication_information(self, req):
if not self.request_has_auth_info(req):
raise authentication.NoAuthInfo
spid = req.form.get('__externalauthprovider')
oauth2_token = req.form.get('__externalauth_oauth2_token')
autologin = bool(req.form.get('autologin'))
......@@ -301,7 +305,7 @@ class ExternalAuthRetrieverDirect(
adapter = service.cw_adapt_to('externalauth.service')
oauth2_session = adapter.oauth2_service.get_session(
oauth2_token)
except:
except Exception as exc: # noqa
self.error("Cannot get a auth2session")
raise authentication.NoAuthInfo
return self._authentication_information(
......@@ -351,7 +355,7 @@ class ExternalAuthRetrieverFinish(
'code': code,
'redirect_uri': nego['redirect_uri']
})
except:
except Exception as exc: # noqa
self.error("Cannot get a auth2session")
raise authentication.NoAuthInfo
return self._authentication_information(
......@@ -372,8 +376,10 @@ class ExternalAuthRetrieverFinish(
"""Return a string suitable to be a login, based on the given login"""
login = unicodedata.normalize('NFKD', login)
login = login.encode('ascii', 'ignore')
if PY3:
login = login.decode()
login = login.replace(' ', '.').lower()
return unicode(login)
return text_type(login)
def forge_login(self, cnx, infos):
"""Forge a login based on infos comming from the oauth2 provider.
......@@ -468,7 +474,7 @@ Select the provider you want to use to authenticate.
# XXX Hijack the logout method.
# We should have a hook for pre/post-logout actions
# We should have a hook for pre/post-logout actions
def CookieSessionHandler_logout(self, req, goto_url):
if req.user.reverse_identity_of:
req.user.reverse_identity_of[0].cw_set(autologin=False)
......@@ -477,5 +483,6 @@ def CookieSessionHandler_logout(self, req, goto_url):
req.remove_cookie(self.session_cookie(req))
raise LogOut(url=goto_url)
from cubicweb.web.application import CookieSessionHandler
from cubicweb.web.application import CookieSessionHandler # noqa
CookieSessionHandler.logout = CookieSessionHandler_logout
#!/usr/bin/env python
# pylint: disable=W0142,W0403,W0404,W0613,W0622,W0622,W0704,R0904,C0103,E0611
#
# This file is part of CubicWeb tag cube.
# copyright 2003-2018 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of a cubicweb-file.
#
# CubicWeb is free software: you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
......@@ -13,186 +16,68 @@
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with CubicWeb. If not, see <http://www.gnu.org/licenses/>.
"""Generic Setup script, takes package info from __pkginfo__.py file
# You should have received a copy of the GNU Lesser General Public License
# along with CubicWeb. If not, see <http://www.gnu.org/licenses/>.
"""cubicweb-oauthsetup module using data from
cubicweb_oauth/__pkginfo__.py file
"""
__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() # do as there is no setuptools
from setuptools import setup
from setuptools.command import install_lib
USE_SETUPTOOLS = True
except ImportError:
from distutils.core import setup
from distutils.command import install_lib
USE_SETUPTOOLS = False
from distutils.command import install_data
# import required features
from __pkginfo__ import modname, version, license, description, web, \
author, author_email, classifiers
if exists('README'):
long_description = file('README').read()
else:
long_description = ''
# import optional features
import __pkginfo__
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 = []
distname = getattr(__pkginfo__, 'distname', modname)
scripts = getattr(__pkginfo__, 'scripts', ())
include_dirs = getattr(__pkginfo__, 'include_dirs', ())
data_files = getattr(__pkginfo__, 'data_files', None)
ext_modules = getattr(__pkginfo__, 'ext_modules', None)
dependency_links = getattr(__pkginfo__, 'dependency_links', ())
BASE_BLACKLIST = ('CVS', '.svn', '.hg', 'debian', 'dist', 'build')
IGNORED_EXTENSIONS = ('.pyc', '.pyo', '.elc', '~')
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 export(from_dir, to_dir,
blacklist=BASE_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:
sys.stderr.write('%s -> %s\n' % (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 as 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)
# re-enable copying data files in sys.prefix
old_install_data = install_data.install_data
if USE_SETUPTOOLS:
# overwrite InstallData to use sys.prefix instead of the egg directory
class MyInstallData(old_install_data):
"""A class that manages data files installation"""
def run(self):
_old_install_dir = self.install_dir
if self.install_dir.endswith('egg'):
self.install_dir = sys.prefix
old_install_data.run(self)
self.install_dir = _old_install_dir
try:
import setuptools.command.easy_install # only if easy_install avaible
# monkey patch: Crack SandboxViolation verification
from setuptools.sandbox import DirectorySandbox as DS
old_ok = DS._ok
def _ok(self, path):
"""Return True if ``path`` can be written during installation."""
out = old_ok(self, path) # here for side effect from setuptools
realpath = os.path.normcase(os.path.realpath(path))
allowed_path = os.path.normcase(sys.prefix)
if realpath.startswith(allowed_path):
out = True
return out
DS._ok = _ok
except ImportError:
pass
def install(**kwargs):
"""setup entry point"""
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')
cmdclass = {'install_lib': MyInstallLib}
if USE_SETUPTOOLS:
kwargs['install_requires'] = install_requires
kwargs['dependency_links'] = dependency_links
kwargs['zip_safe'] = False
cmdclass['install_data'] = MyInstallData
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 = cmdclass,
classifiers = classifiers,
**kwargs
)
if __name__ == '__main__' :
install()
from os.path import join, dirname
from setuptools import find_packages, setup
here = dirname(__file__)
# load metadata from the __pkginfo__.py file so there is no risk of conflict
# see https://packaging.python.org/en/latest/single_source_version.html
pkginfo = join(here, 'cubicweb_oauth', '__pkginfo__.py')
__pkginfo__ = {}
with open(pkginfo) as f:
exec(f.read(), __pkginfo__)
# get required metadatas
distname = __pkginfo__['distname']
version = __pkginfo__['version']
license = __pkginfo__['license']
description = __pkginfo__['description']
web = __pkginfo__['web']
author = __pkginfo__['author']
author_email = __pkginfo__['author_email']
classifiers = __pkginfo__['classifiers']
with open(join(here, 'README')) as f:
long_description = f.read()
# get optional metadatas
dependency_links = __pkginfo__.get('dependency_links', ())
requires = {}
for entry in ("__depends__",): # "__recommends__"):
requires.update(__pkginfo__.get(entry, {}))
install_requires = ["{0} {1}".format(d, v and v or "").strip()
for d, v in requires.items()]
setup(
name=distname,
version=version,
license=license,
description=description,
long_description=long_description,
author=author,
author_email=author_email,
url=web,
classifiers=classifiers,
packages=find_packages(exclude=['test']),
install_requires=install_requires,
include_package_data=True,
entry_points={
'cubicweb.cubes': [
'file=cubicweb_file',
],
'cubicweb.i18ncube': [
'file=cubicweb_file.i18n',
]
},
zip_safe=False,
)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment