Ejemplo n.º 1
0
def oauth_register(account_info, form_data=None):
    """Register user if possible."""
    from invenio.modules.accounts.models import User

    email = account_info.get("email")
    if form_data and form_data.get("email"):
        email = form_data.get("email")

    if email:
        if not User.query.filter_by(email=email).first():
            # Email does not already exists. so we can proceed to register
            # user.
            u = User(
                nickname=account_info.get('nickname', ''),
                email=email,
                password=None,
                # email has to be validated
                note='2',
            )

            try:
                db.session.add(u)
                db.session.commit()
            except Exception:
                current_app.logger.exception("Cannot create user")
                return None

            # verify the email
            if cfg['CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT']:
                u.verify_email()

            return UserInfo(u.id)

    return None
Ejemplo n.º 2
0
def oauth_register(account_info, form_data=None):
    """Register user if possible."""
    from invenio.modules.accounts.models import User

    email = account_info.get("email")
    if form_data and form_data.get("email"):
        email = form_data.get("email")

    if email:
        if not User.query.filter_by(email=email).first():
            # Email does not already exists. so we can proceed to register
            # user.
            u = User(
                nickname=account_info.get('nickname', ''),
                email=email,
                password=None,
                # email has to be validated
                note='2',
            )

            try:
                db.session.add(u)
                db.session.commit()
            except Exception:
                current_app.logger.exception("Cannot create user")
                return None

            # verify the email
            if cfg['CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT']:
                u.verify_email()

            return UserInfo(u.id)

    return None
Ejemplo n.º 3
0
    def setUp(self):
        super(ProviderTestCase, self).setUp()
        # Set environment variable DEBUG to true, to allow testing without
        # SSL in oauthlib.
        if self.app.config.get("CFG_SITE_SECURE_URL").startswith("http://"):
            self.os_debug = os.environ.get("OAUTHLIB_INSECURE_TRANSPORT", "")
            os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "true"

        from ..models import Client, Scope
        from invenio.modules.accounts.models import User
        from ..registry import scopes as scopes_registry

        # Register a test scope
        scopes_registry.register(Scope("test:scope"))

        self.base_url = self.app.config.get("CFG_SITE_SECURE_URL")

        # Create needed objects
        u = User(email="*****@*****.**", nickname="tester")
        u.password = "******"

        u2 = User(email="*****@*****.**", nickname="tester2")
        u2.password = "******"

        db.session.add(u)
        db.session.add(u2)

        c1 = Client(
            client_id="dev",
            client_secret="dev",
            name="dev",
            description="",
            is_confidential=False,
            user=u,
            _redirect_uris="%s/oauth2test/authorized" % self.base_url,
            _default_scopes="test:scope",
        )

        c2 = Client(
            client_id="confidential",
            client_secret="confidential",
            name="confidential",
            description="",
            is_confidential=True,
            user=u,
            _redirect_uris="%s/oauth2test/authorized" % self.base_url,
            _default_scopes="test:scope",
        )

        db.session.add(c1)
        db.session.add(c2)

        db.session.commit()

        self.objects = [u, u2, c1, c2]

        # Create a personal access token as well.
        from ..models import Token

        self.personal_token = Token.create_personal("test-personal", 1, scopes=[], is_internal=True)
Ejemplo n.º 4
0
    def login_callback(user_info):
        """Login user base on SSO context (create one if necessary).

        Function should not raise an exception if `user_info` is not valid
        or `User` was not found in database.
        """
        from invenio.modules.accounts.models import User
        from invenio.ext.login import (authenticate, login_redirect,
                                       current_user)
        from invenio.ext.sqlalchemy import db

        user_info['group'] = fetch_groups(user_info['group']).values()
        user_info['external'] = fetch_external(user_info.get('external'))
        try:
            auth = authenticate(user_info['email'], login_method='SSO')
            if auth is None:
                user = User()
                user.nickname = user_info['nickname']
                user.email = user_info['email']
                user.password = ''
                user.settings = {'login_method': 'SSO'}
                db.session.add(user)
                db.session.commit()
                auth = authenticate(user_info['email'], login_method='SSO')
                if auth is None:
                    return redirect('/')

            current_user.info['group'] = current_user.get('group', []) + \
                user_info['group']
            current_user.save()
        except:
            flash('Problem with login (%s)' % (str(user_info)), 'error')
            return redirect('/')

        return login_redirect()
