本文整理汇总了Python中website.models.User.load方法的典型用法代码示例。如果您正苦于以下问题:Python User.load方法的具体用法?Python User.load怎么用?Python User.load使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类website.models.User
的用法示例。
在下文中一共展示了User.load方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_waterbutler_log
# 需要导入模块: from website.models import User [as 别名]
# 或者: from website.models.User import load [as 别名]
def create_waterbutler_log(payload, **kwargs):
try:
auth = payload['auth']
action = payload['action']
provider = payload['provider']
metadata = payload['metadata']
except KeyError:
raise HTTPError(httplib.BAD_REQUEST)
metadata['path'] = metadata['path'].lstrip('/')
user = User.load(auth['id'])
if user is None:
raise HTTPError(httplib.BAD_REQUEST)
node = kwargs['node'] or kwargs['project']
node_addon = node.get_addon(provider)
if node_addon is None:
raise HTTPError(httplib.BAD_REQUEST)
try:
osf_action = LOG_ACTION_MAP[action]
except KeyError:
raise HTTPError(httplib.BAD_REQUEST)
auth = Auth(user=user)
node_addon.create_waterbutler_log(auth, osf_action, metadata)
return {'status': 'success'}
示例2: confirm_email_get
# 需要导入模块: from website.models import User [as 别名]
# 或者: from website.models.User import load [as 别名]
def confirm_email_get(**kwargs):
"""View for email confirmation links.
Authenticates and redirects to user settings page if confirmation is
successful, otherwise shows an "Expired Link" error.
methods: GET
"""
user = User.load(kwargs['uid'])
token = kwargs['token']
if user:
if user.confirm_email(token): # Confirm and register the user
user.date_last_login = datetime.datetime.utcnow()
user.save()
# Go to settings page
status.push_status_message(language.WELCOME_MESSAGE, 'success')
response = redirect('/settings/')
return framework.auth.authenticate(user, response=response)
# Return data for the error template
return {
'code': http.BAD_REQUEST,
'message_short': 'Link Expired',
'message_long': language.LINK_EXPIRED
}, http.BAD_REQUEST
示例3: migrate_to_external_account
# 需要导入模块: from website.models import User [as 别名]
# 或者: from website.models.User import load [as 别名]
def migrate_to_external_account(user_settings_document):
user_info = utils.get_user_info(access_key=user_settings_document['access_key'], secret_key=user_settings_document['secret_key'])
user = User.load(user_settings_document['owner'])
if not user_info:
return (None, None, None)
new = False
try:
external_account = ExternalAccount.find_one(Q('provider_id', 'eq', user_info.id))
logger.info('Duplicate account use found: s3usersettings {0} with id {1}'.format(user_settings_document['_id'], user._id))
except NoResultsFound:
new = True
external_account = ExternalAccount(
provider=PROVIDER,
provider_name=PROVIDER_NAME,
provider_id=user_info.id,
oauth_key=user_settings_document['access_key'],
oauth_secret=user_settings_document['secret_key'],
display_name=user_info.display_name,
)
external_account.save()
user.external_accounts.append(external_account)
user.save()
return external_account, user, new
示例4: test_embargoed_registration_set_privacy_sends_mail
# 需要导入模块: from website.models import User [as 别名]
# 或者: from website.models.User import load [as 别名]
def test_embargoed_registration_set_privacy_sends_mail(self, mock_send_mail):
"""
Integration test for https://github.com/CenterForOpenScience/osf.io/pull/5294#issuecomment-212613668
"""
# Initiate and approve embargo
for i in range(3):
c = AuthUserFactory()
self.registration.add_contributor(c, [permissions.ADMIN], auth=Auth(self.user))
self.registration.save()
self.registration.embargo_registration(
self.user,
datetime.datetime.utcnow() + datetime.timedelta(days=10)
)
for user_id, embargo_tokens in self.registration.embargo.approval_state.iteritems():
approval_token = embargo_tokens['approval_token']
self.registration.embargo.approve_embargo(User.load(user_id), approval_token)
self.registration.save()
res = self.app.post(
self.registration.api_url_for('project_set_privacy', permissions='public'),
auth=self.user.auth,
)
assert_equal(res.status_code, 200)
for admin in self.registration.admin_contributors:
assert_true(any([c[0][0] == admin.username for c in mock_send_mail.call_args_list]))
示例5: test_make_child_embargoed_registration_public_asks_all_admins_in_tree
# 需要导入模块: from website.models import User [as 别名]
# 或者: from website.models.User import load [as 别名]
def test_make_child_embargoed_registration_public_asks_all_admins_in_tree(self, mock_ask):
# Initiate and approve embargo
node = NodeFactory(creator=self.user)
c1 = AuthUserFactory()
child = NodeFactory(parent=node, creator=c1)
c2 = AuthUserFactory()
NodeFactory(parent=child, creator=c2)
registration = RegistrationFactory(project=node)
registration.embargo_registration(
self.user,
datetime.datetime.utcnow() + datetime.timedelta(days=10)
)
for user_id, embargo_tokens in registration.embargo.approval_state.iteritems():
approval_token = embargo_tokens['approval_token']
registration.embargo.approve_embargo(User.load(user_id), approval_token)
self.registration.save()
res = self.app.post(
registration.api_url_for('project_set_privacy', permissions='public'),
auth=self.user.auth
)
assert_equal(res.status_code, 200)
asked_admins = [(admin._id, n._id) for admin, n in mock_ask.call_args[0][0]]
for admin, node in registration.get_admin_contributors_recursive():
assert_in((admin._id, node._id), asked_admins)
示例6: osf_user
# 需要导入模块: from website.models import User [as 别名]
# 或者: from website.models.User import load [as 别名]
def osf_user(self):
# import on call to avoid interference w/ django's manage.py commands like collectstatic
from website.models import User as OsfUserModel
if not self.osf_id:
raise RuntimeError('This user does not have an associated Osf User')
return OsfUserModel.load(self.osf_id)
示例7: test_embargoed_registration_set_privacy_requests_embargo_termination
# 需要导入模块: from website.models import User [as 别名]
# 或者: from website.models.User import load [as 别名]
def test_embargoed_registration_set_privacy_requests_embargo_termination(self, mock_ask):
# Initiate and approve embargo
for i in range(3):
c = AuthUserFactory()
self.registration.add_contributor(c, [permissions.ADMIN], auth=Auth(self.user))
self.registration.save()
self.registration.embargo_registration(
self.user,
datetime.datetime.utcnow() + datetime.timedelta(days=10)
)
for user_id, embargo_tokens in self.registration.embargo.approval_state.iteritems():
approval_token = embargo_tokens['approval_token']
self.registration.embargo.approve_embargo(User.load(user_id), approval_token)
self.registration.save()
res = self.app.post(
self.registration.api_url_for('project_set_privacy', permissions='public'),
auth=self.user.auth,
)
assert_equal(res.status_code, 200)
for reg in self.registration.node_and_primary_descendants():
reg.reload()
assert_false(reg.is_public)
assert_true(reg.embargo_termination_approval)
assert_true(reg.embargo_termination_approval.is_pending_approval)
示例8: process_project_search_results
# 需要导入模块: from website.models import User [as 别名]
# 或者: from website.models.User 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 = User.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
示例9: move_subscription
# 需要导入模块: from website.models import User [as 别名]
# 或者: from website.models.User import load [as 别名]
def move_subscription(remove_users, source_event, source_node, new_event, new_node):
"""Moves subscription from old_node to new_node
:param remove_users: dictionary of lists of users to remove from the subscription
:param source_event: A specific guid event <guid>_file_updated
:param source_node: Instance of Node
:param new_event: A specific guid event
:param new_node: Instance of Node
:return: Returns a NOTIFICATION_TYPES list of removed users without permissions
"""
if source_node == new_node:
return
old_sub = NotificationSubscription.load(to_subscription_key(source_node._id, source_event))
if not old_sub:
return
elif old_sub:
old_sub.update_fields(_id=to_subscription_key(new_node._id, new_event), event_name=new_event,
owner=new_node)
new_sub = old_sub
# Remove users that don't have permission on the new node.
for notification_type in constants.NOTIFICATION_TYPES:
if new_sub:
for user_id in remove_users[notification_type]:
if user_id in getattr(new_sub, notification_type, []):
user = User.load(user_id)
new_sub.remove_user_from_subscription(user)
示例10: reset_password_get
# 需要导入模块: from website.models import User [as 别名]
# 或者: from website.models.User import load [as 别名]
def reset_password_get(auth, uid=None, token=None):
"""
View for user to land on the reset password page.
HTTp Method: GET
:param auth: the authentication state
:param uid: the user id
:param token: the token in verification key
:return
:raises: HTTPError(http.BAD_REQUEST) if verification key for the user is invalid, has expired or was used
"""
# if users are logged in, log them out and redirect back to this page
if auth.logged_in:
return auth_logout(redirect_url=request.url)
# Check if request bears a valid pair of `uid` and `token`
user_obj = User.load(uid)
if not (user_obj and user_obj.verify_password_token(token=token)):
error_data = {
'message_short': 'Invalid Request.',
'message_long': 'The requested URL is invalid, has expired, or was already used',
}
raise HTTPError(http.BAD_REQUEST, data=error_data)
# refresh the verification key (v2)
user_obj.verification_key_v2 = generate_verification_key(verification_type='password')
user_obj.save()
return {
'uid': user_obj._id,
'token': user_obj.verification_key_v2['token'],
}
示例11: salvage_broken_user_settings_document
# 需要导入模块: from website.models import User [as 别名]
# 或者: from website.models.User import load [as 别名]
def salvage_broken_user_settings_document(document):
if not document['access_token'] or not document['dropbox_id']:
return False
if not document['owner'] or not User.load(document['owner']).is_active:
return False
if document['deleted']:
return False
if not document.get('dropbox_info') or not document['dropbox_info']['display_name']:
logger.info(
"Attempting dropbox_info population for document (id:{0})".format(document['_id'])
)
client = DropboxClient(document['access_token'])
document['dropbox_info'] = {}
try:
database['dropboxusersettings'].find_and_modify(
{'_id': document['_id']},
{
'$set': {
'dropbox_info': client.account_info()
}
}
)
except Exception:
# Invalid token probably
# Still want Dropbox to be enabled to show error message
# to user on node settings, pass
return True
else:
return True
return False
示例12: confirm_email_get
# 需要导入模块: from website.models import User [as 别名]
# 或者: from website.models.User import load [as 别名]
def confirm_email_get(token, auth=None, **kwargs):
"""View for email confirmation links.
Authenticates and redirects to user settings page if confirmation is
successful, otherwise shows an "Expired Link" error.
methods: GET
"""
user = User.load(kwargs['uid'])
is_merge = 'confirm_merge' in request.args
is_initial_confirmation = not user.date_confirmed
if user is None:
raise HTTPError(http.NOT_FOUND)
if auth and auth.user and (auth.user._id == user._id or auth.user._id == user.merged_by._id):
if not is_merge:
# determine if the user registered through a campaign
campaign = campaigns.campaign_for_user(user)
if campaign:
return redirect(
campaigns.campaign_url_for(campaign)
)
status.push_status_message(language.WELCOME_MESSAGE, 'default', jumbotron=True)
# Go to dashboard
return redirect(web_url_for('dashboard'))
status.push_status_message(language.MERGE_COMPLETE, 'success')
return redirect(web_url_for('user_account'))
try:
user.confirm_email(token, merge=is_merge)
except exceptions.EmailConfirmTokenError as e:
raise HTTPError(http.BAD_REQUEST, data={
'message_short': e.message_short,
'message_long': e.message_long
})
if is_initial_confirmation:
user.date_last_login = datetime.datetime.utcnow()
user.save()
# Send out our welcome message
mails.send_mail(
to_addr=user.username,
mail=mails.WELCOME,
mimetype='html',
user=user
)
# Redirect to CAS and authenticate the user with a verification key.
user.verification_key = security.random_string(20)
user.save()
return redirect(cas.get_login_url(
request.url,
auto=True,
username=user.username,
verification_key=user.verification_key
))
示例13: get_public_components
# 需要导入模块: from website.models import User [as 别名]
# 或者: from website.models.User import load [as 别名]
def get_public_components(uid=None, user=None):
user = user or User.load(uid)
# TODO: This should use User.visible_contributor_to?
# In future redesign, should be limited for users with many projects / components
nodes = list(
Node.find_for_user(user, subquery=(PROJECT_QUERY & Q("parent_node", "ne", None) & Q("is_public", "eq", True)))
)
return _render_nodes(nodes, show_path=True)
示例14: osfstorage_create_child
# 需要导入模块: from website.models import User [as 别名]
# 或者: from website.models.User import load [as 别名]
def osfstorage_create_child(file_node, payload, node_addon, **kwargs):
parent = file_node # Just for clarity
name = payload.get("name")
user = User.load(payload.get("user"))
is_folder = payload.get("kind") == "folder"
if not (name or user) or "/" in name:
raise HTTPError(httplib.BAD_REQUEST)
try:
if is_folder:
created, file_node = True, parent.append_folder(name)
else:
created, file_node = True, parent.append_file(name)
except KeyExistsException:
created, file_node = False, parent.find_child_by_name(name, kind="folder" if is_folder else "file")
if not created and is_folder:
raise HTTPError(
httplib.CONFLICT,
data={
"message": 'Cannot create folder "{name}" because a file or folder already exists at path "{path}"'.format(
name=file_node.name, path=file_node.materialized_path()
)
},
)
if not is_folder:
try:
version = file_node.create_version(
user,
dict(
payload["settings"],
**dict(
payload["worker"],
**{"object": payload["metadata"]["name"], "service": payload["metadata"]["provider"]}
)
),
dict(payload["metadata"], **payload["hashes"]),
)
version_id = version._id
archive_exists = version.archive is not None
except KeyError:
raise HTTPError(httplib.BAD_REQUEST)
else:
version_id = None
archive_exists = False
return (
{
"status": "success",
"archive": not archive_exists, # Should waterbutler also archive this file
"data": file_node.serialized(),
"version": version_id,
},
httplib.CREATED if created else httplib.OK,
)
示例15: get_organization_json
# 需要导入模块: from website.models import User [as 别名]
# 或者: from website.models.User import load [as 别名]
def get_organization_json(*args, **kwargs):
uid = kwargs.get('uid', None)
if uid:
user = User.load(uid)
if user:
badger = user.get_addon('badges')
if badger:
return badger.to_openbadge()
raise HTTPError(http.BAD_REQUEST)