Check credentials against the RADIUS server identified by `realm` and
        return a User object or None. If no argument is supplied, Django will
        skip this backend and try the next one (as a TypeError will be raised
        and caught).
7655
def authenticate(self, request, username=None, password=None, realm=None):
        
        if isinstance(username, basestring):
            username = username.encode('utf-8')

        if isinstance(password, basestring):
            password = password.encode('utf-8')

        server = self.get_server(realm)

        if not server:
            return None

        result = self._radius_auth(server, username, password)

        if result:
            full_username = self.construct_full_username(username, realm)
            return self.get_django_user(full_username, password)

        return None
743951
def get_user(request):
    
    if settings.LOCKDOWN and hasattr(request, 'user'):
        if request.user.is_authenticated:
            user = request.user.username
        else:
            # This may happen with crafted requests
            user = ''
    else:
        user = getattr(settings, 'DEFAULT_USER', getpass.getuser())

    return user
18152
def before_request(self) -> Optional[Response]:
        """"""
        auth = request.authorization
        if not auth or not self._check_auth(auth.username, auth.password):
            return Response(
                'Could not verify your access level for that URL.\n'
                'You have to login with proper credentials', 401,
                {'WWW-Authenticate': 'Basic realm="Login Required"'}
            )
        session['logged_in'] = auth.username
        # pylint wants this return statement
        return None
1348152
def handle_exception(self, exc):
        """"""
        if isinstance(
            exc, (rest_exceptions.NotAuthenticated,
                  rest_exceptions.AuthenticationFailed)) and self.HANDLE_UNAUTHENTICATED:
            return HttpResponseRedirect('{}?next={}'.format(
                reverse('users:login'),
                self.request.get_full_path()))

        if isinstance(exc, Http404):
            raise Http404()

        if isinstance(exc, rest_exceptions.PermissionDenied):
            raise django_exceptions.PermissionDenied()

        return super().handle_exception(exc)
987965
def try_storage(self, identifier, req, resp, resource, uri_kwargs):
        
        if identifier is None:
            user = None

        # note: if user_storage is defined, always use it in order to
        #       authenticate user.
        elif self.user_storage is not None:
            user = self.user_storage.get_user(
                self, identifier, req, resp, resource, uri_kwargs
            )

        # note: some authentication middleware classes may not require
        #       to be initialized with their own user_storage. In such
        #       case this will always authenticate with "syntetic user"
        #       if there is a valid indentity.
        elif self.user_storage is None and not self.only_with_storage:
            user = {
                'identified_with': self,
                'identifier': identifier
            }

        else:  # pragma: nocover
            # note: this should not happen if the base class is properly
            #       initialized. Still, user can skip super().__init__() call.
            user = None

        return user
171608
def get(self, server):
        
        if not isinstance(server, six.binary_type):
            server = server.encode('utf-8')
        data = self._execute('get', server)
        result = json.loads(data.decode('utf-8'))

        # docker-credential-pass will return an object for inexistent servers
        # whereas other helpers will exit with returncode != 0. For
        # consistency, if no significant data is returned,
        # raise CredentialsNotFound
        if result['Username'] == '' and result['Secret'] == '':
            raise errors.CredentialsNotFound(
                'No matching credentials in {}'.format(self.program)
            )

        return result
1053756
def authenticated(self, environ, username=None, password=None, **params):
        ''''''
        if username != self.username:
            return False
        o = self.options
        qop = o.get('qop')
        method = environ['REQUEST_METHOD']
        uri = environ.get('PATH_INFO', '')
        ha1 = self.ha1(o['realm'], password)
        ha2 = self.ha2(qop, method, uri)
        if qop is None:
            response = hexmd5(":".join((ha1, self.nonce, ha2)))
        elif qop == 'auth' or qop == 'auth-int':
            response = hexmd5(":".join((ha1, o['nonce'], o['nc'],
                                        o['cnonce'], qop, ha2)))
        else:
            raise ValueError("qop value are wrong")
        return o['response'] == response
1107536
def http_auth_required(realm):
    """"""

    def decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            if _check_http_auth():
                return fn(*args, **kwargs)
            if _security._unauthorized_callback:
                return _security._unauthorized_callback()
            else:
                r = _security.default_http_auth_realm \
                    if callable(realm) else realm
                h = {'WWW-Authenticate': 'Basic realm="%s"' % r}
                return _get_unauthorized_response(headers=h)
        return wrapper

    if callable(realm):
        return decorator(realm)
    return decorator
