当前位置: 首页>>代码示例>>Python>>正文


Python OSFUser.load方法代码示例

本文整理汇总了Python中osf.models.OSFUser.load方法的典型用法代码示例。如果您正苦于以下问题:Python OSFUser.load方法的具体用法?Python OSFUser.load怎么用?Python OSFUser.load使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在osf.models.OSFUser的用法示例。


在下文中一共展示了OSFUser.load方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_user_from_cas_resp

# 需要导入模块: from osf.models import OSFUser [as 别名]
# 或者: from osf.models.OSFUser import load [as 别名]
def get_user_from_cas_resp(cas_resp):
    """
    Given a CAS service validation response, attempt to retrieve user information and next action.
    The `user` in `cas_resp` is the unique GUID of the user. Please do not use the primary key `id`
    or the email `username`. This holds except for the first step of ORCiD login.

    :param cas_resp: the cas service validation response
    :return: the user, the external_credential, and the next action
    """
    from osf.models import OSFUser
    if cas_resp.user:
        user = OSFUser.load(cas_resp.user)
        # cas returns a valid OSF user id
        if user:
            return user, None, 'authenticate'
        # cas does not return a valid OSF user id
        else:
            external_credential = validate_external_credential(cas_resp.user)
            # invalid cas response
            if not external_credential:
                return None, None, None
            # cas returns a valid external credential
            user = get_user(external_id_provider=external_credential['provider'],
                            external_id=external_credential['id'])
            # existing user found
            if user:
                return user, external_credential, 'authenticate'
            # user first time login through external identity provider
            else:
                return None, external_credential, 'external_first_login'
开发者ID:CenterForOpenScience,项目名称:osf.io,代码行数:32,代码来源:cas.py

示例2: send_users_email

# 需要导入模块: from osf.models import OSFUser [as 别名]
# 或者: from osf.models.OSFUser import load [as 别名]
def send_users_email(send_type):
    """Find pending Emails and amalgamates them into a single Email.

    :param send_type
    :return:
    """
    grouped_emails = get_users_emails(send_type)
    for group in grouped_emails:
        user = OSFUser.load(group['user_id'])
        if not user:
            log_exception()
            continue
        info = group['info']
        notification_ids = [message['_id'] for message in info]
        sorted_messages = group_by_node(info)
        if sorted_messages:
            if not user.is_disabled:
                mails.send_mail(
                    to_addr=user.username,
                    mimetype='html',
                    mail=mails.DIGEST,
                    name=user.fullname,
                    message=sorted_messages,
                )
            remove_notifications(email_notification_ids=notification_ids)
开发者ID:mfraezz,项目名称:osf.io,代码行数:27,代码来源:tasks.py

示例3: process_project_search_results

# 需要导入模块: from osf.models import OSFUser [as 别名]
# 或者: from osf.models.OSFUser import load [as 别名]
def process_project_search_results(results, **kwargs):
    """
    :param results: list of projects from the modular ODM search
    :return: we return the entire search result, which is a list of
    dictionaries. This includes the list of contributors.
    """
    user = kwargs['auth'].user

    ret = []

    for project in results:
        authors = get_node_contributors_abbrev(project=project, auth=kwargs['auth'])
        authors_html = ''
        for author in authors['contributors']:
            a = OSFUser.load(author['user_id'])
            authors_html += '<a href="%s">%s</a>' % (a.url, a.fullname)
            authors_html += author['separator'] + ' '
        authors_html += ' ' + authors['others_count']

        ret.append({
            'id': project._id,
            'label': project.title,
            'value': project.title,
            'category': 'My Projects' if user in project.contributors else 'Public Projects',
            'authors': authors_html,
        })

    return ret
开发者ID:adlius,项目名称:osf.io,代码行数:30,代码来源:views.py

示例4: get_public_components

# 需要导入模块: from osf.models import OSFUser [as 别名]
# 或者: from osf.models.OSFUser import load [as 别名]
def get_public_components(uid=None, user=None):
    user = user or User.load(uid)

    rel_child_ids = (
        NodeRelation.objects.filter(
            child__is_public=True,
            child__type='osf.node',  # nodes only (not collections or registration)
            child___contributors=user,  # user is a contributor
            is_node_link=False  # exclude childs by node linkage
        )
        .exclude(parent__type='osf.collection')
        .exclude(child__is_deleted=True)
        .values_list('child_id', flat=True)
    )

    nodes = (Node.objects.filter(id__in=rel_child_ids)
    .include('contributor__user__guids', 'guids', '_parents__parent__guids')
    # Defer some fields that we don't use for rendering node lists
    .defer('child_node_subscriptions', 'date_created', 'deleted_date', 'description',
           'file_guid_to_share_uuids')
        .order_by('-date_modified'))

    return [
        serialize_node_summary(node=node, auth=Auth(user), show_path=True)
        for node in nodes
    ]
