Python django.conf.settings.AUTHENTICATION_BACKENDS Examples

The following are 30 code examples of django.conf.settings.AUTHENTICATION_BACKENDS(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .
Example #1
Source File: panel.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #2
Source File: decorators.py    From steemprojects.com with MIT License 6 votes vote down vote up
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 
Example #3
Source File: api.py    From canvas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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,
    } 
Example #4
Source File: models.py    From diting with GNU General Public License v2.0 6 votes vote down vote up
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,
            ) 
Example #5
Source File: middleware.py    From govready-q with GNU General Public License v3.0 6 votes vote down vote up
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. 
Example #6
Source File: functionaltest.py    From dirigible-spreadsheet with MIT License 6 votes vote down vote up
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 
Example #7
Source File: auth.py    From zulip with Apache License 2.0 6 votes vote down vote up
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) 
Example #8
Source File: views.py    From starthinker with Apache License 2.0 6 votes vote down vote up
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('/') 
Example #9
Source File: tests.py    From starthinker with Apache License 2.0 6 votes vote down vote up
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()) 
Example #10
Source File: views.py    From YaraGuardian with Apache License 2.0 5 votes vote down vote up
def social_login_enabled(self):
        supported_backends = ['social_core.backends.google.GoogleOAuth2']
        available_backends = set(settings.AUTHENTICATION_BACKENDS) & set(supported_backends)

        if available_backends:
            return True
        else:
            return False 
Example #11
Source File: perftest.py    From casepro with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def force_login(self, user, backend=None):
        if backend is None:
            backend = settings.AUTHENTICATION_BACKENDS[0]
        user.backend = backend
        self._login(user) 
Example #12
Source File: __init__.py    From kpi with GNU Affero General Public License v3.0 5 votes vote down vote up
def one_time_login(request):
    """
    If the request provides a key that matches a OneTimeAuthenticationKey
    object, log in the User specified in that object and redirect to the
    location specified in the 'next' parameter
    """
    try:
        key = request.POST['key']
    except KeyError:
        return HttpResponseBadRequest(_('No key provided'))
    try:
        next_ = request.GET['next']
    except KeyError:
        next_ = None
    if not next_ or not is_safe_url(url=next_, host=request.get_host()):
        next_ = resolve_url(settings.LOGIN_REDIRECT_URL)
    # Clean out all expired keys, just to keep the database tidier
    OneTimeAuthenticationKey.objects.filter(
        expiry__lt=datetime.datetime.now()).delete()
    with transaction.atomic():
        try:
            otak = OneTimeAuthenticationKey.objects.get(
                key=key,
                expiry__gte=datetime.datetime.now()
            )
        except OneTimeAuthenticationKey.DoesNotExist:
            return HttpResponseBadRequest(_('Invalid or expired key'))
        # Nevermore
        otak.delete()
    # The request included a valid one-time key. Log in the associated user
    user = otak.user
    user.backend = settings.AUTHENTICATION_BACKENDS[0]
    login(request, user)
    return HttpResponseRedirect(next_)


# TODO Verify if it's still used 
Example #13
Source File: client.py    From python2017 with MIT License 5 votes vote down vote up
def force_login(self, user, backend=None):
        def get_backend():
            from django.contrib.auth import load_backend
            for backend_path in settings.AUTHENTICATION_BACKENDS:
                backend = load_backend(backend_path)
                if hasattr(backend, 'get_user'):
                    return backend_path
        if backend is None:
            backend = get_backend()
        user.backend = backend
        self._login(user, backend) 