Ejemplo n.º 5
0
    def setUp(self):
        """Setup needed related models."""
        from zenodo.modules.accessrequests.models import AccessRequest, \
            SecretLink
        from invenio.modules.accounts.models import User

        AccessRequest.query.delete()
        SecretLink.query.delete()
        User.query.filter_by(nickname='sender').delete()
        User.query.filter_by(nickname='receiver').delete()

        self.sender = User(
            nickname="sender",
            family_name="sender",
            given_names="a",
            password="******",
            note="1",

        )
        self.receiver = User(
            nickname="receiver",
            family_name="receiver",
            given_names="a",
            password="******",
            note="1"
        )

        db.session.add(self.sender)
        db.session.add(self.receiver)
        db.session.commit()

        self.called = dict()
Ejemplo n.º 6
0
def cli_cmd_reset(sender, yes_i_know=False, drop=True, **kwargs):
    """Reset legacy values."""
    from invenio.ext.sqlalchemy import db
    from invenio.modules.accounts.models import User
    # from invenio.legacy.inveniocfg import cli_cmd_reset_sitename
    # from invenio.legacy.inveniocfg import cli_cmd_reset_fieldnames
    from invenio.legacy.bibsort.daemon import main as bibsort
    from invenio.modules.access.scripts.webaccessadmin import main as \
        webaccessadmin

    # FIXME refactor fixtures so these calls are not needed
    # cli_cmd_reset_sitename(conf)
    User.query.filter_by(id=1).delete()
    siteadminemail = current_app.config.get('CFG_SITE_ADMIN_EMAIL')
    u = User(id=1, email=siteadminemail, password='', note=1, nickname='admin')
    db.session.add(u)
    db.session.commit()
    # cli_cmd_reset_fieldnames(conf)

    for cmd in (
        (webaccessadmin, "webaccessadmin -u admin -c -a -D"),
        (bibsort, "bibsort -u admin --load-config"),
        (bibsort, "bibsort 1"),
    ):
        if run_py_func(*cmd, passthrough=True).exit_code:
            print("ERROR: failed execution of", *cmd)
            sys.exit(1)
Ejemplo n.º 7
0
def oauth_register(account_info, form_data=None):
    """Register user if possible."""
    from invenio.modules.accounts.models import User

    email = account_info.get("email")
    if form_data and form_data.get("email"):
        email = form_data.get("email")

    if email:
        if not User.query.filter_by(email=email).first():
            # Email does not already exists. so we can proceed to register
            # user.
            u = User(
                nickname=account_info.get('nickname', ''),
                email=email,
                password=generate_secret_key(),
                note='1',  # Activated - assumes email is validated
            )

            try:
                db.session.add(u)
                db.session.commit()
                return UserInfo(u.id)
            except Exception:
                current_app.logger.exception("Cannot create user")
    return None
Ejemplo n.º 8
0
 def setUp(self):
     from invenio.modules.accounts.models import User
     self.user = User(email='*****@*****.**', nickname='tester')
     self.user.password = "******"
     db.session.add(self.user)
     db.session.commit()
     self.create_oauth_token(self.user.id, scopes=[""])
Ejemplo n.º 9
0
 def create_and_login_user(self, user_nickname=None, user_password=None):
     """Create test user and log him in."""
     from invenio.modules.accounts.models import User
     self.user_nickname = user_nickname or "tester"
     self.user_password = user_password or "tester"
     # remove the user if he exists
     self.user = User.query.filter(
         User.nickname == self.user_nickname).first()
     if self.user:
         try:
             db.session.delete(self.user)
             db.session.commit()
         except:
             db.session.rollback()
             raise
     # create the user
     email = "{}@b2share.com".format(self.user_nickname)
     self.user = User(email=email, nickname=self.user_nickname)
     self.user.password = self.user_password
     try:
         db.session.add(self.user)
         db.session.commit()
     except:
         db.session.rollback()
         raise
     from invenio.ext.login import login_user
     from flask.ext.login import current_user
     login_user(self.user.id)
     current_user.reload()
     self.assertEqual(current_user.get_id(), self.user.id)
     self.safe_login_web_user(self.user_nickname, self.user_password)
     return self.user.id
Ejemplo n.º 10
0
    def test_verify_email_works_with_numbers_and_strings(self):
        from invenio.modules.accounts.models import User
        u = User(email="*****@*****.**", password="")
        u.note = 2
        self.assertTrue(u.verify_email())

        u2 = User(email="*****@*****.**", password="")
        u2.note = "2"
        self.assertTrue(u2.verify_email())
