hacked login, but the alternative is
 not having integration tests when
 using a Shibboleth based auth
194882
def sign_in_as(group)
      FactoryGirl.create(:user, umbcusername: 'test_user', group: group)
      page.driver.browser.process_and_follow_redirects(:get, '/shibbolite/login', {}, {'umbcusername' => 'test_user'})
    end
846182
private boolean loginMissingToken(NextFilter nextFilter,
                                      IoSession session,
                                      HttpRequestMessage httpRequest,
                                      AuthenticationToken authToken,
                                      TypedCallbackHandlerMap additionalCallbacks,
                                      HttpRealmInfo[] realms,
                                      int realmIndex,
                                      LoginContext[] loginContexts) {
        HttpRealmInfo realm = realms[realmIndex];

        // We build a LoginContext here and call login() so that login
        // modules have a chance to any challenge parameters to the initial
        // challenge (KG-2191).
        ResultAwareLoginContext loginContext = null;

        try {


            LoginContextFactory loginContextFactory = realm.getLoginContextFactory();
            TypedCallbackHandlerMap callbackHandlerMap = new TypedCallbackHandlerMap();

            registerCallbacks(session, httpRequest, authToken, callbackHandlerMap);
            callbackHandlerMap.putAll(additionalCallbacks);

            loginContext = (ResultAwareLoginContext) loginContextFactory.createLoginContext(callbackHandlerMap);
            if (loginContext == null) {
                throw new LoginException("Login failed; cannot create a login context for authentication token '" + authToken + "\'.");
            }

            if (loggerEnabled()) {
                log("Login module login required; [%s].", authToken);
            }

            loginContext.login();
        } catch (LoginException le) {
            // Depending on the login modules configured, this could be
            // a very normal condition.
            if (loggerEnabled()) {

                // Ignore the common "all modules ignored case", it just gums
                // up the logs whilst adding no value.
                if (le.getMessage() != null && !le.getMessage().contains("all modules ignored")) {
                    log("Login failed: " + le.getMessage(), le);
                }
            }

            if (loginContext == null) {
                // This can happen if the given authentication token is
                // not one that we support.  And if that is the case, then
                // we will never able to handle the token, so return
                // 403 now.
                writeResponse(HttpStatus.CLIENT_FORBIDDEN, nextFilter, session, httpRequest);
                return false;
            }
        } catch (Exception e) {
            if (loggerEnabled()) {
                log("Login failed.", e);
            }
            writeResponse(HttpStatus.CLIENT_FORBIDDEN, nextFilter, session, httpRequest);
            return false;
        }
        DefaultLoginResult loginResult = loginContext.getLoginResult();
        String challenge = sendChallengeResponse(nextFilter, session, httpRequest, loginResult, realms, realmIndex, loginContexts);
        if (loggerEnabled()) {
            log(String.format("No authentication token was provided.  Issuing an authentication challenge '%s'.", challenge));
        }
        // No matter what happens, we know that the roles currently present
        // are not sufficient for logging in, so return false.
        ResourceAddress localAddress = LOCAL_ADDRESS.get(session);
        String nextProtocol = localAddress.getOption(NEXT_PROTOCOL);
        if ("http/1.1".equals(nextProtocol)) {
            HttpMergeRequestFilter.INITIAL_HTTP_REQUEST_KEY.remove(session);
        }

        return false;
    }
817310
def session_login(self, user=None, passwd=None):
        
        self.change_credentials(user=user, auth_token=passwd)
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;
}
910122
def whoami(ctx, opts):
    """"""
    click.echo("Retrieving your authentication status from the API ... ", nl=False)

    context_msg = "Failed to retrieve your authentication status!"
    with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
        with maybe_spinner(opts):
            is_auth, username, email, name = get_user_brief()

    click.secho("OK", fg="green")
    click.echo("You are authenticated as:")
    if not is_auth:
        click.secho("Nobody (i.e. anonymous user)", fg="yellow")
    else:
        click.secho(
            "%(name)s (slug: %(username)s, email: %(email)s)"
            % {
                "name": click.style(name, fg="cyan"),
                "username": click.style(username, fg="magenta"),
                "email": click.style(email, fg="green"),
            }
        )