Example #14
Source File: checks.py    From python2017 with MIT License 5 votes vote down vote up
def check_dependencies(**kwargs):
    """
    Check that the admin's dependencies are correctly installed.
    """
    errors = []
    # contrib.contenttypes must be installed.
    if not apps.is_installed('django.contrib.contenttypes'):
        missing_app = checks.Error(
            "'django.contrib.contenttypes' must be in INSTALLED_APPS in order "
            "to use the admin application.",
            id="admin.E401",
        )
        errors.append(missing_app)
    # The auth context processor must be installed if using the default
    # authentication backend.
    try:
        default_template_engine = Engine.get_default()
    except Exception:
        # Skip this non-critical check:
        # 1. if the user has a non-trivial TEMPLATES setting and Django
        #    can't find a default template engine
        # 2. if anything goes wrong while loading template engines, in
        #    order to avoid raising an exception from a confusing location
        # Catching ImproperlyConfigured suffices for 1. but 2. requires
        # catching all exceptions.
        pass
    else:
        if ('django.contrib.auth.context_processors.auth'
                not in default_template_engine.context_processors and
                'django.contrib.auth.backends.ModelBackend' in settings.AUTHENTICATION_BACKENDS):
            missing_template = checks.Error(
                "'django.contrib.auth.context_processors.auth' must be in "
                "TEMPLATES in order to use the admin application.",
                id="admin.E402"
            )
            errors.append(missing_template)
    return errors 
Example #15
Source File: __init__.py    From python2017 with MIT License 5 votes vote down vote up
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 
Example #16
Source File: __init__.py    From python2017 with MIT License 5 votes vote down vote up
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 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() 
Example #17
Source File: test_base.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def client_post_login(self):
        self.user = User.objects.create_user(
            username=self.username, password=self.password
        )

        url = reverse("login")

        if (
            "callisto_core.accounts.auth.EncryptedBackend"
            in settings.AUTHENTICATION_BACKENDS
        ):
            from hashlib import sha256
            import bcrypt
            from callisto_core.accounts.auth import index

            userhash = sha256(self.username.lower().encode("utf-8")).hexdigest()
            usercrypt = bcrypt.hashpw(userhash.encode("utf-8"), bcrypt.gensalt())
            userindex = index(userhash)

            self.userhash = userhash

            Account.objects.create(
                user=self.user,
                site_id=1,
                encrypted_username=usercrypt.decode(),
                username_index=userindex,
            )

            data = {"username": self.userhash, "password": self.password}
        else:
            data = {"username": self.username, "password": self.password}
            Account.objects.create(user=self.user, site_id=1)
        response = self.client.post(url, data, follow=True)
        self.assertIn(response.status_code, self.valid_statuses)
        return response 
Example #18
Source File: test_base.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def _setup_user(self):
        username = "testing_122"
        self.user = User.objects.create_user(username=username, password="testing_12")

        if (
            "callisto_core.accounts.auth.EncryptedBackend"
            in settings.AUTHENTICATION_BACKENDS
        ):
            from hashlib import sha256
            import bcrypt
            from callisto_core.accounts.auth import index

            userhash = sha256(username.lower().encode("utf-8")).hexdigest()
            usercrypt = bcrypt.hashpw(userhash.encode("utf-8"), bcrypt.gensalt())
            userindex = index(userhash)

            Account.objects.create(
                user=self.user,
                site_id=1,
                school_email=self.school_email,
                encrypted_username=usercrypt.decode(),
                username_index=userindex,
            )
            self.client.login(username=userhash, password="testing_12")
            self.userhash = userhash
        else:
            Account.objects.create(
                user=self.user, site_id=1, school_email=self.school_email
            )
            self.client.login(username=username, password="testing_12") 
Example #19
Source File: views.py    From django-u2f with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_user(self):
        try:
            user_id = self.request.session['u2f_pre_verify_user_pk']
            backend_path = self.request.session['u2f_pre_verify_user_backend']
            assert backend_path in settings.AUTHENTICATION_BACKENDS
            backend = load_backend(backend_path)
            user = backend.get_user(user_id)
            if user is not None:
                user.backend = backend_path
            return user
        except (KeyError, AssertionError):
            return None 
Example #20
Source File: auth.py    From django-pgschemas with MIT License 5 votes vote down vote up
def get_user(scope):
    """
    Return the user model instance associated with the given scope.
    If no user is retrieved, return an instance of `AnonymousUser`.
    """
    if "session" not in scope:
        raise ValueError("Cannot find session in scope. You should wrap your consumer in SessionMiddleware.")
    user = None
    session = scope["session"]
    with scope["tenant"]:
        try:
            user_id = _get_user_session_key(session)
            backend_path = 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 hasattr(user, "get_session_auth_hash"):
                    session_hash = 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:
                        session.flush()
                        user = None
    return user or AnonymousUser() 