Ejemplo n.º 11
0
    def setUp(self):
        from ..models import Scope
        from invenio.modules.accounts.models import User
        from ..registry import scopes as scopes_registry

        # Register a test scope
        scopes_registry.register(Scope('test:scope1'))
        scopes_registry.register(Scope('test:scope2', internal=True))

        self.base_url = self.app.config.get('CFG_SITE_SECURE_URL')

        # Create needed objects
        u = User(email='*****@*****.**', nickname='tester')
        u.password = "******"

        db.session.add(u)
        db.session.commit()

        self.objects = [u]
    def setUp(self):
        from ..models import Scope
        from invenio.modules.accounts.models import User
        from ..registry import scopes as scopes_registry

        # Register a test scope
        scopes_registry.register(Scope('test:scope1'))
        scopes_registry.register(Scope('test:scope2', internal=True))

        self.base_url = self.app.config.get('CFG_SITE_SECURE_URL')

        # Create needed objects
        u = User(
            email='*****@*****.**', nickname='tester'
        )
        u.password = "******"

        db.session.add(u)
        db.session.commit()

        self.objects = [u]
Ejemplo n.º 13
0
    def login_callback(user_info):
        """Login user base on SSO context (create one if necessary).

        Function should not raise an exception if `user_info` is not valid
        or `User` was not found in database.
        """
        from invenio.modules.accounts.models import User
        from invenio.ext.login import (authenticate, login_redirect,
                                       current_user)
        from invenio.ext.sqlalchemy import db

        user_info['group'] = fetch_groups(user_info['group']).values()
        user_info['external'] = fetch_external(user_info.get('external'))
        try:
            auth = authenticate(user_info['email'], login_method='SSO')
            if auth is None:
                user = User()
                user.nickname = user_info['nickname']
                user.email = user_info['email']
                user.password = ''
                user.settings = {'login_method': 'SSO'}
                db.session.add(user)
                db.session.commit()
                auth = authenticate(user_info['email'], login_method='SSO')
                if auth is None:
                    return redirect('/')

            current_user.info['group'] = current_user.get('group', []) + \
                user_info['group']
            current_user.save()
        except:
            flash('Problem with login (%s)' % (str(user_info)), 'error')
            return redirect('/')

        return login_redirect()
Ejemplo n.º 14
0
    def setUp(self):
        super(ProviderTestCase, self).setUp()
        # Set environment variable DEBUG to true, to allow testing without
        # SSL in oauthlib.
        if self.app.config.get('CFG_SITE_SECURE_URL').startswith('http://'):
            self.os_debug = os.environ.get('OAUTHLIB_INSECURE_TRANSPORT', '')
            os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = 'true'

        from ..models import Client, Scope
        from invenio.modules.accounts.models import User
        from ..registry import scopes as scopes_registry

        # Register a test scope
        scopes_registry.register(Scope('test:scope'))

        self.base_url = self.app.config.get('CFG_SITE_SECURE_URL')

        # Create needed objects
        u = User(email='*****@*****.**', nickname='tester')
        u.password = "******"

        u2 = User(email='*****@*****.**', nickname='tester2')
        u2.password = "******"

        db.session.add(u)
        db.session.add(u2)

        c1 = Client(client_id='dev',
                    client_secret='dev',
                    name='dev',
                    description='',
                    is_confidential=False,
                    user=u,
                    _redirect_uris='%s/oauth2test/authorized' % self.base_url,
                    _default_scopes="test:scope")

        c2 = Client(client_id='confidential',
                    client_secret='confidential',
                    name='confidential',
                    description='',
                    is_confidential=True,
                    user=u,
                    _redirect_uris='%s/oauth2test/authorized' % self.base_url,
                    _default_scopes="test:scope")

        db.session.add(c1)
        db.session.add(c2)

        db.session.commit()

        self.objects = [u, u2, c1, c2]

        # Create a personal access token as well.
        from ..models import Token
        self.personal_token = Token.create_personal('test-personal',
                                                    1,
                                                    scopes=[],
                                                    is_internal=True)
Ejemplo n.º 15
0
    def setUp(self):
        """Run before each test."""
        from invenio.modules.accounts.models import User

        self.user_a = User(email='*****@*****.**',
                           _password='******',
                           nickname='user_a')
        try:
            db.session.add(self.user_a)
            db.session.commit()
        except Exception:
            db.session.rollback()
            raise
        self.create_oauth_token(self.user_a.id, scopes=[""])
