Decorator to require HTTP Basic Auth for your endpoint.
963113
def requires_basic_auth(f):
    """"""

    def check_auth(username, password):
        return username == "guest" and password == "secret"

    def authenticate():
        return Response(
            "Authentication required.", 401,
            {"WWW-Authenticate": "Basic realm='Login Required'"},
        )

    @wraps(f)
    def decorated(*args, **kwargs):
        # NOTE: This example will require Basic Auth only when you run the
        # app directly. For unit tests, we can't block it from getting the
        # Swagger specs so we just allow it to go thru without auth.
        # The following two lines of code wouldn't be needed in a normal
        # production environment.
        if __name__ != "__main__":
            return f(*args, **kwargs)

        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)

    return decorated
384029
def auth_required(*auth_methods):
    
    login_mechanisms = {
        'token': lambda: _check_token(),
        'basic': lambda: _check_http_auth(),
        'session': lambda: current_user.is_authenticated
    }

    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            h = {}
            mechanisms = [(method, login_mechanisms.get(method))
                          for method in auth_methods]
            for method, mechanism in mechanisms:
                if mechanism and mechanism():
                    return fn(*args, **kwargs)
                elif method == 'basic':
                    r = _security.default_http_auth_realm
                    h['WWW-Authenticate'] = 'Basic realm="%s"' % r
            if _security._unauthorized_callback:
                return _security._unauthorized_callback()
            else:
                return _get_unauthorized_response(headers=h)
        return decorated_view
    return wrapper
884633
def requires_authentication(func):
        
        def _auth(self, *args, **kwargs):
            if not self._authenticated:
                raise NotAuthenticatedException('Function {} requires'
                                                .format(func.__name__)
                                                + ' authentication')
            else:
                return func(self, *args, **kwargs)
        return _auth
1311112
def basic_auth(user, password, realm=None):
    
    from neobolt.security import AuthToken
    return AuthToken("basic", user, password, realm)
759307
def _get_auth(username, password):
    '''
    
    '''
    if username and password:
        return requests.auth.HTTPBasicAuth(username, password)
    else:
        return None
988741
def _auth_required(method, validator):
    
    @gen.coroutine
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        token = _get_token(self.request)
        valid_token = yield validator(token)
        if not valid_token:
            message = 'Invalid token: {}'.format(token)
            logging.warning(message)
            raise HTTPError(401, message)
        result = method(self, *args, **kwargs)

        if isinstance(result, Future):
            result = yield result

        raise gen.Return(result)

    return wrapper
258921
def requires_auth(f):
    
    @wraps(f)

    def decorated(self, *args, **kwargs):
        

        # Fetch auth options from args
        auth_options = {}
        nipap_args = {}

        # validate function arguments
        if len(args) == 1:
            nipap_args = args[0]
        else:
            self.logger.debug("Malformed request: got %d parameters" % len(args))
            raise Fault(1000, ("NIPAP API functions take exactly 1 argument (%d given)") % len(args))

        if type(nipap_args) != dict:
            self.logger.debug("Function argument is not struct")
            raise Fault(1000, ("Function argument must be XML-RPC struct/Python dict (Python %s given)." %
                type(nipap_args).__name__ ))

        # fetch auth options
        try:
            auth_options = nipap_args['auth']
            if type(auth_options) is not dict:
                raise ValueError()
        except (KeyError, ValueError):
            self.logger.debug("Missing/invalid authentication options in request.")
            raise Fault(1000, ("Missing/invalid authentication options in request."))

        # fetch authoritative source
        try:
            auth_source = auth_options['authoritative_source']
        except KeyError:
            self.logger.debug("Missing authoritative source in auth options.")
            raise Fault(1000, ("Missing authoritative source in auth options."))

        if not request.authorization:
            return authenticate()

        # init AuthFacory()
        af = AuthFactory()
        auth = af.get_auth(request.authorization.username,
                request.authorization.password, auth_source, auth_options or {})

        # authenticated?
        if not auth.authenticate():
            self.logger.debug("Incorrect username or password.")
            raise Fault(1510, ("Incorrect username or password."))

        # Replace auth options in API call arguments with auth object
        new_args = dict(args[0])
        new_args['auth'] = auth

        return f(self, *(new_args,), **kwargs)

    return decorated
