Resolves the default auth mechanism according to https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst
970749
function getDefaultAuthMechanism(ismaster) {
  if (ismaster) {
    // If ismaster contains saslSupportedMechs, use scram-sha-256
    // if it is available, else scram-sha-1
    if (Array.isArray(ismaster.saslSupportedMechs)) {
      return ismaster.saslSupportedMechs.indexOf('SCRAM-SHA-256') >= 0
        ? 'scram-sha-256'
        : 'scram-sha-1';
    }

    // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1
    if (ismaster.maxWireVersion >= 3) {
      return 'scram-sha-1';
    }
  }

  // Default for wireprotocol < 3
  return 'mongocr';
}
614266
function applyAxiosDefaults(authenticatedAPIClient) {
  /* eslint-disable no-param-reassign */
  authenticatedAPIClient.defaults.withCredentials = true;
  authenticatedAPIClient.defaults.headers.common['USE-JWT-COOKIE'] = true;
  /* eslint-enable no-param-reassign */
}
770961
def rebuild_auth(self, prepared_request, response):
        
        u = urlparse(prepared_request.url)
        if u.netloc.endswith('archive.org'):
            return
        super(ArchiveSession, self).rebuild_auth(prepared_request, response)
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
4565
public MongoDB auth(String username, String password) {
        return username(username).password(password);
    }
1048937
function getMongoHandle(mongoose) {
    var res = {
        mongoose: mongoose,
        modelDocs: {},
        modelESchemas: {},
        mongoMaps: {}
    };
    var modelES = Schemaload.getExtendedSchemaModel(mongoose);
    return modelES.distinct('modelname').then((modelnames) => {
        debuglog(() => 'here distinct modelnames ' + JSON.stringify(modelnames));
        return Promise.all(modelnames.map(function (modelname) {
            debuglog(() => 'creating tripel for ' + modelname);
            return Promise.all([Schemaload.getExtendSchemaDocFromDB(mongoose, modelname),
                Schemaload.makeModelFromDB(mongoose, modelname),
                Schemaload.getModelDocFromDB(mongoose, modelname)]).then((value) => {
                debuglog(() => 'attempting to load ' + modelname + 'to create mongomap');
                var [extendedSchema, model, modelDoc] = value;
                res.modelESchemas[modelname] = extendedSchema;
                res.modelDocs[modelname] = modelDoc;
                res.mongoMaps[modelname] = MongoMap.makeMongoMap(modelDoc, extendedSchema);
                debuglog(() => 'created mongomap for ' + modelname);
            });
        }));
    }).then(() => {
        return res;
    });
    //var modelDoc = Schemaload.getExtendedDocModel(mongoose);
    //res.modelDocs[ISchema.MongoNLQ.MODELNAME_METAMODELS] = modelDoc;
    //return Promise.resolve(res);
}
910683
function useAccessAuth() {
  return new Promise((resolve, reject) => {
    if (!defaults.accessToken) {
      reject(__generateFakeResponse__(0, '', {}, 'accessToken is missing for Access authentication'))
    }
    else {
      let details = {
        "token_type": "",
        "expires_in": 0,
        "appName": defaults.appName,
        "username": "",
        "role": "",
        "firstName": "",
        "lastName": "",
        "fullName": "",
        "regId": 0,
        "userId": null
      };
      var aToken = defaults.accessToken.toLowerCase().startsWith('bearer') ? defaults.accessToken : 'Bearer ' + defaults.accessToken;
      utils.storage.set('user', {
        token: {
          Authorization:  aToken,
          appName: defaults.appName
        },
        details: details
      });
      resolve(__generateFakeResponse__(200, 'OK', {}, details, {}));
    }
  });

}
831483
function useBasicAuth() {
  return new Promise((resolve, reject) => {
    if (!defaults.userToken || !defaults.masterToken) {
      reject(__generateFakeResponse__(0, '', {}, 'userToken or masterToken are missing for basic authentication'))
    }
    else {
      let details = {
        "token_type": "Basic",
        "expires_in": 0,
        "appName": defaults.appName,
        "username": "",
        "role": "",
        "firstName": "",
        "lastName": "",
        "fullName": "",
        "regId": 0,
        "userId": null
      };
      let basicToken = 'Basic ' + createBasicToken(defaults.masterToken, defaults.userToken);
      utils.storage.set('user', {
        token: {
          Authorization:  basicToken
        },
        details: details
      });
      resolve(__generateFakeResponse__(200, 'OK', {}, details, {}));
    }
  });

}
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;
        }