147140
def enable_root_f5(host)
      for tries in 1..10
        begin
          #This command is problematic as the F5 is not always done loading
          if host.exec(Command.new("modify sys db systemauth.disablerootlogin value false"), :acceptable_exit_codes => [0,1]).exit_code == 0 \
              and host.exec(Command.new("modify sys global-settings gui-setup disabled"), :acceptable_exit_codes => [0,1]).exit_code == 0 \
              and host.exec(Command.new("save sys config"), :acceptable_exit_codes => [0,1]).exit_code == 0
            backoff_sleep(tries)
            break
          elsif tries == 10
            raise "Instance was unable to be configured"
          end
        rescue Beaker::Host::CommandFailure => e
          @logger.debug("Instance not yet configured (#{e})")
        end
        backoff_sleep(tries)
      end
      host['user'] = 'admin'
      sha256 = Digest::SHA256.new
      password = sha256.hexdigest((1..50).map{(rand(86)+40).chr}.join.gsub(/\\/,'\&\&')) + 'password!'
      # disabling password policy to account for the enforcement level set
      # and the generated password is sometimes too `01070366:3: Bad password (admin): BAD PASSWORD: \
      # it is too simplistic/systematic`
      host.exec(Command.new('modify auth password-policy policy-enforcement disabled'))
      host.exec(Command.new("modify auth user admin password #{password}"))
      @logger.notify("f5: Configured admin password to be #{password}")
      host.close
      host['ssh'] = {:password => password}
    end
224169
def _basic_login(self):
        
        _LOGGER.debug("No/Expired/Invalid access_token, re-authenticating...")
        self.access_token = self.access_token_expires = None

        if self.refresh_token:
            _LOGGER.debug("Trying refresh_token...")
            credentials = {'grant_type': "refresh_token",
                           'scope': "EMEA-V1-Basic EMEA-V1-Anonymous",
                           'refresh_token': self.refresh_token}

            try:
                self._obtain_access_token(credentials)
            except (requests.HTTPError, KeyError, ValueError):
                _LOGGER.warning(
                    "Invalid refresh_token, will try user credentials.")
                self.refresh_token = None

        if not self.refresh_token:
            _LOGGER.debug("Trying user credentials...")
            credentials = {'grant_type': "password",
                           'scope': "EMEA-V1-Basic EMEA-V1-Anonymous "
                                    "EMEA-V1-Get-Current-User-Account",
                           'Username': self.username,
                           'Password': self.password}

            self._obtain_access_token(credentials)

        _LOGGER.debug("refresh_token = %s", self.refresh_token)
        _LOGGER.debug("access_token = %s", self.access_token)
        _LOGGER.debug("access_token_expires = %s",
                      self.access_token_expires.strftime("%Y-%m-%d %H:%M:%S"))
832128
def __auth_call(self, load):
        '''
        
        '''
        if 'eauth' not in load:
            return False
        fstr = '{0}.auth'.format(load['eauth'])
        if fstr not in self.auth:
            return False
        # When making auth calls, only username, password, auth, and token
        # are valid, so we strip anything else out.
        _valid = ['username', 'password', 'eauth', 'token']
        _load = {key: value for (key, value) in load.items() if key in _valid}

        fcall = salt.utils.args.format_call(
            self.auth[fstr],
            _load,
            expected_extra_kws=AUTH_INTERNAL_KEYWORDS)
        try:
            if 'kwargs' in fcall:
                return self.auth[fstr](*fcall['args'], **fcall['kwargs'])
            else:
                return self.auth[fstr](*fcall['args'])
        except Exception as e:
            log.debug('Authentication module threw %s', e)
            return False