开发者ID:adlius,项目名称:osf.io,代码行数:28,代码来源:views.py

示例5: check_spam

# 需要导入模块: from osf.models import OSFUser [as 别名]
# 或者: from osf.models.OSFUser import load [as 别名]
    def check_spam(self):
        request, user_id = get_request_and_user_id()
        user = OSFUser.load(user_id)
        if not isinstance(request, DummyRequest):
            request_headers = {
                k: v
                for k, v in get_headers_from_request(request).items()
                if isinstance(v, basestring)
            }

        node = self.wiki_page.node

        if not settings.SPAM_CHECK_ENABLED:
            return False
        if settings.SPAM_CHECK_PUBLIC_ONLY and not node.is_public:
            return False
        if 'ham_confirmed' in user.system_tags:
            return False

        content = self._get_spam_content(node)
        if not content:
            return
        is_spam = node.do_check_spam(
            user.fullname,
            user.username,
            content,
            request_headers
        )

        logger.info("Node ({}) '{}' smells like {} (tip: {})".format(
            node._id, node.title.encode('utf-8'), 'SPAM' if is_spam else 'HAM', node.spam_pro_tip
        ))
        if is_spam:
            node._check_spam_user(user)
        return is_spam
开发者ID:aaxelb,项目名称:osf.io,代码行数:37,代码来源:models.py

示例6: save

# 需要导入模块: from osf.models import OSFUser [as 别名]
# 或者: from osf.models.OSFUser import load [as 别名]
    def save(self, *args, **kwargs):
        first_save = not bool(self.pk)
        saved_fields = self.get_dirty_fields() or []
        old_subjects = kwargs.pop('old_subjects', [])
        if saved_fields:
            request, user_id = get_request_and_user_id()
            request_headers = {}
            if not isinstance(request, DummyRequest):
                request_headers = {
                    k: v
                    for k, v in get_headers_from_request(request).items()
                    if isinstance(v, basestring)
                }
            user = OSFUser.load(user_id)
            if user:
                self.check_spam(user, saved_fields, request_headers)

        if not first_save and ('ever_public' in saved_fields and saved_fields['ever_public']):
            raise ValidationError('Cannot set "ever_public" to False')

        ret = super(Preprint, self).save(*args, **kwargs)

        if first_save:
            self._set_default_region()
            self.update_group_permissions()
            self._add_creator_as_contributor()

        if (not first_save and 'is_published' in saved_fields) or self.is_published:
            update_or_enqueue_on_preprint_updated(preprint_id=self._id, old_subjects=old_subjects, saved_fields=saved_fields)
        return ret
开发者ID:CenterForOpenScience,项目名称:osf.io,代码行数:32,代码来源:preprint.py

示例7: _get_current_user

# 需要导入模块: from osf.models import OSFUser [as 别名]
# 或者: from osf.models.OSFUser import load [as 别名]
def _get_current_user():
    from osf.models import OSFUser
    current_user_id = get_current_user_id()
    if current_user_id:
        return OSFUser.load(current_user_id)
    else:
        return None
开发者ID:adlius,项目名称:osf.io,代码行数:9,代码来源:core.py

示例8: _get_current_user

# 需要导入模块: from osf.models import OSFUser [as 别名]
# 或者: from osf.models.OSFUser import load [as 别名]
def _get_current_user():
    from osf.models import OSFUser
    current_user_id = get_current_user_id()
    if current_user_id:
        return OSFUser.load(current_user_id, select_for_update=check_select_for_update(request))
    else:
        return None
开发者ID:leb2dg,项目名称:osf.io,代码行数:9,代码来源:core.py

示例9: get_contributors

# 需要导入模块: from osf.models import OSFUser [as 别名]
# 或者: from osf.models.OSFUser import load [as 别名]
    def get_contributors(self, obj):

        contributor_info = []

        if is_anonymized(self.context['request']):
            return contributor_info

        contributor_ids = obj.get('contributors', None)
        params_node = obj.get('node', None)

        if contributor_ids:
            for contrib_id in contributor_ids:
                user = OSFUser.load(contrib_id)
                unregistered_name = None
                if user.unclaimed_records.get(params_node):
                    unregistered_name = user.unclaimed_records[params_node].get('name', None)

                contributor_info.append({
                    'id': contrib_id,
                    'full_name': user.fullname,
                    'given_name': user.given_name,
                    'middle_names': user.middle_names,
                    'family_name': user.family_name,
                    'unregistered_name': unregistered_name,
                    'active': user.is_active
                })
        return contributor_info
开发者ID:adlius,项目名称:osf.io,代码行数:29,代码来源:serializers.py