136717
def login_required(function=None, required=False, redirect_field_name=REDIRECT_FIELD_NAME):
    
    if required:
        if django.VERSION < (1, 11):
            actual_decorator = user_passes_test(
                lambda u: u.is_authenticated(),
                redirect_field_name=redirect_field_name
            )
        else:
            actual_decorator = user_passes_test(
                lambda u: u.is_authenticated,
                redirect_field_name=redirect_field_name
            )
        if function:
            return actual_decorator(function)
        return actual_decorator
    # login not required
    def decorator(view_func):
        def _wrapper(request, *args, **kwargs):
            return function(request, *args, **kwargs)
        return wraps(function)(_wrapper)
    return method_decorator(decorator)
642484
def get_object(self, queryset=None):
        
        if queryset is None:
            queryset = self.get_queryset()

        try:
            return queryset.get(user__pk=self.request.user.pk)
        except ObjectDoesNotExist:
            raise Http404
1017634
def authDomainUser(self, realmname, username, password, environ):
        """"""
        try:
            apikey = self.user_manager.get_user_api_key(username, create=None)
            return apikey is not None and password == apikey
        except:
            return False
420713
def authenticate(self, provider=None, identifier=None):
        ""
        provider_q = Q(provider__name=provider)
        if isinstance(provider, Provider):
            provider_q = Q(provider=provider)
        try:
            access = AccountAccess.objects.filter(
                provider_q, identifier=identifier
            ).select_related('user')[0]
        except IndexError:
            return None
        else:
            return access.user
562700
def get_response(self, url, username=None, password=None):
        
        scheme, netloc, path, query, frag = urlparse.urlsplit(url)
        req = self.get_request(url)

        stored_username, stored_password = self.passman.find_user_password(None, netloc)
        # see if we have a password stored
        if stored_username is None:
            if username is None and self.prompting:
                username = urllib.quote(raw_input('User for %s: ' % netloc))
                password = urllib.quote(getpass.getpass('Password: '))
            if username and password:
                self.passman.add_password(None, netloc, username, password)
            stored_username, stored_password = self.passman.find_user_password(None, netloc)
        authhandler = urllib2.HTTPBasicAuthHandler(self.passman)
        opener = urllib2.build_opener(authhandler)
        # FIXME: should catch a 401 and offer to let the user reenter credentials
        return opener.open(req)
874455
def validate_authentication(self, username, password, handler):
        
        user = authenticate(
            **{self.username_field: username, 'password': password}
        )
        account = self.get_account(username)
        if not (user and account):
            raise AuthenticationFailed("Authentication failed.")
957213
def authenticate(self, username=None, password=None, **kwargs):
        
        try:
            user = User.objects.get(email=username)
            if user.check_password(password):
                return user
        except (User.DoesNotExist, User.MultipleObjectsReturned):
            logging.warning('Unsuccessful login attempt using username/email: {0}'.format(username))

        return None
245196
def check_auth(user):
    '''
    
    '''

    # Initialize authentication
    auth = None
    person = None

    # Check if there is an user
    if user:

        # It means that Django accepted the user and it is active
        if user.is_staff or user.is_superuser:
            # This is an administrator, let it in
            auth = user
        else:
            # It is a normal user, check if there is a person behind
            person = getattr(user, "person", None)
            if not person:
                # Check if there is related one
                person_related = getattr(user, "people", None)
                if person_related:
                    # Must be only one
                    if person_related.count() == 1:
                        person = person_related.get()

            if person and ((person.disabled is None) or (person.disabled > timezone.now())):
                # There is a person, no disabled found or the found one is fine to log in
                auth = user

    # Return back the final decision
    return auth
269469
def anonymous_user_required(*decorator_args, msg=None, category=None, redirect_url=None):
    
    def wrapper(fn):
        @wraps(fn)
        def decorated(*args, **kwargs):
            if current_user.is_authenticated:
                if request.is_json:
                    abort(HTTPStatus.FORBIDDEN)
                else:
                    if msg:
                        flash(msg, category)
                    return redirect('SECURITY_POST_LOGIN_REDIRECT_ENDPOINT',
                                    override=redirect_url)
            return fn(*args, **kwargs)
        return decorated

    if decorator_args and callable(decorator_args[0]):
        return wrapper(decorator_args[0])
    return wrapper