Example #1
0
def access():
    """Access."""
    try:
        mail = mail_cookie_check_mail_activation(request.values['mailcookie'])

        u = User.query.filter(User.email == mail).one()
        u.note = 1
        try:
            db.session.commit()
        except SQLAlchemyError:
            db.session.rollback()
            flash(_('Authorization failled.'), 'error')
            redirect('/')

        if current_user.is_authenticated():
            current_user.reload()
            flash(_('Your email address has been validated'), 'success')
        else:
            UserInfo(u.id).reload()
            flash(
                _('Your email address has been validated, and you can '
                  'now proceed to sign-in.'), 'success')
    except Exception:
        current_app.logger.exception("Authorization failed.")
        flash(_('The authorization token is invalid.'), 'error')
    return redirect('/')
Example #2
0
    def test_change_password_password(self):
        """Test ChangePasswordForm password."""
        from invenio_accounts.forms import ChangePasswordForm
        from flask_login import login_user, logout_user
        from invenio.ext.login import UserInfo

        not_valid_pwd = "x" * (self.min_len - 1)
        valid_pwd = "x" * self.min_len

        login_user(UserInfo(self.user.id))
        form = ChangePasswordForm(current_password=self.password,
                                  password=valid_pwd,
                                  password2=valid_pwd)
        assert form.validate() is True

        form = ChangePasswordForm(current_password=self.password,
                                  password=not_valid_pwd,
                                  password2=not_valid_pwd)
        assert form.validate() is False

        form = ChangePasswordForm(current_password=self.password,
                                  password=valid_pwd,
                                  password2=valid_pwd + 'different')
        assert form.validate() is False

        logout_user()
Example #3
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
Example #4
0
def oauth_register(account_info, form_data=None):
    """Register user if possible."""
    from invenio_accounts.models import User

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

    if email:
        note = '1'
        if cfg['CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT']:
            note = '2'

        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,
                     note=note)

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

            # verify the email
            if note == '2':
                u.verify_email()

            return UserInfo(u.id)

    return None
Example #5
0
 def setUp(self):
     """setting up helper variables for tests"""
     from invenio.ext.login import UserInfo
     self.user_info = {'email' : '*****@*****.**', 'uid': 1000,
         'group' : ['patata', 'cetriolo'], 'remote_ip' : '127.0.0.1',
         'guest' : '0'}
     self.guest = UserInfo(None)
Example #6
0
    def test_profile_form_nickname(self):
        """Test ProfileForm nickname."""
        from invenio_accounts.forms import ProfileForm
        from flask_login import login_user, logout_user
        from invenio.ext.login import UserInfo

        form = ProfileForm(nickname=self.nickname,
                           email=self.email,
                           repeat_email=self.email)
        assert form.validate() is False

        form = ProfileForm(nickname=" nickname",
                           email=self.email,
                           repeat_email=self.email)
        assert form.validate() is False

        form = ProfileForm(nickname="nickname ",
                           email=self.email,
                           repeat_email=self.email)
        assert form.validate() is False

        form = ProfileForm(nickname="nick.name",
                           email=self.email,
                           repeat_email=self.email)
        assert form.validate() is False

        form = ProfileForm(nickname="nick@name",
                           email=self.email,
                           repeat_email=self.email)
        assert form.validate() is False

        form = ProfileForm(nickname="*****@*****.**",
                           email=self.email,
                           repeat_email=self.email)
        assert form.validate() is False

        form = ProfileForm(nickname="guest",
                           email=self.email,
                           repeat_email=self.email)
        assert form.validate() is False

        form = ProfileForm(nickname="Guest",
                           email=self.email,
                           repeat_email=self.email)
        assert form.validate() is False

        login_user(UserInfo(self.user.id))
        form = ProfileForm(nickname=self.nickname,
                           email=self.email,
                           repeat_email=self.email)
        assert form.validate() is True

        self.delete_objects([self.user])
        form = ProfileForm(nickname=self.nickname,
                           email=self.email,
                           repeat_email=self.email)
        assert form.validate() is True

        logout_user()