Example #21
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
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() 
Example #22
Source File: signals_handler.py    From diting with GNU General Public License v2.0 5 votes vote down vote up
def ldap_auth_on_changed(sender, enabled=True, **kwargs):
    if enabled:
        logger.debug("Enable LDAP auth")
        if settings.AUTH_LDAP_BACKEND not in settings.AUTH_LDAP_BACKEND:
            settings.AUTHENTICATION_BACKENDS.insert(0, settings.AUTH_LDAP_BACKEND)

    else:
        logger.debug("Disable LDAP auth")
        if settings.AUTH_LDAP_BACKEND in settings.AUTHENTICATION_BACKENDS:
            settings.AUTHENTICATION_BACKENDS.remove(settings.AUTH_LDAP_BACKEND) 
Example #23
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
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() 
Example #24
Source File: views.py    From django-mfa with MIT License 5 votes vote down vote up
def get_user(self):
        try:
            user_id = self.request.session['u2f_pre_verify_user_pk']
            backend_path = self.request.session['u2f_pre_verify_user_backend']
            self.request.session['verfied_u2f'] = False
            assert backend_path in settings.AUTHENTICATION_BACKENDS
            backend = load_backend(backend_path)
            user = backend.get_user(user_id)
            if user is not None:
                user.backend = backend_path
            return user
        except (KeyError, AssertionError):
            return None 
Example #25
Source File: views.py    From django-user-management with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        auto_login = getattr(settings, 'LOGIN_ON_EMAIL_VERIFICATION', False)

        if not self.already_verified:
            self.activate_user()
            if auto_login is True:
                self.user.backend = settings.AUTHENTICATION_BACKENDS[0]
                auth.login(request=request, user=self.user)
        messages.success(request, self.success_message)
        return super(VerifyUserEmailView, self).get(request, *args, **kwargs) 
Example #26
Source File: middleware.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def process_request(self, request):
        if settings.AUTHENTICATION_BACKENDS:
            auth_backend = settings.AUTHENTICATION_BACKENDS[0]

            if request.session.get(self.BACKEND_KEY, auth_backend) != auth_backend:
                request.session['_old_auth_user_backend'] = request.session[self.BACKEND_KEY]
                request.session[self.BACKEND_KEY] = auth_backend

 
# http://djangosnippets.org/snippets/1720/ 
Example #27
Source File: models.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def migrate_canvas_user(cls, request, canvas_username, canvas_password, email=None):
        """
        Will error out if the password isn't correct, with an (empty) ValidationError.

        `email` will override whatever email the example.com account had.

        May also raise an IntegrityError if the user already exists in drawquest.

        Returns the new `User` instance.
        """
        canvas_user = User.canvas_account_info(canvas_username)

        if email is None:
            email = canvas_user['email']
        elif not User.validate_email(email):
            raise ValidationError("Please enter a valid email address.")

        user = User.objects.create_user(canvas_username, email, canvas_password)

        # this is a total hack because we don't care to write a backend for this authenticate method
        user.backend = settings.AUTHENTICATION_BACKENDS[0]

        if User.check_canvas_account_password(canvas_username, canvas_password):
            avatar = None

            if canvas_user.get('profile_image_url'):
                avatar = User.upload_avatar_from_url(request, canvas_user['profile_image_url'])

            UserInfo.objects.create(user=user, bio_text=canvas_user['bio'], avatar=avatar)
        else:
            user.delete()
            raise ValidationError("Wrong password for Canvas account.")

        return user 
Example #28
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
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 
Example #29
Source File: views.py    From steemprojects.com with MIT License 5 votes vote down vote up
def get_context_data(self, **kwargs):
        context = super(ProfileEditUpdateView, self).get_context_data(**kwargs)
        # context['available_backends'] = load_backends()

        context.update(common_context(
            authentication_backends=settings.AUTHENTICATION_BACKENDS,
            user=self.request.user
        ))

        context['memberships'] = TeamMembership.objects.filter(account__in=self.request.user.profile.account_set.all())

        return context 
Example #30
Source File: checks.py    From django-rest-registration with MIT License 5 votes vote down vote up
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__
    )