Ejemplo n.º 16
0
    def setUp(self):
        """Setup test."""
        from invenio.modules.oauthclient.models import RemoteToken, \
            RemoteAccount
        from invenio.modules.accounts.models import UserEXT, User
        RemoteToken.query.delete()
        RemoteAccount.query.delete()
        UserEXT.query.delete()
        User.query.filter_by(email=self.example_email).delete()

        self.u = User(email=self.existing_email, nickname='tester')
        self.u.password = "******"
        db.session.add(self.u)
        db.session.commit()
Ejemplo n.º 17
0
    def test_verify_email_works_with_numbers_and_strings(self):
        from invenio.modules.accounts.models import User

        u = User(email="*****@*****.**", password="")
        u.note = 2
        self.assertTrue(u.verify_email())

        u2 = User(email="*****@*****.**", password="")
        u2.note = "2"
        self.assertTrue(u2.verify_email())
def pre_upgrade():
    """Run pre-upgrade checks (optional)."""
    users = User.query.all()

    not_valid_nicknames = []
    for user in users:
        if not User.check_nickname(user.nickname):
            not_valid_nicknames.append(user)

    if len(not_valid_nicknames) > 0:
        list_users = ', '.join([u.nickname for u in not_valid_nicknames])
        raise RuntimeError(
            "These nicknames are not valid: {list_users}. "
            "Please fix them before continuing.".format(
                list_users=list_users)
        )
Ejemplo n.º 19
0
    def setUp(self):
        # Create celery application
        self.create_celery_app()

        self.app.extensions['zenodo_github.request_factory'] = partial(
            tclient_request_factory, self.client)

        # Run Flask initialization code - to before_first_request functions
        # being executed
        with self.app.test_request_context(''):
            self.app.try_trigger_before_first_request_functions()
            self.app.preprocess_request()

        # Create a user
        from invenio.modules.accounts.models import User
        self.user = User(email='*****@*****.**',
                         nickname='githubuser')
        self.user.password = "******"
        db.session.add(self.user)
        db.session.commit()

        # Create GitHub link
        from invenio.modules.oauthclient.models import RemoteToken
        from zenodo.modules.github.helpers import get_client_id
        from zenodo.modules.github.utils import init_account

        self.remote_token = RemoteToken.create(
            self.user.id,
            get_client_id(),
            "test",
            "",
        )

        # Init GitHub account and mock up GitHub API
        httpretty.enable()
        fixtures.register_github_api()
        init_account(self.remote_token)
        httpretty.disable()
Ejemplo n.º 20
0
def _get_users_invenio12(*args, **kwargs):
    """Get user accounts Invenio 1."""
    from invenio.dbquery import run_sql, deserialize_via_marshal
    User = namedtuple('User', [
        'id', 'email', 'password', 'password_salt', 'note', 'full_name',
        'settings', 'nickname', 'last_login'
    ])
    users = run_sql(
        'SELECT id, email, password, note, settings, nickname, last_login'
        ' FROM user',
        run_on_slave=True)
    return len(users), [
        User(
            id=user[0],
            email=user[1],
            password=user[2].decode('latin1'),
            password_salt=user[1],
            note=user[3],
            full_name=user[5],
            settings=deserialize_via_marshal(user[4]) if user[4] else {},
            # we don't have proper nicknames on Invenio v1
            nickname='id_{0}'.format(user[0]),
            last_login=user[6]) for user in users
    ]
Ejemplo n.º 21
0
    def setUp(self):
        """Set up some dummy data and a resource."""
        from invenio.modules.accounts.models import User
        from invenio.modules.oauth2server.models import Token

        self.data = range(25)

        # setup test api resources

        class TestDataResource(Resource):

            method_decorators = [require_api_auth()]

            @require_header('Content-Type', 'application/json')
            def get(self):
                import json
                from flask import make_response
                from invenio.ext.restful.errors import (InvalidPageError)
                from invenio.ext.restful import pagination
                # Test to see that the exceptions are raised correctly
                # In restful.py it is not needed because the error_hanler
                # takes care of exceptions
                response = None
                try:
                    # test data
                    testdata = range(25)
                    endpoint = request.endpoint
                    args = request.args
                    page = int(args.get('page', 1))
                    per_page = int(args.get('per_page', 10))
                    p = pagination.RestfulPagination(page=page,
                                                     per_page=per_page,
                                                     total_count=len(testdata))
                    data_to_return = p.slice(testdata)
                    kwargs = {}
                    kwargs['endpoint'] = endpoint
                    kwargs['args'] = request.args
                    link_header = p.link_header(**kwargs)
                    response = make_response(json.dumps(data_to_return))
                    response.headers[link_header[0]] = link_header[1]
                    response.headers['Content-Type'] = request.headers[
                        'Content-Type']
                except InvalidPageError as e:
                    exception = {}
                    exception['message'] = e.error_msg
                    exception['type'] = "{0}".format(type(e))
                    response = make_response(json.dumps(exception))
                return response

        # Register API resources
        api = self.app.extensions['restful']
        api.add_resource(TestDataResource, '/api/testdata/')

        # Create a user
        self.user = User(email='*****@*****.**', nickname='tester')
        self.user.password = "******"
        db.session.add(self.user)
        db.session.commit()

        # create token
        self.token = Token.create_personal('test-',
                                           self.user.id,
                                           scopes=[],
                                           is_internal=True)