Example #7
0
def merge(deposition, dest, a, b):
    """
    Merge changes from editing a deposition.
    """
    # A record might have been approved in communities since it was loaded,
    # thus we "manually" merge communities
    approved = set(a['communities']) & set(b['provisional_communities'])

    communities = b['communities']
    provisional = []

    for c in b['provisional_communities']:
        if c in approved:
            if c not in communities:
                communities.append(c)
        else:
            provisional.append(c)

    # Ensure that no community is in two states
    common = set(communities) & set(provisional)
    for c in common:
        provisional.pop(c)

    b['communities'] = communities
    b['provisional_communities'] = provisional

    # Append Zenodo collection
    if CFG_ZENODO_USER_COLLECTION_ID in dest['communities']:
        a['communities'].append(CFG_ZENODO_USER_COLLECTION_ID)
        b['communities'].append(CFG_ZENODO_USER_COLLECTION_ID)
    elif CFG_ZENODO_USER_COLLECTION_ID in dest['provisional_communities']:
        a['provisional_communities'].append(CFG_ZENODO_USER_COLLECTION_ID)
        b['provisional_communities'].append(CFG_ZENODO_USER_COLLECTION_ID)

    if CFG_ECFUNDED_USER_COLLECTION_ID in dest['communities']:
        a['communities'].append(CFG_ECFUNDED_USER_COLLECTION_ID)
        b['communities'].append(CFG_ECFUNDED_USER_COLLECTION_ID)
    elif CFG_ECFUNDED_USER_COLLECTION_ID in dest['provisional_communities']:
        a['provisional_communities'].append(CFG_ECFUNDED_USER_COLLECTION_ID)
        b['provisional_communities'].append(CFG_ECFUNDED_USER_COLLECTION_ID)

    # Now proceed, with normal merging.
    data = merge_changes(deposition, dest, a, b)

    if 'authors' in data and data['authors']:
        data['_first_author'] = data['authors'][0]
        data['_additional_authors'] = data['authors'][1:]

    # Force ownership (owner of record (can edit/view the record))
    user = UserInfo(deposition.user_id)
    data['owner'].update(dict(
        email=user.info.get('email', ''),
        username=user.info.get('nickname', ''),
        id=deposition.user_id,
        deposition_id=deposition.id,
    ))

    return data
Example #8
0
def process_recjson_new(deposition, recjson):
    """
    Process exported recjson for a new record
    """
    process_recjson(deposition, recjson)

    # ================
    # Owner
    # ================
    # Owner of record (can edit/view the record)
    user = UserInfo(deposition.user_id)
    email = user.info.get('email', '')
    recjson['owner'] = dict(
        email=email,
        username=user.info.get('nickname', ''),
        id=deposition.user_id,
        deposition_id=deposition.id,
    )

    # ===========
    # Communities
    # ===========
    # Specific Zenodo user collection, used to curate content for
    # Zenodo
    if CFG_ZENODO_USER_COLLECTION_ID not in recjson['provisional_communities']:
        recjson['provisional_communities'].append(
            CFG_ZENODO_USER_COLLECTION_ID
        )

    # Specific Zenodo user collection for OpenAIRE (used to curate
    # FP7 funded research)
    if recjson.get('grants', []) and CFG_ECFUNDED_USER_COLLECTION_ID \
       not in recjson['provisional_communities']:
        recjson['provisional_communities'].append(
            CFG_ECFUNDED_USER_COLLECTION_ID
        )

    # ==============================
    # Files (sorting + restrictions)
    # ==============================
    fft_status = file_firerole(
        email, recjson['access_right'], recjson.get('embargo_date', None)
    )

    # Calculate number of leading zeros needed in the comment.
    file_commment_fmt = "%%0%dd" % len(str(len(recjson['fft'])))

    for idx, f in enumerate(recjson['fft']):
        f['restriction'] = fft_status
        # Bibdocfile does not have any concept of ordering, nor will
        # bibupload keep the order of FFT tags for the MARC field 8564.
        # Hence, this trick stores the ordering of files for a record in
        # the files comment, so files can be alphabetically sorted by their
        # comment (i.e. we add leading zeros).
        f['comment'] = file_commment_fmt % idx

    return recjson