991197
function authorize(newDoc, oldDoc, userContext, securityInfo, docDefinition) {
    if (utils.isValueNullOrUndefined(userContext)) {
      throw unauthorizedResult();
    }

    var authorizedRoles = resolveRequiredAuthorizations(newDoc, oldDoc, docDefinition.authorizedRoles);
    var authorizedUsers = resolveRequiredAuthorizations(newDoc, oldDoc, docDefinition.authorizedUsers);
    var grantAllMembersWriteAccess = utils.resolveDocumentConstraint(docDefinition.grantAllMembersWriteAccess);

    if (grantAllMembersWriteAccess) {
      // The document definition allows any authenticated DB member to write documents of this type
      return authorizationSuccessResult(authorizedRoles, authorizedUsers);
    } else if (isAdminUser(userContext, securityInfo)) {
      // Database admins have unrestricted access
      return authorizationSuccessResult(authorizedRoles, authorizedUsers);
    } else if (!authorizedRoles && !authorizedUsers) {
      // The document type does not define any authorized roles or users
      throw forbiddenResult();
    }

    var roleMatch = hasAuthorizedRole(authorizedRoles, userContext.roles);
    var usernameMatch = hasAuthorizedUsername(authorizedUsers, userContext.name);
    if (!roleMatch && !usernameMatch) {
      // None of the required authorizations were satisfied
      throw forbiddenResult();
    } else {
      return authorizationSuccessResult(authorizedRoles, authorizedUsers);
    }
  }
733620
def get_auth():
    """"""
    import getpass
    user = input("User Name: ")  # noqa
    pswd = getpass.getpass('Password: ')
    return Github(user, pswd)
657681
def auth_view(name, **kwargs):
    
    ctx = Context(**kwargs)
    ctx.execute_action('auth:group:view', **{
        'storage': ctx.repo.create_secure_service('storage'),
        'name': name,
    })
1228192
function defaultJsonResponse(req, res) {
  res.json({
    account: helpers.strippedAccount(req.user)
  });
}
1086979
def _parse_credentials(username, password, database, options):
    """"""
    mechanism = options.get('authmechanism', 'DEFAULT')
    if username is None and mechanism != 'MONGODB-X509':
        return None
    source = options.get('authsource', database or 'admin')
    return _build_credentials_tuple(
        mechanism, source, username, password, options)
233967
function(
  self,
  mongo_auth_process,
  payload,
  db,
  username,
  password,
  authdb,
  server,
  connection,
  callback
) {
  // Build the sasl start command
  var command = {
    saslStart: 1,
    mechanism: 'GSSAPI',
    payload: payload,
    autoAuthorize: 1
  };

  // Write the commmand on the connection
  server(
    connection,
    new Query(self.bson, '$external.$cmd', command, {
      numberToSkip: 0,
      numberToReturn: 1
    }),
    function(err, r) {
      if (err) return callback(err, false);
      var doc = r.result;
      // Execute mongodb transition
      mongo_auth_process.transition(r.result.payload, function(err, payload) {
        if (err) return callback(err, false);

        // MongoDB API Second Step
        MongoDBGSSAPISecondStep(
          self,
          mongo_auth_process,
          payload,
          doc,
          db,
          username,
          password,
          authdb,
          server,
          connection,
          callback
        );
      });
    }
  );
}
848990
function (auth, done) {
        !auth.get('nonce') && auth.set('nonce', randomString(6));
        !_.parseInt(auth.get('timestamp')) && auth.set('timestamp', Math.floor(Date.now() / 1e3));
        done(null, true);
    }
1311112
def basic_auth(user, password, realm=None):
    
    from neobolt.security import AuthToken
    return AuthToken("basic", user, password, realm)