Ejemplo n.º 22
0
    def test_note_is_converted_to_string(self):
        from invenio.modules.accounts.models import User

        u = User(email="*****@*****.**", password="")
        u.note = 2
        self.assertTrue(isinstance(u.note, str))
Ejemplo n.º 23
0
def registerUser(req,
                 email,
                 passw,
                 nickname,
                 register_without_nickname=False,
                 login_method=None,
                 ln=CFG_SITE_LANG):
    """Register user with the desired values of NICKNAME, EMAIL and
       PASSW.

       If REGISTER_WITHOUT_NICKNAME is set to True, then ignore
       desired NICKNAME and do not set any.  This is suitable for
       external authentications so that people can login without
       having to register an internal account first.

       Return 0 if the registration is successful, 1 if email is not
       valid, 2 if nickname is not valid, 3 if email is already in the
       database, 4 if nickname is already in the database, 5 when
       users cannot register themselves because of the site policy, 6 when the
       site is having problem contacting the user.

       If login_method is None or is equal to the key corresponding to local
       authentication, then CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS is taken
       in account for deciding the behaviour about registering.
       """

    # is email valid?
    email = email.lower()
    if not email_valid_p(email):
        return 1

    _ = gettext_set_language(ln)

    # is email already taken?
    res = run_sql("SELECT email FROM user WHERE email=%s", (email, ))
    if len(res) > 0:
        return 3

    if register_without_nickname:
        # ignore desired nick and use default empty string one:
        nickname = ""
    else:
        # is nickname valid?
        if not nickname_valid_p(nickname):
            return 2
        # is nickname already taken?
        res = run_sql("SELECT nickname FROM user WHERE nickname=%s",
                      (nickname, ))
        if len(res) > 0:
            return 4

    activated = 1  # By default activated

    if not login_method or not CFG_EXTERNAL_AUTHENTICATION[
            login_method]:  # local login
        if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 2:
            return 5
        elif CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT:
            activated = 2  # Email confirmation required
        elif CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 1:
            activated = 0  # Administrator confirmation required

    # okay, go on and register the user: FIXME
    user = User(nickname=nickname,
                email=email,
                password=passw,
                note=activated,
                last_login=datetime.datetime.now())

    if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT:
        user.verify_email()

    try:
        db.session.add(user)
        db.session.commit()
    except Exception:
        current_app.logger.exception("Could not store user.")
        db.session.rollback()
        return 7
    if activated == 1:  # Ok we consider the user as logged in :-)
        setUid(req, uid)
    return 0
