本文整理汇总了Python中two_factor.utils.default_device函数的典型用法代码示例。如果您正苦于以下问题:Python default_device函数的具体用法?Python default_device怎么用?Python default_device使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了default_device函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_default_device
def test_default_device(self):
user = self.create_user()
self.assertEqual(default_device(user), None)
user.phonedevice_set.create(name='backup', number='+1')
self.assertEqual(default_device(user), None)
default = user.phonedevice_set.create(name='default', number='+1')
self.assertEqual(default_device(user).pk, default.pk)
开发者ID:Parasail-Health,项目名称:django-two-factor-auth,代码行数:9,代码来源:tests.py
示例2: test_default_device
def test_default_device(self):
user = User.objects.create_user('bouke')
self.assertEqual(default_device(user), None)
user.phonedevice_set.create(name='backup')
self.assertEqual(default_device(user), None)
default = user.phonedevice_set.create(name='default')
self.assertEqual(default_device(user).pk, default.pk)
开发者ID:smarthall,项目名称:django-two-factor-auth,代码行数:9,代码来源:tests.py
示例3: test_default_device
def test_default_device(self):
user = self.create_user()
self.assertEqual(default_device(user), None)
PhoneDevice.objects.create(user=user, name='backup')
self.assertEqual(default_device(user), None)
default = PhoneDevice.objects.create(user=user, name='default')
self.assertEqual(default_device(user).pk, default.pk)
开发者ID:myfreecomm,项目名称:django-two-factor-auth,代码行数:9,代码来源:tests.py
示例4: login_user
def login_user(self, user=None):
if not user:
user = list(self._passwords.keys())[0]
username = user.get_username()
assert self.client.login(username=username, password=self._passwords[user])
if default_device(user):
session = self.client.session
session[DEVICE_ID_SESSION_KEY] = default_device(user).persistent_id
session.save()
开发者ID:Bouke,项目名称:django-two-factor-auth,代码行数:9,代码来源:utils.py
示例5: account
def account(request):
try:
backup_tokens = request.user.staticdevice_set.all()[0].token_set.count()
except Exception:
backup_tokens = 0
status = {
'default_device': default_device(request.user),
'default_device_type': default_device(request.user).__class__.__name__,
'backup_phones': backup_phones(request.user),
'backup_tokens': backup_tokens,
'site_user': request.user
}
return render_to_response('account.html', status, context_instance=RequestContext(request))
开发者ID:HanabiDev,项目名称:Ursus,代码行数:15,代码来源:views.py
示例6: wrapped
def wrapped(request, *args, **kwargs):
u = request.user
if (not hasattr(u, 'userprofile') or not hasattr(u.userprofile, 'teacher') or
(not u.is_verified() and default_device(u))):
return HttpResponseRedirect(reverse_lazy('teach'))
return view_func(request, *args, **kwargs)
开发者ID:javicg,项目名称:codeforlife-portal,代码行数:7,代码来源:permissions.py
示例7: profile
def profile(request):
# Get a list of the users API Keys
keys = ApiKey.objects.filter(user=request.user)
try:
backup_tokens = request.user.staticdevice_set.all()[0].token_set.count()
except IndexError:
backup_tokens = 0
# Get a list of the users current sessions
sessions = request.user.session_set.filter(expire_date__gt=now())
# Get the current session key
session_key = request.session.session_key
# Process the form if we have data coming in
if request.method == 'POST':
form = UserProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
form.save()
else:
form = UserProfileForm(instance=request.user.profile)
# Show the template
return render(request, 'account_profile.html', {
'keys': keys,
'sessions': sessions,
'session_key': session_key,
'form': form,
'user': request.user,
'default_device': default_device(request.user),
'backup_tokens': backup_tokens,
})
开发者ID:Dem0n3D,项目名称:RatticWeb,代码行数:32,代码来源:views.py
示例8: dispatch
def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated() or \
(not request.user.is_verified() and default_device(request.user)):
# If the user has not authenticated raise or redirect to the login
# page. Also if the user just enabled two-factor authentication and
# has not yet logged in since should also have the same result. If
# the user receives a 'you need to enable TFA' by now, he gets
# confuses as TFA has just been enabled. So we either raise or
# redirect to the login page.
if self.raise_anonymous:
raise PermissionDenied()
else:
return redirect('%s?%s' % (
self.get_login_url(),
urlencode({self.redirect_field_name: request.get_full_path()})
))
if not request.user.is_verified():
if self.raise_unverified:
raise PermissionDenied()
elif self.get_verification_url():
return redirect('%s?%s' % (
self.verification_url,
urlencode({self.redirect_field_name: request.get_full_path()})
))
else:
return TemplateResponse(
request=request,
template='two_factor/core/otp_required.html',
status=403,
)
return super(OTPRequiredMixin, self).dispatch(request, *args, **kwargs)
开发者ID:ghedsouza,项目名称:django-two-factor-auth,代码行数:32,代码来源:mixins.py
示例9: teacher_edit_account
def teacher_edit_account(request):
teacher = request.user.userprofile.teacher
backup_tokens = 0
# For teachers using 2FA, find out how many backup tokens they have
if default_device(request.user):
try:
backup_tokens = request.user.staticdevice_set.all()[0].token_set.count()
except Exception:
backup_tokens = 0
if request.method == "POST":
form = TeacherEditAccountForm(request.user, request.POST)
if form.is_valid():
data = form.cleaned_data
changing_email = False
# check not default value for CharField
if data["password"] != "":
teacher.user.user.set_password(data["password"])
teacher.user.user.save()
update_session_auth_hash(request, form.user)
teacher.title = data["title"]
teacher.user.user.first_name = data["first_name"]
teacher.user.user.last_name = data["last_name"]
new_email = data["email"]
if new_email != "" and new_email != teacher.user.user.email:
# new email to set and verify
changing_email = True
send_verification_email(request, teacher.user, new_email)
teacher.save()
teacher.user.user.save()
if changing_email:
logout(request)
messages.success(
request,
"Your account details have been successfully changed. Your email will be changed once you have verified it, until then you can still log in with your old email.",
)
return render(
request, "portal/email_verification_needed.html", {"userprofile": teacher.user, "email": new_email}
)
messages.success(request, "Your account details have been successfully changed.")
return HttpResponseRedirect(reverse_lazy("teacher_home"))
else:
form = TeacherEditAccountForm(
request.user,
initial={
"title": teacher.title,
"first_name": teacher.user.user.first_name,
"last_name": teacher.user.user.last_name,
"school": teacher.school,
},
)
return render(request, "portal/teach/teacher_edit_account.html", {"form": form, "backup_tokens": backup_tokens})
开发者ID:HackLinux,项目名称:codeforlife-portal,代码行数:60,代码来源:teach.py
示例10: two_form_authentication_warnings
def two_form_authentication_warnings(request, teacher):
# For teachers using 2FA, warn if they don't have any backup tokens set, and warn solo-admins to set up another admin
if default_device(request.user):
# check backup tokens
try:
backup_tokens = request.user.staticdevice_set.all()[0].token_set.count()
except Exception:
backup_tokens = 0
if not backup_tokens > 0:
link = reverse('two_factor:profile')
messages.warning(request,
'You do not have any backup tokens set up for two factor authentication, so could lose '
'access to your account if you have problems with your smartphone or tablet. '
'<a href="{link}">Set up backup tokens now</a>.'.format(link = link), extra_tags='safe')
# check admin
if teacher.is_admin:
admins = Teacher.objects.filter(school=teacher.school, is_admin=True)
manageSchoolLink = reverse('organisation_manage')
if len(admins) == 1:
messages.warning(request,
'You are the only administrator in your school and are using Two Factor Authentication '
'(2FA). We recommend you <a href="{manageSchoolLink}">set up another '
'administrator</a> who will be able to disable your 2FA should you have problems with '
'your smartphone or tablet.'.format(manageSchoolLink = manageSchoolLink),
extra_tags='safe')
开发者ID:javicg,项目名称:codeforlife-portal,代码行数:25,代码来源:home.py
示例11: login
def login(self, request, redirect_url=None):
# prevent admin users hijacking this login page to circumvent
# two factor authentication
if site_settings.ADMIN_ENABLED:
if default_device(self.user):
raise Http404
if request.limited:
return render(request, 'account/ratelimit_triggered.html', {})
return super(RatelimitedLoginForm, self).login(request, redirect_url)
开发者ID:Utsira,项目名称:movements,代码行数:10,代码来源:views.py
示例12: process_request
def process_request(self, request):
if settings.ADMIN_ENABLED:
allowed_urls = [reverse('admin:logout')]
requested_url = request.get_full_path()
two_factor_base = reverse('two_factor:profile')
if two_factor_base not in requested_url \
and requested_url not in allowed_urls \
and request.user and any([request.user.is_superuser, request.user.is_staff]) \
and not default_device(request.user):
return HttpResponseRedirect(reverse('two_factor:setup'))
开发者ID:Utsira,项目名称:movements,代码行数:10,代码来源:middleware.py
示例13: teacher_edit_account
def teacher_edit_account(request):
teacher = request.user.userprofile.teacher
backup_tokens = 0
# For teachers using 2FA, find out how many backup tokens they have
if default_device(request.user):
try:
backup_tokens = request.user.staticdevice_set.all()[0].token_set.count()
except Exception:
backup_tokens = 0
if request.method == 'POST':
form = TeacherEditAccountForm(request.user, request.POST)
if form.is_valid():
data = form.cleaned_data
changing_email=False
# check not default value for CharField
if (data['password'] != ''):
teacher.user.user.set_password(data['password'])
teacher.user.user.save()
update_session_auth_hash(request, form.user)
teacher.title = data['title']
teacher.user.user.first_name = data['first_name']
teacher.user.user.last_name = data['last_name']
new_email = data['email']
if new_email != '' and new_email != teacher.user.user.email:
# new email to set and verify
changing_email=True
send_verification_email(request, teacher.user, new_email)
teacher.save()
teacher.user.user.save()
if changing_email:
logout(request)
messages.success(request, 'Your account details have been successfully changed. Your email will be changed once you have verified it, until then you can still log in with your old email.')
return render(request, 'portal/email_verification_needed.html', { 'userprofile': teacher.user, 'email': new_email })
messages.success(request, 'Your account details have been successfully changed.')
return HttpResponseRedirect(reverse_lazy('teacher_home'))
else:
form = TeacherEditAccountForm(request.user, initial={
'title' : teacher.title,
'first_name': teacher.user.user.first_name,
'last_name': teacher.user.user.last_name,
'school': teacher.school,
})
return render(request, 'portal/teach/teacher_edit_account.html', { 'form': form, 'backup_tokens': backup_tokens })
开发者ID:javicg,项目名称:codeforlife-portal,代码行数:52,代码来源:teach.py
示例14: list
def list(self, request):
try:
token_set = request.user.staticdevice_set.first().token_set.all()
except AttributeError:
token_set = []
return Response({
'default': get_info_text_for_device(default_device(request.user)),
'backup_phone_numbers': [
{
'id': phone.pk,
'number': mask_phone_number(format_phone_number(phone.number)),
} for phone in backup_phones(request.user)
],
'backup_tokens': [token.token for token in token_set],
})
开发者ID:HelloLily,项目名称:hellolily,代码行数:16,代码来源:views.py
示例15: do_two_factor_login
def do_two_factor_login(request: HttpRequest, user_profile: UserProfile) -> None:
device = default_device(user_profile)
if device:
django_otp.login(request, device)
开发者ID:brainwane,项目名称:zulip,代码行数:4,代码来源:decorator.py
示例16: _using_two_factor
def _using_two_factor(user):
'''Returns whether the user is using 2fa or not.'''
return default_device(user)
开发者ID:eddarmitage,项目名称:codeforlife-portal,代码行数:3,代码来源:utils.py
示例17: aggregated_data
def aggregated_data(request):
tables = []
table_head = ["Data description", "Value", "More info"]
table_data = []
"""
Overall statistics
"""
table_data.append(
[
"Number of users",
Teacher.objects.count() + Student.objects.count(),
"Number of teachers + Number of students",
]
)
tables.append(
{
"title": "Overall Statistics",
"description": "CFL site overall statistics",
"header": table_head,
"data": table_data,
}
)
"""
School statistics
"""
table_data = []
table_data.append(["Number of schools signed up", School.objects.count(), ""])
num_of_teachers_per_school = School.objects.annotate(num_teachers=Count("teacher_school"))
stats_teachers_per_school = num_of_teachers_per_school.aggregate(Avg("num_teachers"))
table_data.append(["Average number of teachers per school", stats_teachers_per_school["num_teachers__avg"], ""])
tables.append({"title": "Schools or Clubs", "description": "", "header": table_head, "data": table_data})
"""
Teacher statistics
"""
table_data = []
table_data.append(["Number of teachers signed up", Teacher.objects.count(), ""])
table_data.append(["Number of teachers not in a school", Teacher.objects.filter(school=None).count(), ""])
table_data.append(
[
"Number of teachers with request pending to join a school",
Teacher.objects.exclude(pending_join_request=None).count(),
"",
]
)
table_data.append(
[
"Number of teachers with unverified email address",
Teacher.objects.filter(user__awaiting_email_verification=True).count(),
"",
]
)
teachers = Teacher.objects.all()
two_factor_teachers = 0
for teacher in teachers:
if default_device(teacher.user.user):
two_factor_teachers += 1
table_data.append(["Number of teachers setup with 2FA", two_factor_teachers, ""])
num_of_classes_per_teacher = Teacher.objects.annotate(num_classes=Count("class_teacher"))
stats_classes_per_teacher = num_of_classes_per_teacher.aggregate(Avg("num_classes"))
num_of_classes_per_active_teacher = num_of_classes_per_teacher.exclude(school=None)
stats_classes_per_active_teacher = num_of_classes_per_active_teacher.aggregate(Avg("num_classes"))
table_data.append(["Average number of classes per teacher", stats_classes_per_teacher["num_classes__avg"], ""])
table_data.append(
[
"Average number of classes per active teacher",
stats_classes_per_active_teacher["num_classes__avg"],
"Excludes teachers without a school",
]
)
table_data.append(
["Number of of teachers with no classes", num_of_classes_per_teacher.filter(num_classes=0).count(), ""]
)
table_data.append(
[
"Number of of active teachers with no classes",
num_of_classes_per_active_teacher.filter(num_classes=0).count(),
"Excludes teachers without a school",
]
)
tables.append({"title": "Teachers", "description": "", "header": table_head, "data": table_data})
"""
Class statistics
"""
table_data = []
table_data.append(["Number of classes", Class.objects.count(), ""])
num_students_per_class = Class.objects.annotate(num_students=Count("students"))
stats_students_per_class = num_students_per_class.aggregate(Avg("num_students"))
#.........这里部分代码省略.........
开发者ID:HackLinux,项目名称:codeforlife-portal,代码行数:101,代码来源:admin.py
示例18: home_real
#.........这里部分代码省略.........
debug_mode = settings.DEBUG,
test_suite = settings.TEST_SUITE,
poll_timeout = settings.POLL_TIMEOUT,
login_page = settings.HOME_NOT_LOGGED_IN,
root_domain_uri = settings.ROOT_DOMAIN_URI,
maxfilesize = settings.MAX_FILE_UPLOAD_SIZE,
max_avatar_file_size = settings.MAX_AVATAR_FILE_SIZE,
server_generation = settings.SERVER_GENERATION,
use_websockets = settings.USE_WEBSOCKETS,
save_stacktraces = settings.SAVE_FRONTEND_STACKTRACES,
warn_no_email = settings.WARN_NO_EMAIL,
server_inline_image_preview = settings.INLINE_IMAGE_PREVIEW,
server_inline_url_embed_preview = settings.INLINE_URL_EMBED_PREVIEW,
password_min_length = settings.PASSWORD_MIN_LENGTH,
password_min_guesses = settings.PASSWORD_MIN_GUESSES,
jitsi_server_url = settings.JITSI_SERVER_URL,
search_pills_enabled = settings.SEARCH_PILLS_ENABLED,
# Misc. extra data.
have_initial_messages = user_has_messages,
initial_servertime = time.time(), # Used for calculating relative presence age
default_language_name = get_language_name(register_ret['default_language']),
language_list_dbl_col = get_language_list_for_templates(register_ret['default_language']),
language_list = get_language_list(),
needs_tutorial = needs_tutorial,
first_in_realm = first_in_realm,
prompt_for_invites = prompt_for_invites,
furthest_read_time = sent_time_in_epoch_seconds(latest_read),
has_mobile_devices = num_push_devices_for_user(user_profile) > 0,
bot_types = get_bot_types(user_profile),
two_fa_enabled = two_fa_enabled,
# Adding two_fa_enabled as condition saves us 3 queries when
# 2FA is not enabled.
two_fa_enabled_user = two_fa_enabled and bool(default_device(user_profile)),
)
undesired_register_ret_fields = [
'streams',
]
for field_name in set(register_ret.keys()) - set(undesired_register_ret_fields):
page_params[field_name] = register_ret[field_name]
if narrow_stream is not None:
# In narrow_stream context, initial pointer is just latest message
recipient = get_stream_recipient(narrow_stream.id)
try:
initial_pointer = Message.objects.filter(recipient=recipient).order_by('id').reverse()[0].id
except IndexError:
initial_pointer = -1
page_params["narrow_stream"] = narrow_stream.name
if narrow_topic is not None:
page_params["narrow_topic"] = narrow_topic
page_params["narrow"] = [dict(operator=term[0], operand=term[1]) for term in narrow]
page_params["max_message_id"] = initial_pointer
page_params["pointer"] = initial_pointer
page_params["have_initial_messages"] = (initial_pointer != -1)
page_params["enable_desktop_notifications"] = False
statsd.incr('views.home')
show_invites = True
# Some realms only allow admins to invite users
if user_profile.realm.invite_by_admins_only and not user_profile.is_realm_admin:
show_invites = False
if user_profile.is_guest:
show_invites = False
开发者ID:akashnimare,项目名称:zulip,代码行数:67,代码来源:home.py
示例19: get
def get(self, request, *args, **kwargs):
default_device(request.user).delete()
return super(TwoFactorResetView, self).get(request, *args, **kwargs)
开发者ID:dimagi,项目名称:commcare-hq,代码行数:3,代码来源:views.py
示例20: has_2FA
def has_2FA(u):
return default_device(u)
开发者ID:javicg,项目名称:codeforlife-portal,代码行数:2,代码来源:app_tags.py
注:本文中的two_factor.utils.default_device函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论