示例10: _send_global_and_node_emails

# 需要导入模块: from osf.models import OSFUser [as 别名]
# 或者: from osf.models.OSFUser import load [as 别名]
def _send_global_and_node_emails(send_type):
    """
    Called by `send_users_email`. Send all global and node-related notification emails.
    """
    grouped_emails = get_users_emails(send_type)
    for group in grouped_emails:
        user = OSFUser.load(group['user_id'])
        if not user:
            log_exception()
            continue
        info = group['info']
        notification_ids = [message['_id'] for message in info]
        sorted_messages = group_by_node(info)
        if sorted_messages:
            if not user.is_disabled:
                # If there's only one node in digest we can show it's preferences link in the template.
                notification_nodes = sorted_messages['children'].keys()
                node = AbstractNode.load(notification_nodes[0]) if len(
                    notification_nodes) == 1 else None
                mails.send_mail(
                    to_addr=user.username,
                    mimetype='html',
                    can_change_node_preferences=bool(node),
                    node=node,
                    mail=mails.DIGEST,
                    name=user.fullname,
                    message=sorted_messages,
                )
            remove_notifications(email_notification_ids=notification_ids)
开发者ID:icereval,项目名称:osf.io,代码行数:31,代码来源:tasks.py

示例11: authenticate

# 需要导入模块: from osf.models import OSFUser [as 别名]
# 或者: from osf.models.OSFUser import load [as 别名]
    def authenticate(self, request):
        """
        Check whether the request provides a valid OAuth2 bearer token.
        The `user` in `cas_auth_response` is the unique GUID of the user. Please do not use
        the primary key `id` or the email `username`.

        :param request: the request
        :return: the user who owns the bear token and the cas repsonse
        """

        client = cas.get_client()
        try:
            auth_header_field = request.META['HTTP_AUTHORIZATION']
            auth_token = cas.parse_auth_header(auth_header_field)
        except (cas.CasTokenError, KeyError):
            return None

        try:
            cas_auth_response = client.profile(auth_token)
        except cas.CasHTTPError:
            raise exceptions.NotAuthenticated(_('User provided an invalid OAuth2 access token'))

        if cas_auth_response.authenticated is False:
            raise exceptions.NotAuthenticated(_('CAS server failed to authenticate this token'))

        user = OSFUser.load(cas_auth_response.user)
        if not user:
            raise exceptions.AuthenticationFailed(_('Could not find the user associated with this token'))

        check_user(user)
        return user, cas_auth_response
开发者ID:icereval,项目名称:osf.io,代码行数:33,代码来源:drf.py

示例12: deserialize_contributors

# 需要导入模块: from osf.models import OSFUser [as 别名]
# 或者: from osf.models.OSFUser import load [as 别名]
def deserialize_contributors(node, user_dicts, auth, validate=False):
    """View helper that returns a list of User objects from a list of
    serialized users (dicts). The users in the list may be registered or
    unregistered users.

    e.g. ``[{'id': 'abc123', 'registered': True, 'fullname': ..},
            {'id': None, 'registered': False, 'fullname'...},
            {'id': '123ab', 'registered': False, 'fullname': ...}]

    If a dict represents an unregistered user without an ID, creates a new
    unregistered User record.

    :param Node node: The node to add contributors to
    :param list(dict) user_dicts: List of serialized users in the format above.
    :param Auth auth:
    :param bool validate: Whether to validate and sanitize fields (if necessary)
    """

    # Add the registered contributors
    contribs = []
    for contrib_dict in user_dicts:
        fullname = contrib_dict['fullname']
        visible = contrib_dict['visible']
        email = contrib_dict.get('email')

        if validate is True:
            # Validate and sanitize inputs as needed. Email will raise error if invalid.
            # TODO Edge case bug: validation and saving are performed in same loop, so all in list
            # up to the invalid entry will be saved. (communicate to the user what needs to be retried)
            fullname = sanitize.strip_html(fullname)
            if not fullname:
                raise ValidationError('Full name field cannot be empty')
            if email:
                validate_email(email)  # Will raise a ValidationError if email invalid

        if contrib_dict['id']:
            contributor = OSFUser.load(contrib_dict['id'])
        else:
            try:
                contributor = OSFUser.create_unregistered(
                    fullname=fullname,
                    email=email)
                contributor.save()
            except ValidationError:
                ## FIXME: This suppresses an exception if ID not found & new validation fails; get_user will return None
                contributor = get_user(email=email)

        # Add unclaimed record if necessary
        if not contributor.is_registered:
            contributor.add_unclaimed_record(node, referrer=auth.user,
                given_name=fullname,
                email=email)
            contributor.save()

        contribs.append({
            'user': contributor,
            'visible': visible,
            'permissions': expand_permissions(contrib_dict.get('permission'))
        })
    return contribs