Ejemplo n.º 24
0
    def setUp(self):
        from ..models import Scope
        from invenio.modules.accounts.models import User
        from invenio.modules.oauth2server.models import Client, Token

        from ..registry import scopes as scopes_registry

        # Register a test scope
        scopes_registry.register(Scope('test:scope1'))
        scopes_registry.register(Scope('test:scope2', internal=True))

        self.base_url = self.app.config.get('CFG_SITE_SECURE_URL')

        # Create needed objects
        u = User(
            email='*****@*****.**', nickname='tester'
        )
        u.password = "******"

        self.create_objects([u])

        # environment
        #
        # resource_owner -- client1 -- token_1
        #                     |
        #                     -------- token_2
        #                               |
        #       consumer ----------------

        # create resource_owner and consumer
        self.resource_owner = User(
            email='*****@*****.**',
            nickname='resource_owner', password='******')
        self.consumer = User(
            email='*****@*****.**', nickname='consumer',
            password='******')

        self.create_objects([self.resource_owner, self.consumer])

        # create resource_owner -> client_1
        self.u1c1 = Client(
            client_id='client_test_u1c1',
            client_secret='client_test_u1c1',
            name='client_test_u1c1',
            description='',
            is_confidential=False,
            user=self.resource_owner,
            _redirect_uris='',
            _default_scopes=""
        )

        self.create_objects([self.u1c1])

        # create resource_owner -> client_1 / resource_owner -> token_1
        self.u1c1u1t1 = Token(
            client=self.u1c1,
            user=self.resource_owner,
            token_type='u',
            access_token='dev_access_1',
            refresh_token='dev_refresh_1',
            expires=None,
            is_personal=False,
            is_internal=False,
            _scopes='',
        )
        # create consumer -> client_1 / resource_owner -> token_2
        self.u1c1u2t2 = Token(
            client=self.u1c1,
            user=self.consumer,
            token_type='u',
            access_token='dev_access_2',
            refresh_token='dev_refresh_2',
            expires=None,
            is_personal=False,
            is_internal=False,
            _scopes='',
        )

        # create objects
        self.create_objects([self.u1c1u1t1, self.u1c1u2t2])

        self.objects = [u,
                        self.resource_owner, self.consumer,
                        self.u1c1u1t1, self.u1c1u2t2]
Ejemplo n.º 25
0
    def setUp(self):
        from flask_restful import Resource, fields, marshal
        from invenio.modules.accounts.models import User
        from invenio.modules.oauth2server.models import Token

        class TagRepresenation(object):
            """A representation of a tag.

            This class will be only used to return a tag as JSON.
            """

            marshaling_fields = dict(id=fields.Integer,
                                     name=fields.String,
                                     id_user=fields.Integer)

            def __init__(self, retrieved_tag):
                """Initialization.

                Declared the attributes to marshal with a tag.
                :param retrieved_tag: a tag from the database
                """
                # get fields from the given tag
                self.id = retrieved_tag.id
                self.name = retrieved_tag.name
                self.id_user = retrieved_tag.id_user

            def marshal(self):
                """Marshal the Tag."""
                return marshal(self, self.marshaling_fields)

        class TestTagsResource(Resource):

            method_decorators = [require_api_auth()]

            @require_header('Content-Type', 'application/json')
            def get(self):
                import json
                from flask import make_response
                from invenio.ext.restful.errors import (RestfulError,
                                                        InvalidPageError)
                from invenio.ext.restful import pagination

                response = None
                try:
                    endpoint = request.endpoint
                    args = request.args
                    page = int(args.get('page', 1))
                    per_page = int(args.get('per_page', 2))
                    # check values arguments and raise exceptions if any errors
                    if per_page < 0:
                        raise RestfulError(
                            error_msg="Invalid per_page: {}".format(per_page),
                            status_code=400)
                    if page < 0:
                        raise InvalidPageError(
                            error_msg="Invalid page: {}".format(page),
                            status_code=400)

                    # need to sort by id
                    # also assuming only one user so no need to filter
                    # user's id
                    tags_q = WtgTAGPaginationMokup()
                    p = pagination.RestfulSQLAlchemyPagination(
                        query=tags_q, page=page, per_page=per_page)
                    if page > p.pages:
                        raise InvalidPageError(
                            error_msg="Invalid page: {}".format(page),
                            status_code=400)
                    tags_to_return = map(
                        lambda x: TagRepresenation(x).marshal(), p.items)

                    kwargs = {}
                    kwargs['endpoint'] = endpoint
                    kwargs['args'] = request.args
                    link_header = p.link_header(**kwargs)
                    response = make_response(json.dumps(tags_to_return))
                    response.headers[link_header[0]] = link_header[1]
                    response.headers['Content-Type'] = request.headers[
                        'Content-Type']
                except (RestfulError, InvalidPageError) as e:
                    exception = {}
                    exception['message'] = e.error_msg
                    exception['type'] = "{0}".format(type(e))
                    response = make_response(json.dumps(exception))
                return response

        # Register API resources
        api = self.app.extensions['restful']
        api.add_resource(TestTagsResource, '/api/testtags/')

        # Create a user
        self.user = User(email='*****@*****.**', nickname='tester')
        self.user.password = "******"
        db.session.add(self.user)
        db.session.commit()

        # create token
        self.token = Token.create_personal('test-',
                                           self.user.id,
                                           scopes=[],
                                           is_internal=True)
