Support basic_auth via /login or login_required(basic=True)
181117
def basic_auth(self, response=None):
        """"""
        auth = request.authorization
        if auth and self._login_checker({'username': auth.username,
                                         'password': auth.password}):
            session['simple_logged_in'] = True
            session['simple_basic_auth'] = True
            session['simple_username'] = auth.username
            return response or True
        else:
            headers = {'WWW-Authenticate': 'Basic realm="Login Required"'}
            return 'Invalid credentials', 401, headers
861245
def auth_set(self, status):
		
		if not bool(status):
			self.__config['basic_auth'] = None
			self.logger.info('basic authentication has been disabled')
		else:
			self.__config['basic_auth'] = {}
			self.logger.info('basic authentication has been enabled')
627012
def basic_auth(opts)
      user = opts.fetch :user
      pass = opts.fetch :pass

      auth("Basic " + Base64.strict_encode64("#{user}:#{pass}"))
    end
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
1254437
def http_basic_auth_group_member_required(groups):
    """"""

    if isinstance(groups, six.string_types):
        # Check user is in a group
        return auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_in_group, groups])
    else:
        # Check user is in many group
        return auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_in_any_group, groups])
1362181
function auth(cmd, args, info) {
  var pass = args[0];
  if(pass instanceof Buffer) {
    pass = pass.toString();
  }
  if(!info.conf.requirepass) {
    throw AuthNotSet;
  }else if(pass !== info.conf.requirepass) {
    throw InvalidPassword;
  }
  return true;
}
186990
def authentication_validation(username, password, access_token):
    '''
    
    '''
    if bool(username) is not bool(password):
        raise Exception("Basic authentication requires a username AND"
                        " password.")
    if (username and access_token) or (password and access_token):
        raise Exception("Cannot use both Basic Authentication and"
                        " OAuth2.0. Please use only one authentication"
                        " method.")
1095083
def _auth_required():
    

    login_mechanisms = (
        ('token', lambda: _check_token()),
        ('session', lambda: current_user.is_authenticated),
    )

    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            for method, mechanism in login_mechanisms:
                if mechanism and mechanism():
                    return fn(*args, **kwargs)
            return security._unauthorized_callback()
        return decorated_view
    return wrapper
1099270
def authenticate(self, request):
        
        auth = get_authorization_header(request).split()

        if not auth or auth[0].lower() != b'basic':
            return None

        if len(auth) == 1:
            msg = _('Invalid basic header. No credentials provided.')
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = _('Invalid basic header. Credentials string should not contain spaces.')
            raise exceptions.AuthenticationFailed(msg)

        try:
            auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':')
        except (TypeError, UnicodeDecodeError):
            msg = _('Invalid basic header. Credentials not correctly base64 encoded.')
            raise exceptions.AuthenticationFailed(msg)

        userid, password = auth_parts[0], auth_parts[2]
        return self.authenticate_credentials(userid, password)
1244198
def _auth(url, user, passwd, realm):
    '''
    
    '''

    basic = _HTTPBasicAuthHandler()
    basic.add_password(realm=realm, uri=url, user=user, passwd=passwd)
    digest = _HTTPDigestAuthHandler()
    digest.add_password(realm=realm, uri=url, user=user, passwd=passwd)
    return _build_opener(basic, digest)
523229
def auth_basic(check, realm="private", text="Access denied"):
    '''  '''
    def decorator(func):
      def wrapper(*a, **ka):
        user, password = request.auth or (None, None)
        if user is None or not check(user, password):
          response.headers['WWW-Authenticate'] = 'Basic realm="%s"' % realm
          return HTTPError(401, text)
        return func(*a, **ka)
      return wrapper
    return decorator
654476
def basicauth(self, realm = b'all', nofail = False):
        ""
        if b'authorization' in self.headerdict:
            auth = self.headerdict[b'authorization']
            auth_pair = auth.split(b' ', 1)
            if len(auth_pair) < 2:
                raise HttpInputException('Authorization header is malformed')
            if auth_pair[0].lower() == b'basic':
                try:
                    userpass = base64.b64decode(auth_pair[1])
                except Exception:
                    raise HttpInputException('Invalid base-64 string')
                userpass_pair = userpass.split(b':', 1)
                if len(userpass_pair) != 2:
                    raise HttpInputException('Authorization header is malformed')
                return userpass_pair
        if nofail:
            return (None, None)
        else:
            self.basicauthfail(realm)
759521
def basic_auth_string(username, password):
    
    b64 = base64.encodestring('%s:%s' % (username, password)).strip()
    return 'Basic %s' % b64
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
169975
def requires_auth(self, func):
        '''
        
        '''
        @wraps(func)
        def decorated(*args, **kwargs):
            ''' Wrapper '''
            auth = request.authorization
            if not auth or not self.check_auth(auth.username, auth.password):
                return self.authenticate()
            return func(*args, **kwargs)
        return decorated
35605
function basic($func=NULL) {
		$fw=Base::instance();
		$realm=$fw->REALM;
		$hdr=NULL;
		if (isset($_SERVER['HTTP_AUTHORIZATION']))
			$hdr=$_SERVER['HTTP_AUTHORIZATION'];
		elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
			$hdr=$_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
		if (!empty($hdr))
			list($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW'])=
				explode(':',base64_decode(substr($hdr,6)));
		if (isset($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']) &&
			$this->login(
				$_SERVER['PHP_AUTH_USER'],
				$func?
					$fw->call($func,$_SERVER['PHP_AUTH_PW']):
					$_SERVER['PHP_AUTH_PW'],
				$realm
			))
			return TRUE;
		if (PHP_SAPI!='cli')
			header('WWW-Authenticate: Basic realm="'.$realm.'"');
		$fw->status(401);
		return FALSE;
	}
513963
def add_http_basic_auth(url,
                        user=None,
                        password=None,
                        https_only=False):
    '''
    
    '''
    if user is None and password is None:
        return url
    else:
        urltuple = urlparse(url)
        if https_only and urltuple.scheme != 'https':
            raise ValueError('Basic Auth only supported for HTTPS')
        if password is None:
            netloc = '{0}@{1}'.format(
                user,
                urltuple.netloc
            )
            urltuple = urltuple._replace(netloc=netloc)
            return urlunparse(urltuple)
        else:
            netloc = '{0}:{1}@{2}'.format(
                user,
                password,
                urltuple.netloc
            )
            urltuple = urltuple._replace(netloc=netloc)
            return urlunparse(urltuple)