开发者ID:aaxelb,项目名称:osf.io,代码行数:62,代码来源:contributor.py

示例13: subscribe_mailchimp

# 需要导入模块: from osf.models import OSFUser [as 别名]
# 或者: from osf.models.OSFUser import load [as 别名]
def subscribe_mailchimp(list_name, user_id):
    user = User.load(user_id)
    m = get_mailchimp_api()
    list_id = get_list_id_from_name(list_name=list_name)

    if user.mailchimp_mailing_lists is None:
        user.mailchimp_mailing_lists = {}

    try:
        m.lists.subscribe(
            id=list_id,
            email={'email': user.username},
            merge_vars={
                'fname': user.given_name,
                'lname': user.family_name,
            },
            double_optin=False,
            update_existing=True,
        )

    except (mailchimp.ValidationError, mailchimp.ListInvalidBounceMemberError) as error:
        sentry.log_exception()
        sentry.log_message(error.message)
        user.mailchimp_mailing_lists[list_name] = False
    else:
        user.mailchimp_mailing_lists[list_name] = True
    finally:
        user.save()
开发者ID:adlius,项目名称:osf.io,代码行数:30,代码来源:mailchimp_utils.py

示例14: serialize_comment

# 需要导入模块: from osf.models import OSFUser [as 别名]
# 或者: from osf.models.OSFUser import load [as 别名]
def serialize_comment(comment):
    reports = [
        serialize_report(user, report)
        for user, report in comment.reports.iteritems()
    ]
    author_abs_url = furl(OSF_DOMAIN)
    author_abs_url.path.add(comment.user.url)

    return {
        'id': comment._id,
        'author': OSFUser.load(comment.user._id),
        'author_id': comment.user._id,
        'author_path': author_abs_url.url,
        'date_created': comment.created,
        'date_modified': comment.modified,
        'content': comment.content,
        'has_children': bool(getattr(comment, 'commented', [])),
        'modified': comment.edited,
        'is_deleted': comment.is_deleted,
        'spam_status': comment.spam_status,
        'reports': reports,
        'node': comment.node,
        'category': reports[0]['category'],
        'osf_support_email': OSF_SUPPORT_EMAIL,
    }
开发者ID:erinspace,项目名称:osf.io,代码行数:27,代码来源:serializers.py

示例15: send_claim_registered_email

# 需要导入模块: from osf.models import OSFUser [as 别名]
# 或者: from osf.models.OSFUser import load [as 别名]
def send_claim_registered_email(claimer, unclaimed_user, node, throttle=24 * 3600):
    """
    A registered user claiming the unclaimed user account as an contributor to a project.
    Send an email for claiming the account to the referrer and notify the claimer.

    :param claimer: the claimer
    :param unclaimed_user: the user account to claim
    :param node: the project node where the user account is claimed
    :param throttle: the time period in seconds before another claim for the account can be made
    :return:
    :raise: http.BAD_REQUEST
    """

    unclaimed_record = unclaimed_user.get_unclaimed_record(node._primary_key)

    # check throttle
    timestamp = unclaimed_record.get('last_sent')
    if not throttle_period_expired(timestamp, throttle):
        raise HTTPError(http.BAD_REQUEST, data=dict(
            message_long='User account can only be claimed with an existing user once every 24 hours'
        ))

    # roll the valid token for each email, thus user cannot change email and approve a different email address
    verification_key = generate_verification_key(verification_type='claim')
    unclaimed_record['token'] = verification_key['token']
    unclaimed_record['expires'] = verification_key['expires']
    unclaimed_record['claimer_email'] = claimer.username
    unclaimed_user.save()

    referrer = User.load(unclaimed_record['referrer_id'])
    claim_url = web_url_for(
        'claim_user_registered',
        uid=unclaimed_user._primary_key,
        pid=node._primary_key,
        token=unclaimed_record['token'],
        _external=True,
    )

    # Send mail to referrer, telling them to forward verification link to claimer
    mails.send_mail(
        referrer.username,
        mails.FORWARD_INVITE_REGISTERED,
        user=unclaimed_user,
        referrer=referrer,
        node=node,
        claim_url=claim_url,
        fullname=unclaimed_record['name'],
    )
    unclaimed_record['last_sent'] = get_timestamp()
    unclaimed_user.save()

    # Send mail to claimer, telling them to wait for referrer
    mails.send_mail(
        claimer.username,
        mails.PENDING_VERIFICATION_REGISTERED,
        fullname=claimer.fullname,
        referrer=referrer,
        node=node,
    )
开发者ID:adlius,项目名称:osf.io,代码行数:61,代码来源:contributor.py


注:本文中的osf.models.OSFUser.load方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。