本文整理匯總了Python中django.conf.settings.AUTHENTICATION_BACKENDS屬性的典型用法代碼示例。如果您正苦於以下問題:Python settings.AUTHENTICATION_BACKENDS屬性的具體用法?Python settings.AUTHENTICATION_BACKENDS怎麽用?Python settings.AUTHENTICATION_BACKENDS使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類django.conf.settings
的用法示例。
在下文中一共展示了settings.AUTHENTICATION_BACKENDS屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: settings_info
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import AUTHENTICATION_BACKENDS [as 別名]
def settings_info():
info = []
info.append(('Deploy mode', settings.DEPLOY_MODE))
info.append(('Database engine', settings.DATABASES['default']['ENGINE']))
info.append(('Authentication Backends', settings.AUTHENTICATION_BACKENDS))
info.append(('Cache backend', settings.CACHES['default']['BACKEND']))
info.append(('Haystack engine', settings.HAYSTACK_CONNECTIONS['default']['ENGINE']))
info.append(('Email backend', settings.EMAIL_BACKEND))
if hasattr(settings, 'CELERY_EMAIL') and settings.CELERY_EMAIL:
info.append(('Celery email backend', settings.CELERY_EMAIL_BACKEND))
if hasattr(settings, 'CELERY_BROKER_URL'):
info.append(('Celery broker', settings.CELERY_BROKER_URL.split(':')[0]))
DATABASES = copy.deepcopy(settings.DATABASES)
for d in DATABASES:
if 'PASSWORD' in DATABASES[d]:
DATABASES[d]['PASSWORD'] = '*****'
info.append(('DATABASES', mark_safe('<pre>'+escape(pprint.pformat(DATABASES))+'</pre>')))
return info
示例2: test_ui_project
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import AUTHENTICATION_BACKENDS [as 別名]
def test_ui_project(self):
# not logged in ( blank )
resp = self.client.get('/project/')
self.assertEqual(resp.status_code, 200)
self.client.force_login(self.account, backend=settings.AUTHENTICATION_BACKENDS[0])
# logged in
resp = self.client.get('/project/')
self.assertEqual(resp.status_code, 200)
self.assertContains(resp, self.project_user.identifier)
self.assertContains(resp, self.project_domain.identifier)
self.assertContains(resp, self.project_global.identifier)
self.assertContains(resp, self.project_domain.share.upper())
self.assertContains(resp, self.project_global.share.upper())
示例3: oauth_callback
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import AUTHENTICATION_BACKENDS [as 別名]
def oauth_callback(request):
# get the credentials from the Google redirect
flow = CredentialsFlowWrapper(settings.UI_CLIENT, redirect_uri=settings.CONST_URL + '/oauth_callback/')
flow.code_verifier = request.session.get('code_verifier')
flow.fetch_token(code=request.GET['code'])
# get or create the account
account = Account.objects.get_or_create_user(flow.credentials)
# log the account in ( set cookie )
django_login(request, account, backend=settings.AUTHENTICATION_BACKENDS[0])
messages.success(request, 'Welcome To StarThinker')
return HttpResponseRedirect('/')
示例4: dev_direct_login
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import AUTHENTICATION_BACKENDS [as 別名]
def dev_direct_login(
request: HttpRequest,
next: str = REQ(default="/"),
) -> HttpResponse:
# This function allows logging in without a password and should only be called
# in development environments. It may be called if the DevAuthBackend is included
# in settings.AUTHENTICATION_BACKENDS
if (not dev_auth_enabled()) or settings.PRODUCTION:
# This check is probably not required, since authenticate would fail without
# an enabled DevAuthBackend.
return redirect_to_config_error('dev')
email = request.POST['direct_email']
subdomain = get_subdomain(request)
realm = get_realm(subdomain)
user_profile = authenticate(dev_auth_username=email, realm=realm)
if user_profile is None:
return redirect_to_config_error('dev')
do_login(request, user_profile)
redirect_to = get_safe_redirect_to(next, user_profile.realm.uri)
return HttpResponseRedirect(redirect_to)
示例5: create_users
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import AUTHENTICATION_BACKENDS [as 別名]
def create_users(self):
for username in self.get_my_usernames():
user = User.objects.create(username=username)
user.set_password('p4ssw0rd')
user.save()
profile = user.get_profile()
profile.has_seen_sheet_page = True
profile.save()
# create sessions we can use for login too
session = SessionStore()
session[SESSION_KEY] = user.pk
session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0]
session[HASH_SESSION_KEY] = user.get_session_auth_hash()
session.save()
self.session_keys[username] = session.session_key
示例6: QTemplateContextProcessor
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import AUTHENTICATION_BACKENDS [as 別名]
def QTemplateContextProcessor(request):
return {
"APP_VERSION_STRING": settings.APP_VERSION_STRING,
"APP_VERSION_COMMIT": settings.APP_VERSION_COMMIT,
"MOUSE_CURSOR_FOLLOWER": getattr(settings, 'MOUSE_CURSOR_FOLLOWER', False),
"LOGIN_ENABLED": ('django.contrib.auth.backends.ModelBackend' in settings.AUTHENTICATION_BACKENDS),
}
# The authentication backend below is used when Q is behind an enterprise proxy server
# handling authentication. The proxy server passes the username and email address of
# the authenticated user in the environment (via HTTP headers or other variables). When
# specifying HTTP headers, be sure to prepend "HTTP_" (e.g., HTTP_IAM-Username). Do not
# prepend anything if it's in the environment (e.g., ICAM_DISPLAYNAME).
# Email address handling: We update the user's email address with the one passed
# in the header whenever we come here. But this only occurs when the user is logging in.
# It seems like if the user has an active Django session and the username in the header
# matches the user in the session then the session is kept and ProxyHeaderUserAuthenticationBackend
# is not called.
示例7: refresh_setting
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import AUTHENTICATION_BACKENDS [as 別名]
def refresh_setting(self):
try:
value = json.loads(self.value)
except json.JSONDecodeError:
return
setattr(settings, self.name, value)
if self.name == "AUTH_LDAP":
if self.cleaned_value and settings.AUTH_LDAP_BACKEND not in settings.AUTHENTICATION_BACKENDS:
settings.AUTHENTICATION_BACKENDS.insert(0, settings.AUTH_LDAP_BACKEND)
elif not self.cleaned_value and settings.AUTH_LDAP_BACKEND in settings.AUTHENTICATION_BACKENDS:
settings.AUTHENTICATION_BACKENDS.remove(settings.AUTH_LDAP_BACKEND)
if self.name == "AUTH_LDAP_SEARCH_FILTER":
settings.AUTH_LDAP_USER_SEARCH = LDAPSearch(
settings.AUTH_LDAP_SEARCH_OU, ldap.SCOPE_SUBTREE,
settings.AUTH_LDAP_SEARCH_FILTER,
)
示例8: login_with_facebook
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import AUTHENTICATION_BACKENDS [as 別名]
def login_with_facebook(request, facebook_access_token):
try:
fb_user = FacebookUser.get_from_access_token(facebook_access_token)
except FacebookUser.DoesNotExist:
raise PermissionDenied("No DrawQuest user exists for this Facebook account.")
user = fb_user.user
if not user.is_active:
return inactive_user_http_response()
# this is a total hack because we don't care to write a backend for the above authenticate method
user.backend = settings.AUTHENTICATION_BACKENDS[0]
auth.login(request, user)
return {
'user': PrivateUserDetails.from_id(user.id).to_client(),
'user_bio': user.userinfo.bio_text,
'user_subscribed_to_starred': is_subscribed(user, 'starred'),
'sessionid': request.session.session_key,
}
示例9: render_to
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import AUTHENTICATION_BACKENDS [as 別名]
def render_to(template):
"""Simple render_to decorator"""
def decorator(func):
"""Decorator"""
@wraps(func)
def wrapper(request, *args, **kwargs):
"""Rendering method"""
out = func(request, *args, **kwargs) or {}
if isinstance(out, dict):
out = render(request, template, common_context(
settings.AUTHENTICATION_BACKENDS,
request.user,
plus_id=getattr(settings, 'SOCIAL_AUTH_GOOGLE_PLUS_KEY', None),
**out
))
return out
return wrapper
return decorator
示例10: drf_compatible_django_auth_backend_check
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import AUTHENTICATION_BACKENDS [as 別名]
def drf_compatible_django_auth_backend_check() -> bool:
return all(
incompat_cls_name not in settings.AUTHENTICATION_BACKENDS
for incompat_cls_name in __DRF_INCOMPATIBLE_DJANGO_AUTH_BACKENDS__
)
示例11: _get_backends
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import AUTHENTICATION_BACKENDS [as 別名]
def _get_backends(return_tuples=False):
backends = []
for backend_path in settings.AUTHENTICATION_BACKENDS:
backend = load_backend(backend_path)
backends.append((backend, backend_path) if return_tuples else backend)
if not backends:
raise ImproperlyConfigured(
'No authentication backends have been defined. Does '
'AUTHENTICATION_BACKENDS contain anything?'
)
return backends
示例12: get_user
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import AUTHENTICATION_BACKENDS [as 別名]
def get_user(request):
"""
Returns the user model instance associated with the given request session.
If no user is retrieved an instance of `AnonymousUser` is returned.
"""
from .models import AnonymousUser
user = None
try:
user_id = _get_user_session_key(request)
backend_path = request.session[BACKEND_SESSION_KEY]
except KeyError:
pass
else:
if backend_path in settings.AUTHENTICATION_BACKENDS:
backend = load_backend(backend_path)
user = backend.get_user(user_id)
# Verify the session
if ('django.contrib.auth.middleware.SessionAuthenticationMiddleware'
in settings.MIDDLEWARE_CLASSES and hasattr(user, 'get_session_auth_hash')):
session_hash = request.session.get(HASH_SESSION_KEY)
session_hash_verified = session_hash and constant_time_compare(
session_hash,
user.get_session_auth_hash()
)
if not session_hash_verified:
request.session.flush()
user = None
return user or AnonymousUser()
示例13: test_login_authenticate_and_create_user
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import AUTHENTICATION_BACKENDS [as 別名]
def test_login_authenticate_and_create_user(monkeypatch, django_user_model, settings):
"""
Test the case where the login view authenticates a new user.
"""
# No need to test the message framework
settings.CAS_LOGIN_MSG = None
# Make sure we use our backend
settings.AUTHENTICATION_BACKENDS = ['django_cas_ng.backends.CASBackend']
# Json serializer was havinga hard time
settings.SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
def mock_verify(ticket, service):
return 'test@example.com', {'ticket': ticket, 'service': service}, None
monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)
factory = RequestFactory()
request = factory.get('/login/', {'ticket': 'fake-ticket',
'service': 'fake-service'})
# Create a session object from the middleware
process_request_for_middleware(request, SessionMiddleware)
# Create a user object from middleware
process_request_for_middleware(request, AuthenticationMiddleware)
response = LoginView().get(request)
assert response.status_code == 302
assert response['Location'] == '/'
assert django_user_model.objects.get(username='test@example.com').is_authenticated is True
示例14: test_login_authenticate_do_not_create_user
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import AUTHENTICATION_BACKENDS [as 別名]
def test_login_authenticate_do_not_create_user(monkeypatch, django_user_model, settings):
"""
Test the case where the login view authenticates a user, but does not
create a user based on the CAS_CREATE_USER setting.
"""
# No need to test the message framework
settings.CAS_CREATE_USER = False
# No need to test the message framework
settings.CAS_LOGIN_MSG = None
# Make sure we use our backend
settings.AUTHENTICATION_BACKENDS = ['django_cas_ng.backends.CASBackend']
# Json serializer was havinga hard time
settings.SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
def mock_verify(ticket, service):
return 'test@example.com', {'ticket': ticket, 'service': service}, None
monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)
factory = RequestFactory()
request = factory.get('/login/', {'ticket': 'fake-ticket',
'service': 'fake-service'})
# Create a session object from the middleware
process_request_for_middleware(request, SessionMiddleware)
# Create a user object from middleware
process_request_for_middleware(request, AuthenticationMiddleware)
with pytest.raises(PermissionDenied):
LoginView().get(request)
assert django_user_model.objects.filter(username='test@example.com').exists() is False
示例15: test_login_proxy_callback
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import AUTHENTICATION_BACKENDS [as 別名]
def test_login_proxy_callback(monkeypatch, django_user_model, settings):
"""
Test the case where the login view has a pgtiou.
"""
# No need to test the message framework
settings.CAS_PROXY_CALLBACK = True
# No need to test the message framework
settings.CAS_LOGIN_MSG = None
# Make sure we use our backend
settings.AUTHENTICATION_BACKENDS = ['django_cas_ng.backends.CASBackend']
# Json serializer was havinga hard time
settings.SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
def mock_verify(ticket, service):
return 'test@example.com', {'ticket': ticket, 'service': service}, None
monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)
factory = RequestFactory()
request = factory.get('/login/', {'ticket': 'fake-ticket',
'service': 'fake-service'})
# Create a session object from the middleware
process_request_for_middleware(request, SessionMiddleware)
# Create a user object from middleware
process_request_for_middleware(request, AuthenticationMiddleware)
request.session['pgtiou'] = 'fake-pgtiou'
request.session.save()
user = django_user_model.objects.create_user('test@example.com', '')
assert user is not None
pgt = ProxyGrantingTicket.objects.create(session_key=request.session.session_key,
user=user, pgtiou='fake-pgtiou',
pgt='fake-pgt')
assert pgt is not None
response = LoginView().get(request)
assert response.status_code == 302
assert django_user_model.objects.get(username='test@example.com').is_authenticated is True
assert ProxyGrantingTicket.objects.filter(pgtiou='fake-pgtiou').exists() is True
assert ProxyGrantingTicket.objects.filter(pgtiou='fake-pgtiou').count() == 1