200537
def auth(username, password):
    '''
    
    '''
    if not HAS_LDAP:
        log.error('LDAP authentication requires python-ldap module')
        return False

    bind = None

    # If bind credentials are configured, verify that we receive a valid bind
    if _config('binddn', mandatory=False) and _config('bindpw', mandatory=False):
        search_bind = _bind_for_search(anonymous=_config('anonymous', mandatory=False))

        # If username & password are not None, attempt to verify they are valid
        if search_bind and username and password:
            bind = _bind(username, password,
                         anonymous=_config('auth_by_group_membership_only', mandatory=False)
                         and _config('anonymous', mandatory=False))
    else:
        bind = _bind(username, password,
                     anonymous=_config('auth_by_group_membership_only', mandatory=False)
                     and _config('anonymous', mandatory=False))

    if bind:
        log.debug('LDAP authentication successful')
        return bind

    log.error('LDAP _bind authentication FAILED')
    return False
599608
def _plain_authentication(self, login, password, authz_id=b""):
        
        if isinstance(login, six.text_type):
            login = login.encode("utf-8")
        if isinstance(password, six.text_type):
            password = password.encode("utf-8")
        params = base64.b64encode(b'\0'.join([authz_id, login, password]))
        code, data = self.__send_command("AUTHENTICATE", [b"PLAIN", params])
        if code == "OK":
            return True
        return False
413807
def example(host, user, password, token):
    """"""
    client = None
    try:
        if token:
            print('token login')
            client = MatrixClient(host, token=token, user_id=user)
        else:
            print('password login')
            client = MatrixClient(host)
            token = client.login_with_password(user, password)
            print('got token: %s' % token)
    except MatrixRequestError as e:
        print(e)
        if e.code == 403:
            print("Bad username or password")
            exit(2)
        elif e.code == 401:
            print("Bad username or token")
            exit(3)
        else:
            print("Verify server details.")
            exit(4)
    except MissingSchema as e:
        print(e)
        print("Bad formatting of URL.")
        exit(5)
    except InvalidSchema as e:
        print(e)
        print("Invalid URL schema")
        exit(6)
    print("is in rooms")
    for room_id, room in client.get_rooms().items():
        print(room_id)
109522
function passwd(oldPassword, newPassword, callback) {
    if (!deis._authenticated) {
      return callback(new Error('You need to login first'));
    }

    deis.client.post(format('/%s/auth/passwd', deis.version), {
      password: oldPassword,
      new_password: newPassword
    }, function(err, res, body) {
      if (err) {
        return callback(err);
      }

      if (res.statusCode === 200) {
        return callback(null);
      }

      return callback(new Error('Password change failed: ' + body.detail));
    });
  }
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>')
927156
def authenticate_eauth(self, load):
        '''
        
        '''
        if 'eauth' not in load:
            log.warning('Authentication failure of type "eauth" occurred.')
            return False

        if load['eauth'] not in self.opts['external_auth']:
            log.warning('The eauth system "%s" is not enabled', load['eauth'])
            log.warning('Authentication failure of type "eauth" occurred.')
            return False

        # Perform the actual authentication. If we fail here, do not
        # continue.
        if not self.time_auth(load):
            log.warning('Authentication failure of type "eauth" occurred.')
            return False

        return True
838565
function( authType ) {
            switch ( authType.toLowerCase() ) {
                case 'basic':
                    console.log( 'Attempting to use basic authorisation' );
                    getBasicAuth() ? cb_success() : cb_failure();
                    break;

                case 'oauth':
                    console.log( 'Using oAuth to authenticate' );
                    return getOAuth();
                    break;

                default:
                    console.warn( 'Incorrect authorisation type passed to Octofish' );
                    console.warn( 'Authorisation to github will be unauthorised' );

                    cb_failure();
                    return false;
            }

            return true;
        }
62400
def process_basic_auth(auth)
      case auth
      when String
        self.login, self.password = auth.split(':', 2)
      when Hash
        self.login    = auth[:login]
        self.password = auth[:password]
      end
    end
644249
def check_basic_auth(user, passwd):
    """"""

    auth = request.authorization
    return auth and auth.username == user and auth.password == passwd