1329452
def requires_auth(f):
    

    @wraps(f)
    def requires_auth_decorator(*args, **kwargs):

        try:
            authenticate_http_request()
        except PyMacaronException as e:
            return e.http_reply()

        return f(*args, **kwargs)

    return requires_auth_decorator
694800
def authbasic(request):
    
    if len(request.environ.get('HTTP_AUTHORIZATION', '')) > 0:
        auth = request.environ.get('HTTP_AUTHORIZATION')
        scheme, data = auth.split(None, 1)
        assert scheme.lower() == 'basic'
        data = base64.b64decode(data)
        if not isinstance(data, unicode):
            data = data.decode('utf-8')
        username, password = data.split(':', 1)
        if User.by_ldap_credentials(
                DBSession(), username, password, request.registry.settings):
            return HTTPFound(location=request.url)
        if User.by_credentials(DBSession(), username, password):
            return HTTPFound(location=request.url)
    return Response(status=401,
                    headerlist=[(str('WWW-Authenticate'),
                                 str('Basic realm="pyshop repository access"'),
                                 )],
                    )
860352
def login_required(fn):
    
    @wraps(fn)
    async def wrapped(*args, **kwargs):
        request = args[-1]
        if not isinstance(request, web.BaseRequest):
            msg = ("Incorrect decorator usage. "
                   "Expecting `def handler(request)` "
                   "or `def handler(self, request)`.")
            raise RuntimeError(msg)

        await check_authorized(request)
        return await fn(*args, **kwargs)

    warnings.warn("login_required decorator is deprecated, "
                  "use check_authorized instead",
                  DeprecationWarning)
    return wrapped
544988
def requires_basic_auth(func):
    
    @wraps(func)
    def auth_wrapper(self, *args, **kwargs):
        if hasattr(self, '_session') and self._session.auth:
            return func(self, *args, **kwargs)
        else:
            from .models import GitHubError
            # Mock a 401 response
            r = generate_fake_error_response(
                '{"message": "Requires username/password authentication"}'
            )
            raise GitHubError(r)
    return auth_wrapper
595996
def basicauthfail(self, realm = b'all'):
        
        if not isinstance(realm, bytes):
            realm = realm.encode('ascii')
        self.start_response(401, [(b'WWW-Authenticate', b'Basic realm="' + realm + b'"')])
        self.exit(b'<h1>' + _createstatus(401) + b'</h1>')
1022921
def http_auth(self):
        
        if 'HTTP_AUTHORIZATION' in self.request.META.keys():
            authmeth, auth = self.request.META['HTTP_AUTHORIZATION'].split(
                ' ', 1)
            if authmeth.lower() == 'basic':
                auth = auth.strip().decode('base64')
                identifier, password = auth.split(':', 1)
                username = get_username(identifier)
                user = authenticate(username=username, password=password)
                if user:
                    login(self.request, user)
                    return True
1360868
def token_protected_endpoint(function):
  
  @wraps(function)
  def decorated(*args, **kwargs):
    auth_token = request.form.get('auth_token')
    if not auth_token:
      return json.dumps({
        'status': 'fail',
        'reason': 'You must provide an auth_token',
      })

    data = dict(request.form)
    del data['auth_token']
    correct_token = create_token(current_app.config['SECRET_KEY'], data)

    if _compare_digest(auth_token, correct_token):
      return function(*args, **kwargs)

    else:
      return json.dumps({
        'status': 'fail',
        'reason': 'Incorrect auth_token',
      })

  return decorated
610329
def endpoint_get(auth=None, **kwargs):
    '''
    
    '''
    cloud = get_operator_cloud(auth)
    kwargs = _clean_kwargs(**kwargs)
    return cloud.get_endpoint(**kwargs)
1315268
def get_authorization(self):
        
        auth = get_authorization_header()

        if not auth:
            return None

        auth_type, auth_info = auth

        if auth_type != b'basic':
            return None

        try:
            username, password = base64.b64decode(auth_info).split(b':', 1)
        except Exception:
            return None

        return Authorization('basic', username=bytes_to_wsgi(username), password=bytes_to_wsgi(password))
985258
def authenticate(api_key, api_url, **kwargs):
    """"""

    muddle = Muddle(**kwargs)

    # Login.
    muddle.authenticate(api_key, api_url)
    return muddle