Example #9
0
def is_no_quota_user(uid):
    """Return True if the user belongs to any of the no_quota roles."""
    no_quota_role_ids = [
        acc_get_role_id(role)
        for role in cfg['CFG_WEBMESSAGE_ROLES_WITHOUT_QUOTA']
    ]
    user_info = UserInfo(uid)
    for role_id in no_quota_role_ids:
        if acc_is_user_in_role(user_info, role_id):
            return True
    return False
Example #10
0
def oauth_get_user(client_id, account_info=None, access_token=None):
    """Retrieve user object for the given request.

    Uses either the access token or extracted account information to retrieve
    the user object.
    """
    if access_token:
        token = RemoteToken.get_by_token(client_id, access_token)
        if token:
            return UserInfo(token.remote_account.user_id)

    if account_info:
        external_id = _get_external_id(account_info)
        if external_id:
            u = UserEXT.query.filter_by(id=external_id['id'],
                                        method=external_id['method']).first()
            if u:
                return UserInfo(u.id_user)
        if account_info.get('email'):
            u = User.query.filter_by(email=account_info['email']).first()
            if u:
                return UserInfo(u.id)
    return None
Example #11
0
    def setUp(self):
        """Setup."""
        try:
            self.clear('simple')
        except Exception:
            pass
        from invenio.ext.login import UserInfo
        from invenio_deposit import field_widgets
        from invenio_deposit import fields
        from invenio_deposit.form import WebDepositForm
        from invenio_deposit.types import SimpleRecordDeposition

        class SimpleRecordTestForm(WebDepositForm):
            keywords = fields.DynamicFieldList(
                fields.StringField(
                    widget_classes='form-control',
                    widget=field_widgets.ColumnInput(class_="col-xs-10"),
                ),
                label='Keywords',
                add_label='Add another keyword',
                icon='fa fa-tags fa-fw',
                widget_classes='',
                min_entries=1,
            )
            publication_date = fields.Date(
                label=_('Publication date'),
                icon='fa fa-calendar fa-fw',
                description='Required. Format: YYYY-MM-DD.',
                default=date.today(),
                validators=[],
                widget=field_widgets.date_widget,
                widget_classes='input-sm',
                export_key='imprint.date',
            )

        class simple(SimpleRecordDeposition):
            name = "Simple Test"
            name_plural = "Simple Tests"
            group = "Tests"
            draft_definitions = {
                'default': SimpleRecordTestForm,
            }

            @classmethod
            def process_sip_metadata(cls, deposition, metadata):
                self.assert_process_metadata(deposition, metadata)

        self.register(simple)
        UserInfo(1, force=True)
Example #12
0
def collect_user_info(req, login_time=False, refresh=False):
    """Given the mod_python request object rec or a uid it returns a dictionary
    containing at least the keys uid, nickname, email, groups, plus any external keys in
    the user preferences (collected at login time and built by the different
    external authentication plugins) and if the mod_python request object is
    provided, also the remote_ip, remote_host, referer, agent fields.
    NOTE: if req is a mod_python request object, the user_info dictionary
    is saved into req._user_info (for caching purpouses)
    setApacheUser & setUid will properly reset it.
    """
    from flask_login import current_user
    from invenio.ext.login import UserInfo

    if (type(req) in [long, int] and current_user.get_id() != req) \
            or req is None:
        return UserInfo(req)

    return current_user._get_current_object()