Ejemplo n.º 26
0
def registerUser(req, email, passw, nickname, register_without_nickname=False,
        login_method=None, ln=CFG_SITE_LANG):
    """Register user with the desired values of NICKNAME, EMAIL and
       PASSW.

       If REGISTER_WITHOUT_NICKNAME is set to True, then ignore
       desired NICKNAME and do not set any.  This is suitable for
       external authentications so that people can login without
       having to register an internal account first.

       Return 0 if the registration is successful, 1 if email is not
       valid, 2 if nickname is not valid, 3 if email is already in the
       database, 4 if nickname is already in the database, 5 when
       users cannot register themselves because of the site policy, 6 when the
       site is having problem contacting the user.

       If login_method is None or is equal to the key corresponding to local
       authentication, then CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS is taken
       in account for deciding the behaviour about registering.
       """

    # is email valid?
    email = email.lower()
    if not email_valid_p(email):
        return 1

    _ = gettext_set_language(ln)

    # is email already taken?
    res = run_sql("SELECT email FROM user WHERE email=%s", (email,))
    if len(res) > 0:
        return 3

    if register_without_nickname:
        # ignore desired nick and use default empty string one:
        nickname = ""
    else:
        # is nickname valid?
        if not nickname_valid_p(nickname):
            return 2
        # is nickname already taken?
        res = run_sql("SELECT nickname FROM user WHERE nickname=%s", (nickname,))
        if len(res) > 0:
            return 4

    activated = 1 # By default activated

    if not login_method or not CFG_EXTERNAL_AUTHENTICATION[login_method]: # local login
        if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 2:
            return 5
        elif CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT:
            activated = 2 # Email confirmation required
        elif CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 1:
            activated = 0 # Administrator confirmation required


    # okay, go on and register the user: FIXME
    user = User(nickname=nickname,
                email=email,
                password=passw,
                note=activated,
                last_login=datetime.datetime.now())

    if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT:
        user.verify_email()

    try:
        db.session.add(user)
        db.session.commit()
    except Exception:
        current_app.logger.exception("Could not store user.")
        db.session.rollback()
        return 7
    if activated == 1: # Ok we consider the user as logged in :-)
        setUid(req, uid)
    return 0
Ejemplo n.º 27
0
 def test_note_is_converted_to_string(self):
     from invenio.modules.accounts.models import User
     u = User(email="*****@*****.**", password="")
     u.note = 2
     self.assertTrue(isinstance(u.note, str))
    def setUp(self):
        super(OAuth2ProviderTestCase, self).setUp()
        # Set environment variable DEBUG to true, to allow testing without
        # SSL in oauthlib.
        if self.app.config.get('CFG_SITE_SECURE_URL').startswith('http://'):
            self.os_debug = os.environ.get('OAUTHLIB_INSECURE_TRANSPORT', '')
            os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = 'true'

        from ..models import Client, Scope
        from invenio.modules.accounts.models import User
        from ..registry import scopes as scopes_registry

        # Register a test scope
        scopes_registry.register(Scope('test:scope'))

        self.base_url = self.app.config.get('CFG_SITE_SECURE_URL')

        # Create needed objects
        u = User(
            email='*****@*****.**', nickname='tester'
        )
        u.password = "******"

        u2 = User(
            email='*****@*****.**', nickname='tester2'
        )
        u2.password = "******"

        db.session.add(u)
        db.session.add(u2)

        c1 = Client(
            client_id='dev',
            client_secret='dev',
            name='dev',
            description='',
            is_confidential=False,
            user=u,
            _redirect_uris='%s/oauth2test/authorized' % self.base_url,
            _default_scopes="test:scope"
        )

        c2 = Client(
            client_id='confidential',
            client_secret='confidential',
            name='confidential',
            description='',
            is_confidential=True,
            user=u,
            _redirect_uris='%s/oauth2test/authorized' % self.base_url,
            _default_scopes="test:scope"
        )

        db.session.add(c1)
        db.session.add(c2)

        db.session.commit()

        self.objects = [u, u2, c1, c2]

        # Create a personal access token as well.
        from ..models import Token
        self.personal_token = Token.create_personal(
            'test-personal', 1, scopes=[], is_internal=True
        )
