本文整理汇总了Python中framework.auth.core.User类的典型用法代码示例。如果您正苦于以下问题:Python User类的具体用法?Python User怎么用?Python User使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了User类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: populate_conferences
def populate_conferences():
for meeting, attrs in MEETING_DATA.iteritems():
meeting = meeting.strip()
admin_emails = attrs.pop("admins")
admin_objs = []
for email in admin_emails:
try:
user = User.find_one(Q("username", "iexact", email))
admin_objs.append(user)
except ModularOdmException:
raise RuntimeError("Username {0!r} is not registered.".format(email))
conf = Conference(endpoint=meeting, admins=admin_objs, **attrs)
try:
conf.save()
except ModularOdmException:
print("{0} Conference already exists. Updating existing record...".format(meeting))
conf = Conference.find_one(Q("endpoint", "eq", meeting))
for key, value in attrs.items():
setattr(conf, key, value)
conf.admins = admin_objs
changed_fields = conf.save()
if changed_fields:
print("Changed: {}".format(changed_fields))
else:
print("Added new Conference: {}".format(meeting))
示例2: subscribe_mailchimp
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 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()
示例3: 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 = User.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
示例4: 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)
if not grouped_emails:
return
for group in grouped_emails:
user = User.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:
mails.send_mail(
to_addr=user.username,
mimetype='html',
mail=mails.DIGEST,
name=user.fullname,
message=sorted_messages,
callback=remove_notifications(email_notification_ids=notification_ids)
)
示例5: send_digest
def send_digest(grouped_digests):
""" Send digest emails and remove digests for sent messages in a callback.
:param grouped_digests: digest notification messages from the past 24 hours grouped by user
:return:
"""
for group in grouped_digests:
user = User.load(group['user_id'])
if not user:
sentry.log_exception()
sentry.log_message("A user with this username does not exist.")
return
info = group['info']
digest_notification_ids = [message['_id'] for message in info]
sorted_messages = group_messages_by_node(info)
if sorted_messages:
logger.info('Sending email digest to user {0!r}'.format(user))
mails.send_mail(
to_addr=user.username,
mimetype='html',
mail=mails.DIGEST,
name=user.fullname,
message=sorted_messages,
callback=remove_sent_digest_notifications.si(
digest_notification_ids=digest_notification_ids
)
)
示例6: test_send_digest_called_with_correct_args
def test_send_digest_called_with_correct_args(self, mock_send_mail, mock_callback):
d = factories.NotificationDigestFactory(
user_id=factories.UserFactory()._id,
timestamp=datetime.datetime.utcnow(),
message='Hello',
node_lineage=[factories.ProjectFactory()._id]
)
d.save()
user_groups = group_digest_notifications_by_user()
send_digest(user_groups)
assert_true(mock_send_mail.called)
assert_equals(mock_send_mail.call_count, len(user_groups))
last_user_index = len(user_groups) - 1
user = User.load(user_groups[last_user_index]['user_id'])
digest_notification_ids = [message['_id'] for message in user_groups[last_user_index]['info']]
args, kwargs = mock_send_mail.call_args
assert_equal(kwargs['to_addr'], user.username)
assert_equal(kwargs['mimetype'], 'html')
assert_equal(kwargs['mail'], mails.DIGEST)
assert_equal(kwargs['name'], user.fullname)
message = group_messages_by_node(user_groups[last_user_index]['info'])
assert_equal(kwargs['message'], message)
assert_equal(kwargs['callback'],
mock_callback.si(digest_notification_ids=digest_notification_ids))
示例7: 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 = User.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
示例8: get_queryset
def get_queryset(self):
log = self.get_log()
associated_contrib_ids = log.params.get('contributors')
if associated_contrib_ids is None:
return []
associated_users = User.find(Q('_id', 'in', associated_contrib_ids))
return associated_users
示例9: populate_conferences
def populate_conferences():
for meeting, attrs in MEETING_DATA.iteritems():
meeting = meeting.strip()
admin_emails = attrs.pop('admins', [])
admin_objs = []
for email in admin_emails:
try:
user = User.find_one(Q('username', 'iexact', email))
admin_objs.append(user)
except ModularOdmException:
raise RuntimeError('Username {0!r} is not registered.'.format(email))
conf = Conference(
endpoint=meeting, admins=admin_objs, **attrs
)
try:
conf.save()
except ModularOdmException:
conf = Conference.find_one(Q('endpoint', 'eq', meeting))
for key, value in attrs.items():
setattr(conf, key, value)
conf.admins = admin_objs
changed_fields = conf.save()
if changed_fields:
print('Updated {}: {}'.format(meeting, changed_fields))
else:
print('Added new Conference: {}'.format(meeting))
示例10: before_request
def before_request():
from framework.auth import authenticate
from framework.auth.core import User
from framework.auth import cas
# Central Authentication Server Ticket Validation and Authentication
ticket = request.args.get('ticket')
if ticket:
service_url = furl.furl(request.url)
service_url.args.pop('ticket')
# Attempt autn wih CAS, and return a proper redirect response
return cas.make_response_from_ticket(ticket=ticket, service_url=service_url.url)
# Central Authentication Server OAuth Bearer Token
authorization = request.headers.get('Authorization')
if authorization and authorization.startswith('Bearer '):
client = cas.get_client()
try:
access_token = cas.parse_auth_header(authorization)
except cas.CasTokenError as err:
# NOTE: We assume that the request is an AJAX request
return jsonify({'message_short': 'Invalid Bearer token', 'message_long': err.args[0]}), http.UNAUTHORIZED
cas_resp = client.profile(access_token)
if cas_resp.authenticated:
user = User.load(cas_resp.user)
return authenticate(user, access_token=access_token, response=None)
return make_response('', http.UNAUTHORIZED)
if request.authorization:
# TODO: Fix circular import
from framework.auth.core import get_user
user = get_user(
email=request.authorization.username,
password=request.authorization.password
)
# Create empty session
# TODO: Shoudn't need to create a session for Basic Auth
session = Session()
if user:
session.data['auth_user_username'] = user.username
session.data['auth_user_id'] = user._primary_key
session.data['auth_user_fullname'] = user.fullname
else:
# Invalid key: Not found in database
session.data['auth_error_code'] = http.FORBIDDEN
set_session(session)
return
cookie = request.cookies.get(settings.COOKIE_NAME)
if cookie:
try:
session_id = itsdangerous.Signer(settings.SECRET_KEY).unsign(cookie)
session = Session.load(session_id) or Session(_id=session_id)
set_session(session)
return
except:
pass
示例11: update_comments_viewed_timestamp
def update_comments_viewed_timestamp():
users = User.find(Q('comments_viewed_timestamp', 'ne', None) | Q('comments_viewed_timestamp', 'ne', {}))
for user in users:
if user.comments_viewed_timestamp:
for node in user.comments_viewed_timestamp:
user.comments_viewed_timestamp[node] = {'node': user.comments_viewed_timestamp[node]}
user.save()
logger.info('Migrated timestamp for user {0}'.format(user._id))
示例12: test_all_users_have_wiki_osfstorage_enabled
def test_all_users_have_wiki_osfstorage_enabled(self):
all_user_count = User.find().count()
results = AddonSnapshot().get_events()
osfstorage_res = [res for res in results if res['provider']['name'] == 'osfstorage'][0]
wiki_res = [res for res in results if res['provider']['name'] == 'osfstorage'][0]
assert_equal(osfstorage_res['users']['enabled'], all_user_count)
assert_equal(wiki_res['users']['enabled'], all_user_count)
示例13: authenticate
def authenticate(self, request):
cookie_val = request.COOKIES.get(settings.COOKIE_NAME)
if not cookie_val:
return None
session = get_session_from_cookie(cookie_val)
if not session:
return None
user_id = session.data.get('auth_user_id')
user = User.load(user_id)
if user:
return user, None
return None
示例14: populate_conferences
def populate_conferences(dev=False):
if dev:
Conference.remove()
date_format = '%b %d %Y'
for meeting, attrs in MEETING_DATA.iteritems():
meeting = meeting.strip()
admin_emails = attrs.pop('admins', [])
admin_objs = []
if not dev:
for email in admin_emails:
try:
user = User.find_one(Q('username', 'iexact', email))
admin_objs.append(user)
except ModularOdmException:
raise RuntimeError('Username {0!r} is not registered.'.format(email))
# Convert string into datetime object
try:
attrs['end_date'] = datetime.strptime(attrs.get('end_date'), date_format)
attrs['start_date'] = datetime.strptime(attrs.get('start_date'), date_format)
except TypeError:
print '** Meeting {} does not have a start or end date. **'.format(meeting)
custom_fields = attrs.pop('field_names', {})
conf = Conference(
endpoint=meeting, admins=admin_objs, **attrs
)
conf.field_names.update(custom_fields)
try:
conf.save()
except ModularOdmException:
conf = Conference.find_one(Q('endpoint', 'eq', meeting))
for key, value in attrs.items():
if isinstance(value, dict):
current = getattr(conf, key)
current.update(value)
setattr(conf, key, current)
else:
setattr(conf, key, value)
conf.admins = admin_objs
changed_fields = conf.save()
if changed_fields:
print('Updated {}: {}'.format(meeting, changed_fields))
else:
print('Added new Conference: {}'.format(meeting))
示例15: get_or_create_user
def get_or_create_user(fullname, address, is_spam=False):
"""Get or create user by email address.
:param str fullname: User full name
:param str address: User email address
:param bool is_spam: User flagged as potential spam
:return: Tuple of (user, created)
"""
user = get_user(email=address)
if user:
return user, False
else:
password = str(uuid.uuid4())
user = User.create_confirmed(address, password, fullname)
user.verification_key = generate_verification_key()
if is_spam:
user.system_tags.append('is_spam')
return user, True