Example #13
0
def acc_authorize_action(req, name_action, authorized_if_no_roles=False, batch_args=False, **arguments):
    """
    Given the request object (or the user_info dictionary, or the uid), checks
    if the user is allowed to run name_action with the given parameters.
    If authorized_if_no_roles is True and no role exists (different
    than superadmin) that are authorized to execute the given action, the
    authorization will be granted.
    Returns (0, msg) when the authorization is granted, (1, msg) when it's not.
    """
    from invenio.ext.login import UserInfo
    from werkzeug.local import LocalProxy

    if isinstance(req, LocalProxy):
        req = req._get_current_object()
    if isinstance(req, UserInfo):
        user_info = req
        uid = user_info.get_id()
    elif type(req) is dict:
        uid = req.get("uid", None)
        user_info = req
    elif type(req) not in [int, long]:
        uid = current_user.get_id()
        user_info = UserInfo(uid)  # FIXME
    else:
        user_info = current_user

    roles_list = acc_find_possible_roles(name_action, always_add_superadmin=True, batch_args=batch_args, **arguments)

    if not batch_args:
        roles_list = [roles_list]

    result = []
    for roles in roles_list:
        if acc_is_user_in_any_role(user_info, roles):
            # User belong to at least one authorized role
            # or User is SUPERADMIN
            ret_val = (0, CFG_WEBACCESS_WARNING_MSGS[0])
        elif len(roles) <= 1:
            ## No role is authorized for the given action/arguments
            if authorized_if_no_roles:
                # User is authorized because no authorization exists for the
                # given action/arguments
                ret_val = (0, CFG_WEBACCESS_WARNING_MSGS[0])
            else:
                # User is not authorized.
                ret_val = (20, CFG_WEBACCESS_WARNING_MSGS[20] % cgi.escape(name_action))
        else:
            # User is not authorized
            in_a_web_request_p = bool(user_info.get("uri", ""))
            ret_val = (
                1,
                "%s %s"
                % (
                    CFG_WEBACCESS_WARNING_MSGS[1],
                    (
                        in_a_web_request_p
                        and "%s %s" % (CFG_WEBACCESS_MSGS[0] % quote(user_info.get("uri", "")), CFG_WEBACCESS_MSGS[1])
                        or ""
                    ),
                ),
            )
        result.append(ret_val)
    # FIXME removed CERN specific hack!
    return result if batch_args else result[0]
Example #14
0
def acc_authorize_action(req,
                         name_action,
                         authorized_if_no_roles=False,
                         batch_args=False,
                         **arguments):
    """
    Given the request object (or the user_info dictionary, or the uid), checks
    if the user is allowed to run name_action with the given parameters.
    If authorized_if_no_roles is True and no role exists (different
    than superadmin) that are authorized to execute the given action, the
    authorization will be granted.
    Returns (0, msg) when the authorization is granted, (1, msg) when it's not.
    """
    from invenio.ext.login import UserInfo
    from werkzeug.local import LocalProxy
    if isinstance(req, LocalProxy):
        req = req._get_current_object()
    if isinstance(req, UserInfo):
        user_info = req
        uid = user_info.get_id()
    elif type(req) is dict:
        uid = req.get('uid', None)
        user_info = req
    elif type(req) not in [int, long]:
        uid = current_user.get_id()
        user_info = UserInfo(uid)  # FIXME
    else:
        user_info = current_user

    roles_list = acc_find_possible_roles(name_action,
                                         always_add_superadmin=True,
                                         batch_args=batch_args,
                                         **arguments)

    if not batch_args:
        roles_list = [roles_list]

    result = []
    for roles in roles_list:
        if acc_is_user_in_any_role(user_info, roles):
            # User belong to at least one authorized role
            # or User is SUPERADMIN
            ret_val = (0, CFG_WEBACCESS_WARNING_MSGS[0])
        elif len(roles) <= 1:
            ## No role is authorized for the given action/arguments
            if authorized_if_no_roles:
                # User is authorized because no authorization exists for the
                # given action/arguments
                ret_val = (0, CFG_WEBACCESS_WARNING_MSGS[0])
            else:
                # User is not authorized.
                ret_val = (20, CFG_WEBACCESS_WARNING_MSGS[20] %
                           cgi.escape(name_action))
        else:
            # User is not authorized
            in_a_web_request_p = bool(user_info.get('uri', ''))
            ret_val = (
                1, "%s %s" %
                (CFG_WEBACCESS_WARNING_MSGS[1],
                 (in_a_web_request_p and "%s %s" %
                  (CFG_WEBACCESS_MSGS[0] % quote(user_info.get('uri', '')),
                   CFG_WEBACCESS_MSGS[1]) or "")))
        result.append(ret_val)
    # FIXME removed CERN specific hack!
    return result if batch_args else result[0]