Ejemplo n.º 29
0
def registerUser(req, email, passw, nickname, register_without_nickname=False,
        login_method=None, ln=CFG_SITE_LANG):
    """Register user with the desired values of NICKNAME, EMAIL and
       PASSW.

       If REGISTER_WITHOUT_NICKNAME is set to True, then ignore
       desired NICKNAME and do not set any.  This is suitable for
       external authentications so that people can login without
       having to register an internal account first.

       Return 0 if the registration is successful, 1 if email is not
       valid, 2 if nickname is not valid, 3 if email is already in the
       database, 4 if nickname is already in the database, 5 when
       users cannot register themselves because of the site policy, 6 when the
       site is having problem contacting the user.

       If login_method is None or is equal to the key corresponding to local
       authentication, then CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS is taken
       in account for deciding the behaviour about registering.
       """

    # is email valid?
    email = email.lower()
    if not email_valid_p(email):
        return 1

    _ = gettext_set_language(ln)

    # is email already taken?
    res = run_sql("SELECT email FROM user WHERE email=%s", (email,))
    if len(res) > 0:
        return 3

    if register_without_nickname:
        # ignore desired nick and use default empty string one:
        nickname = ""
    else:
        # is nickname valid?
        if not nickname_valid_p(nickname):
            return 2
        # is nickname already taken?
        res = run_sql("SELECT nickname FROM user WHERE nickname=%s", (nickname,))
        if len(res) > 0:
            return 4

    activated = 1 # By default activated

    if not login_method or not CFG_EXTERNAL_AUTHENTICATION[login_method]: # local login
        if CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 2:
            return 5
        elif CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT:
            activated = 2 # Email confirmation required
        elif CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS >= 1:
            activated = 0 # Administrator confirmation required

        if CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT:
            address_activation_key = mail_cookie_create_mail_activation(
                email,
                cookie_timeout=datetime.timedelta(
                    days=CFG_WEBSESSION_ADDRESS_ACTIVATION_EXPIRE_IN_DAYS
                )
            )
            try:
                ip_address = req.remote_host or req.remote_ip
            except:
                ip_address = None
            try:
                if not send_email(CFG_SITE_SUPPORT_EMAIL, email, _("Account registration at %(sitename)s", sitename=CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME)),
                                  tmpl.tmpl_account_address_activation_email_body(
                                      email, address_activation_key,
                                      ip_address, ln)):
                    return 1
            except (smtplib.SMTPException, socket.error):
                return 6

    # okay, go on and register the user: FIXME
    user = User(nickname=nickname,
                email=email,
                password=passw,
                note=activated)
    try:
        db.session.add(user)
        db.session.commit()
    except:
        db.session.rollback()
        return 7
    if activated == 1: # Ok we consider the user as logged in :-)
        setUid(req, uid)
    return 0
Ejemplo n.º 30
0
    def setUp(self):
        from invenio.modules.accounts.models import User
        from invenio.modules.oauth2server.registry import scopes
        from invenio.modules.oauth2server.models import Token, Scope

        # Setup variables:
        self.called = dict()

        # Setup test scopes
        with self.app.app_context():
            scopes.register(
                Scope(
                    'test:testscope',
                    group='Test',
                    help_text='Test scope',
                ))

        # Setup API resources
        class Test1Resource(Resource):
            # NOTE: Method decorators are applied in reverse order
            method_decorators = [
                require_oauth_scopes('test:testscope'),
                require_api_auth(),
            ]

            def get(self):
                assert request.oauth.access_token
                return "success", 200

            def post(self):
                assert request.oauth.access_token
                return "success", 200

            @require_header('Content-Type', 'application/json')
            def put(self):
                return "success", 200

        class Test2Resource(Resource):
            @require_api_auth()
            @require_oauth_scopes('test:testscope')
            def get(self):
                assert request.oauth.access_token
                return "success", 200

            @require_api_auth()
            @require_oauth_scopes('test:testscope')
            def post(self):
                assert request.oauth.access_token
                return "success", 200

            @require_header('Content-Type', 'text/html')
            def put(self):
                return "success", 200

        # Register API resources
        api = self.app.extensions['restful']
        api.add_resource(Test1Resource, '/api/test1/decoratorstestcase/')
        api.add_resource(Test2Resource, '/api/test2/decoratorstestcase/')

        # Create a user
        self.user = User(email='*****@*****.**', nickname='tester')
        self.user.password = "******"
        db.session.add(self.user)
        db.session.commit()

        # Create tokens
        self.token = Token.create_personal('test-',
                                           self.user.id,
                                           scopes=['test:testscope'],
                                           is_internal=True)
        self.token_noscope = Token.create_personal('test-',
                                                   self.user.id,
                                                   scopes=[],
                                                   is_internal=True)