本文整理汇总了Python中osf.models.OSFUser类的典型用法代码示例。如果您正苦于以下问题:Python OSFUser类的具体用法?Python OSFUser怎么用?Python OSFUser使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了OSFUser类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: deserialize_contributors
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
示例2: _get_current_user
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
示例3: save
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
示例4: get_contributors
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
示例5: get_user_from_cas_resp
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'
示例6: authenticate
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
示例7: send_users_email
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)
示例8: serialize_comment
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,
}
示例9: setUpClass
def setUpClass(cls):
super(TestVarnish, cls).setUpClass()
username = uuid.uuid4()
cls.user = OSFUser.create_confirmed(
username='{}@mail.com'.format(str(username)),
password='password',
fullname='Mocha Test User')
cls.user.save()
cls.authorization = HTTPBasicAuth(cls.user.username, 'password')
small = 5
large = 10
components = [[[range(small, random.randint(small, large))
for x in range(small, random.randint(small, large))]
for y in range(small, random.randint(small, large))]
for z in range(small, random.randint(small, large))]
number_of_projects = random.randint(1, 11)
number_of_tags = random.randint(1, 11)
number_of_users = random.randint(1, 11)
for i in range(number_of_projects):
name = ''
create_fake_project(cls.user, number_of_users,
random.choice(['public', 'private']),
components, name, number_of_tags, None, False)
示例10: redirect_to_twitter
def redirect_to_twitter(twitter_handle):
"""Redirect GET requests for /@TwitterHandle/ to respective the OSF user
account if it associated with an active account
:param uid: uid for requested User
:return: Redirect to User's Twitter account page
"""
try:
user = User.find_one(Q('social.twitter', 'iexact', twitter_handle))
except NoResultsFound:
raise HTTPError(http.NOT_FOUND, data={
'message_short': 'User Not Found',
'message_long': 'There is no active user associated with the Twitter handle: {0}.'.format(twitter_handle)
})
except MultipleResultsFound:
users = User.find(Q('social.twitter', 'iexact', twitter_handle))
message_long = 'There are multiple OSF accounts associated with the ' \
'Twitter handle: <strong>{0}</strong>. <br /> Please ' \
'select from the accounts below. <br /><ul>'.format(markupsafe.escape(twitter_handle))
for user in users:
message_long += '<li><a href="{0}">{1}</a></li>'.format(user.url, markupsafe.escape(user.fullname))
message_long += '</ul>'
raise HTTPError(http.MULTIPLE_CHOICES, data={
'message_short': 'Multiple Users Found',
'message_long': message_long
})
return redirect(user.url)
示例11: test_improperly_scoped_token_can_not_create_or_email
def test_improperly_scoped_token_can_not_create_or_email(self, mock_auth, mock_mail):
token = ApiOAuth2PersonalToken(
owner=self.user,
name='Unauthorized Token',
scopes='osf.full_write'
)
mock_cas_resp = CasResponse(
authenticated=True,
user=self.user._id,
attributes={
'accessToken': token.token_id,
'accessTokenScope': [s for s in token.scopes.split(' ')]
}
)
mock_auth.return_value = self.user, mock_cas_resp
assert_equal(User.find(Q('username', 'eq', self.unconfirmed_email)).count(), 0)
res = self.app.post_json_api(
'{}?send_email=true'.format(self.base_url),
self.data,
headers={'Authorization': 'Bearer {}'.format(token.token_id)},
expect_errors=True
)
assert_equal(res.status_code, 403)
assert_equal(User.find(Q('username', 'eq', self.unconfirmed_email)).count(), 0)
assert_equal(mock_mail.call_count, 0)
示例12: test_admin_scoped_token_can_create_and_send_email
def test_admin_scoped_token_can_create_and_send_email(self, mock_auth, mock_mail):
token = ApiOAuth2PersonalToken(
owner=self.user,
name='Admin Token',
scopes='osf.admin'
)
mock_cas_resp = CasResponse(
authenticated=True,
user=self.user._id,
attributes={
'accessToken': token.token_id,
'accessTokenScope': [s for s in token.scopes.split(' ')]
}
)
mock_auth.return_value = self.user, mock_cas_resp
assert_equal(User.find(Q('username', 'eq', self.unconfirmed_email)).count(), 0)
res = self.app.post_json_api(
'{}?send_email=true'.format(self.base_url),
self.data,
headers={'Authorization': 'Bearer {}'.format(token.token_id)}
)
assert_equal(res.status_code, 201)
assert_equal(res.json['data']['attributes']['username'], self.unconfirmed_email)
assert_equal(User.find(Q('username', 'eq', self.unconfirmed_email)).count(), 1)
assert_equal(mock_mail.call_count, 1)
示例13: test_properly_scoped_token_can_create_without_username_but_not_send_email
def test_properly_scoped_token_can_create_without_username_but_not_send_email(self, mock_auth, mock_mail):
token = ApiOAuth2PersonalToken(
owner=self.user,
name='Authorized Token',
scopes='osf.users.create'
)
mock_cas_resp = CasResponse(
authenticated=True,
user=self.user._id,
attributes={
'accessToken': token.token_id,
'accessTokenScope': [s for s in token.scopes.split(' ')]
}
)
mock_auth.return_value = self.user, mock_cas_resp
self.data['data']['attributes'] = {'full_name': 'No Email'}
assert_equal(User.find(Q('fullname', 'eq', 'No Email')).count(), 0)
res = self.app.post_json_api(
'{}?send_email=true'.format(self.base_url),
self.data,
headers={'Authorization': 'Bearer {}'.format(token.token_id)}
)
assert_equal(res.status_code, 201)
username = res.json['data']['attributes']['username']
try:
no_failure = UUID(username)
except ValueError:
raise AssertionError('Username is not a valid UUID')
assert_equal(User.find(Q('fullname', 'eq', 'No Email')).count(), 1)
assert_equal(mock_mail.call_count, 0)
示例14: test_logged_out_user_cannot_create_other_user_or_send_mail
def test_logged_out_user_cannot_create_other_user_or_send_mail(self, mock_mail):
assert_equal(User.find(Q('username', 'eq', self.unconfirmed_email)).count(), 0)
res = self.app.post_json_api(
'{}?send_email=true'.format(self.base_url),
self.data,
expect_errors=True
)
assert_equal(res.status_code, 401)
assert_equal(User.find(Q('username', 'eq', self.unconfirmed_email)).count(), 0)
assert_equal(mock_mail.call_count, 0)
示例15: find_inactive_users_with_no_inactivity_email_sent_or_queued
def find_inactive_users_with_no_inactivity_email_sent_or_queued():
inactive_users = User.find(
(Q('date_last_login', 'lt', timezone.now() - settings.NO_LOGIN_WAIT_TIME) & Q('tags__name', 'ne', 'osf4m')) |
(Q('date_last_login', 'lt', timezone.now() - settings.NO_LOGIN_OSF4M_WAIT_TIME) & Q('tags__name', 'eq', 'osf4m'))
)
inactive_emails = QueuedMail.find(Q('email_type', 'eq', NO_LOGIN_TYPE))
#This is done to prevent User query returns comparison to User, as equality fails
#on datetime fields due to pymongo rounding. Instead here _id is compared.
users_sent_id = [email.user._id for email in inactive_emails]
inactive_ids = [user._id for user in inactive_users if user.is_active]
users_to_send = [User.load(id) for id in (set(inactive_ids) - set(users_sent_id))]
return users_to_send