Spec for a group of authentication options
480882
def authentications_spec(self):
        """"""
        return container_spec(authentication_objs.Authentication
              , dictof(string_spec(), set_options(
                  reading = optional_spec(authentication_spec())
                , writing = optional_spec(authentication_spec())
                )
              )
            )
794090
def _ParseCredentialOptions(self, options):
    
    credentials = getattr(options, 'credentials', [])
    if not isinstance(credentials, list):
      raise errors.BadConfigOption('Unsupported credentials value.')

    for credential_string in credentials:
      credential_type, _, credential_data = credential_string.partition(':')
      if not credential_type or not credential_data:
        raise errors.BadConfigOption(
            'Badly formatted credential: {0:s}.'.format(credential_string))

      if credential_type not in self._SUPPORTED_CREDENTIAL_TYPES:
        raise errors.BadConfigOption(
            'Unsupported credential type for: {0:s}.'.format(
                credential_string))

      if credential_type in self._BINARY_DATA_CREDENTIAL_TYPES:
        try:
          credential_data = credential_data.decode('hex')
        except TypeError:
          raise errors.BadConfigOption(
              'Unsupported credential data for: {0:s}.'.format(
                  credential_string))

      self._credentials.append((credential_type, credential_data))
377
def inspect
      ['{config', *each.map{|key, value| " "+qualified_key(*key)+" => "+value.inspect },'}'].join("\n")
    end
45440
def provider_parser(subparser):
    """"""
    subparser.add_argument("--auth-access-key",
                           help="specify ACCESS_KEY for authentication")
    subparser.add_argument("--auth-access-secret",
                           help="specify ACCESS_SECRET for authentication")
    subparser.add_argument(
        "--private-zone",
        help=("indicates what kind of hosted zone to use. If true, use "
              "only private zones. If false, use only public zones"))

    # TODO: these are only required for testing, we should figure out
    # a way to remove them & update the integration tests
    # to dynamically populate the auth credentials that are required.
    subparser.add_argument(
        "--auth-username", help="alternative way to specify the ACCESS_KEY for authentication")
    subparser.add_argument(
        "--auth-token", help="alternative way to specify the ACCESS_SECRET for authentication")
169345
def validate_options!
      raise PosInvalid.new('Missing pos_id parameter') if pos_id.nil? || pos_id == 0
      raise PosInvalid.new('Missing pos_auth_key parameter') if pos_auth_key.nil? || pos_auth_key == ''
      raise PosInvalid.new('Missing key1 parameter') if key1.nil? || key1 == ''
      raise PosInvalid.new('Missing key2 parameter') if key2.nil? || key2 == ''
      raise PosInvalid.new("Invalid variant parameter, expected one of these: #{TYPES.join(', ')}") unless TYPES.include?(variant)
      raise PosInvalid.new("Invalid encoding parameter, expected one of these: #{ENCODINGS.join(', ')}") unless ENCODINGS.include?(encoding)
    end
1287563
def common_api_auth_options(f):
    """"""

    @click.option(
        "-k",
        "--api-key",
        hide_input=True,
        envvar="CLOUDSMITH_API_KEY",
        help="The API key for authenticating with the API.",
    )
    @click.pass_context
    @functools.wraps(f)
    def wrapper(ctx, *args, **kwargs):
        # pylint: disable=missing-docstring
        opts = config.get_or_create_options(ctx)
        opts.api_key = kwargs.pop("api_key")
        kwargs["opts"] = opts
        return ctx.invoke(f, *args, **kwargs)

    return wrapper
1214523
def authenticate_external(self, auth_params):
        
        if not isinstance(auth_params, list):
            raise TypeError("auth_params can only be an instance of type list")
        for a in auth_params[:10]:
            if not isinstance(a, basestring):
                raise TypeError(
                        "array can only contain objects of type basestring")
        result = self._call("authenticateExternal",
                     in_p=[auth_params])
        return result
1141658
def __verify_auth_params(username, password, access_token):
        """"""

        if all(v is not None for v in [username, password, access_token]):
            raise ValueError('Cannot supply a username/password and a access token')

        if (username is None or password is None) and access_token is None:
            raise ValueError('Must supply a username/password or access token')
435824
function validateConfig(configOrFileName) {
    var expectedKeys = [],
        mountPoints = {},
        mountPoint,
        config,
        errMsg,
        key;

    if (typeof configOrFileName === 'string') {
        configFileName = configOrFileName;
        config = require(configFileName);
    } else {
        config = configOrFileName;
    }

    assertObject('config', config);

    // addOn
    expectedKeys.push('addOn');
    assertObject('config.addOn', config.addOn);
    assertBoolean('config.addOn.enable', config.addOn.enable);
    assertArray('config.addOn.basePaths', config.addOn.basePaths);

    // authentication
    expectedKeys.push('authentication');
    assertObject('config.authentication', config.authentication);
    assertBoolean('config.authentication.enable', config.authentication.enable);
    assertBoolean('config.authentication.allowGuests', config.authentication.allowGuests);
    assertBooleanOrString('config.authentication.allowUserRegistration', config.authentication.allowUserRegistration);
    assertBoolean('config.authentication.registeredUsersCanCreate', config.authentication.registeredUsersCanCreate);
    assertBoolean('config.authentication.inferredUsersCanCreate', config.authentication.inferredUsersCanCreate);
    assertBoolean('config.authentication.guestCanCreate', config.authentication.guestCanCreate);
    assertString('config.authentication.guestAccount', config.authentication.guestAccount);
    assertString('config.authentication.logOutUrl', config.authentication.logOutUrl);
    assertNumber('config.authentication.salts', config.authentication.salts);
    assertObject('config.authentication.jwt', config.authentication.jwt);
    assertNumber('config.authentication.jwt.expiresIn', config.authentication.jwt.expiresIn);
    assertString('config.authentication.jwt.privateKey', config.authentication.jwt.privateKey);
    assertString('config.authentication.jwt.publicKey', config.authentication.jwt.publicKey);
    assertArray('config.authentication.publicOrganizations', config.authentication.publicOrganizations);
    config.authentication.publicOrganizations.forEach(function (publicOrg, idx) {
        assertString('config.authentication.publicOrganizations[' + idx, ']', publicOrg);
    });

    if (config.authentication.adminAccount) {
        assertString('config.authentication.adminAccount', config.authentication.adminAccount);
    }

    // bin scripts
    expectedKeys.push('bin');
    assertObject('config.bin', config.bin);
    assertObject('config.bin.log', config.bin.log);

    // blob
    expectedKeys.push('blob');
    assertObject('config.blob', config.blob);
    assertNumber('config.blob.compressionLevel', config.blob.compressionLevel);

    if (config.blob.compressionLevel < 0 || config.blob.compressionLevel > 9) {
        throw new Error('config.blob.compressionLevel must be an integer between 0 and 9. Got: ' +
            config.blob.compressionLevel);
    }

    assertString('config.blob.type', config.blob.type);
    assertString('config.blob.fsDir', config.blob.fsDir);
    assertObject('config.blob.s3', config.blob.s3);

    // client
    expectedKeys.push('client');
    assertObject('config.client', config.client);
    assertString('config.client.appDir', config.client.appDir);
    assertString('config.client.appVersion', config.client.appVersion);
    assertString('config.client.faviconPath', config.client.faviconPath);
    assertString('config.client.pageTitle', config.client.pageTitle, true);
    assertObject('config.client.log', config.client.log);
    assertString('config.client.log.level', config.client.log.level);

    // core
    expectedKeys.push('core');
    assertBoolean('config.core.enableCustomConstraints', config.core.enableCustomConstraints);
    assertNumber('config.core.overlayShardSize', config.core.overlayShardSize);
    if (config.core.overlayShardSize < 1000) {
        throw new Error('Overlay shard size must be at least 1000.');
    }

    // debug
    expectedKeys.push('debug');
    assertBoolean('config.debug', config.debug);

    expectedKeys.push('documentEditing');
    assertObject('config.documentEditing', config.documentEditing);
    assertBoolean('config.documentEditing.enable', config.documentEditing.enable, true);
    assertNumber('config.documentEditing.disconnectTimeout', config.documentEditing.disconnectTimeout);

    // executor
    expectedKeys.push('executor');
    assertObject('config.executor', config.executor);
    assertBoolean('config.executor.enable', config.executor.enable);
    assertString('config.executor.nonce', config.executor.nonce, true);
    warnDeprecated('config.executor.outputDir', config.executor.outputDir);
    assertString('config.executor.labelJobs', config.executor.labelJobs);
    assertNumber('config.executor.workerRefreshInterval', config.executor.workerRefreshInterval);
    assertNumber('config.executor.clearOutputTimeout', config.executor.clearOutputTimeout);
    assertBoolean('config.executor.clearOldDataAtStartUp', config.executor.clearOldDataAtStartUp);

    // mongo configuration
    expectedKeys.push('mongo');
    assertObject('config.mongo', config.mongo);
    assertString('config.mongo.uri', config.mongo.uri);
    assertObject('config.mongo.options', config.mongo.options);

    // plugin
    expectedKeys.push('plugin');
    assertObject('config.plugin', config.plugin);
    assertBoolean('config.plugin.allowServerExecution', config.plugin.allowServerExecution);
    assertArray('config.plugin.basePaths', config.plugin.basePaths);
    assertBoolean('config.plugin.displayAll', config.plugin.displayAll);

    // requirejsPaths
    expectedKeys.push('requirejsPaths');
    assertObject('config.requirejsPaths', config.requirejsPaths);

    // rest
    expectedKeys.push('rest');
    assertObject('config.rest', config.rest);
    assertObject('config.rest.components', config.rest.components);

    for (key in config.rest.components) {
        if (typeof config.rest.components[key] === 'string') {
            mountPoint = key;
            // TODO: Add this warn when the cli tool has been updated.
            // console.warn('config.rest.components[' + key + '] is a string a not an object. ' +
            // 'It is recommended to change to the format described in #xxxx');
        } else {
            assertObject('config.rest.components[' + key + ']', config.rest.components[key]);
            assertString('config.rest.components[' + key + '].mount', config.rest.components[key].mount);
            assertString('config.rest.components[' + key + '].src', config.rest.components[key].src);
            assertObject('config.rest.components[' + key + '].options', config.rest.components[key].options, true);
            mountPoint = config.rest.components[key].mount;
        }

        if (mountPoints[mountPoint] === true) {
            throw new Error('Same mount point [' + mountPoint + '] specified more than once ' +
                'in config.rest.components.');
        } else {
            mountPoints[mountPoint] = true;
        }
    }

    //seedProjects
    expectedKeys.push('seedProjects');
    assertBoolean('config.seedProjects.enable', config.seedProjects.enable);
    assertString('config.seedProjects.defaultProject', config.seedProjects.defaultProject);
    assertArray('config.seedProjects.basePaths', config.seedProjects.basePaths);
    assertArray('config.seedProjects.createAtStartup', config.seedProjects.createAtStartup);
    config.seedProjects.createAtStartup.forEach(function (seedInfo, index) {
        assertObject('config.seedProjects.createAtStartup[' + index + ']', config.seedProjects.createAtStartup[index]);
        assertString('config.seedProjects.createAtStartup[' + index + '].seedId',
            config.seedProjects.createAtStartup[index].seedId);
        assertString('config.seedProjects.createAtStartup[' + index + '].projectName', seedInfo.projectName);
        assertObject('config.seedProjects.createAtStartup[' + index + '].rights', seedInfo.rights, true);
        if (seedInfo.creatorId) {
            assertString('config.seedProjects.createAtStartup[' + index + '].creatorId', seedInfo.creatorId);
        } else if (typeof config.authentication.adminAccount !== 'string') {
            throw new Error('Either config.seedProjects.createAtStartup[' + index +
                '].creatorId or config.authentication.adminAccount should exists!');
        }

        assertString('config.seedProjects.createAtStartup[' + index + '].ownerId', seedInfo.ownerId, true);
    });

    // server configuration
    expectedKeys.push('server');
    assertObject('config.server', config.server);
    assertNumber('config.server.port', config.server.port);
    assertNumber('config.server.timeout', config.server.timeout);
    assertObject('config.server.handle', config.server.handle);
    assertObject('config.server.workerManager', config.server.workerManager);
    assertString('config.server.workerManager.path', config.server.workerManager.path);
    assertObject('config.server.workerManager.options', config.server.workerManager.options);
    assertNumber('config.server.maxWorkers', config.server.maxWorkers);
    warnDeprecated('config.server.sessionStore', config.server.sessionStore,
        'JWTokens are used for authentication, see config.authentication.jwt');

    // server log
    assertObject('config.server.log', config.server.log);
    assertArray('config.server.log.transports', config.server.log.transports);
    // server extlib
    assertArray('config.server.extlibExcludes', config.server.extlibExcludes);
    // server bodyParser config
    assertObject('config.server.bodyParser', config.server.bodyParser);
    assertObject('config.server.bodyParser.json', config.server.bodyParser.json);

    // socketIO
    expectedKeys.push('socketIO');
    assertObject('config.socketIO', config.socketIO);
    assertObject('config.socketIO.clientOptions', config.socketIO.clientOptions);
    assertObject('config.socketIO.serverOptions', config.socketIO.serverOptions);
    assertObject('config.socketIO.adapter', config.socketIO.adapter);
    assertEnum('config.socketIO.adapter.type', config.socketIO.adapter.type.toLowerCase(), 'memory', 'redis');

    // storage
    expectedKeys.push('storage');
    assertObject('config.storage', config.storage);
    assertBoolean('config.storage.broadcastProjectEvents', config.storage.broadcastProjectEvents);
    warnDeprecated('config.storage.emitCommittedCoreObjects', config.storage.emitCommittedCoreObjects,
        'see new config at config.storage.maxEmittedCoreObjects');
    assertNumber('config.storage.maxEmittedCoreObjects', config.storage.maxEmittedCoreObjects);
    warnDeprecated('config.storage.patchRootCommunicationEnabled', config.storage.patchRootCommunicationEnabled,
        'Since 1.7.0 all node changes are transmitted as patch objects (unless newly created).');
    assertNumber('config.storage.cache', config.storage.cache);
    assertNumber('config.storage.loadBucketSize', config.storage.loadBucketSize);
    assertNumber('config.storage.loadBucketTimer', config.storage.loadBucketTimer);
    assertEnum('config.storage.keyType', config.storage.keyType, 'rand160Bits', 'ZSSHA', 'plainSHA1');
    assertObject('config.storage.database', config.storage.database);
    assertEnum('config.storage.database.type', config.storage.database.type.toLowerCase(), 'mongo', 'redis', 'memory');
    assertObject('config.storage.database.options', config.storage.database.options);
    assertBoolean('config.storage.disableHashChecks', config.storage.disableHashChecks);
    assertBoolean('config.storage.requireHashesToMatch', config.storage.requireHashesToMatch);
    if (config.storage.disableHashChecks && config.storage.requireHashesToMatch) {
        throw new Error('Cannot set config.storage.disableHashChecks and requireHashesToMatch ' +
            'to true at the same time!');
    }

    //visualization
    expectedKeys.push('visualization');
    assertObject('config.visualization', config.visualization);
    assertArray('config.visualization.decoratorPaths', config.visualization.decoratorPaths);
    assertArray('config.visualization.svgDirs', config.visualization.svgDirs);
    assertArray('config.visualization.panelPaths', config.visualization.panelPaths);
    assertArray('config.visualization.visualizerDescriptors', config.visualization.visualizerDescriptors);
    assertObject('config.visualization.layout', config.visualization.layout);
    assertArray('config.visualization.layout.basePaths', config.visualization.layout.basePaths);

    //webhooks
    expectedKeys.push('webhooks');
    assertBoolean('config.webhooks.enable', config.webhooks.enable);
    assertEnum('config.webhooks.manager', config.webhooks.manager.toLowerCase(), 'memory', 'redis');
    if (config.webhooks.manager.toLowerCase() === 'redis' && config.socketIO.adapter.type.toLowerCase() !== 'redis') {
        throw new Error('config.webhooks.manager can only be ' +
            '\'redis\' if config.socketIO.adapter.type is \'redis\' as well');
    }

    if (Object.keys(config).length !== expectedKeys.length) {
        errMsg = 'Configuration had unexpected key(s):';
        for (key in config) {
            if (expectedKeys.indexOf(key) < 0) {
                errMsg += ' "' + key + '"';
            }
        }
        throw new Error(errMsg);
    }

    return config;
}
734332
def _format_auth_line(key, enc, comment, options):
    '''
    
    '''
    line = ''
    if options:
        line += '{0} '.format(','.join(options))
    line += '{0} {1} {2}\n'.format(enc, key, comment)
    return line
1274594
function specs() {
    var routes = {};

    // Reducing the app's recursive stack
    function reduceStack(path, items, item) {
      var nextPath;

      if (item.handle && item.handle.stack) {
        nextPath = join(path, (item.path || helpers.unescapeRegex(item.regexp) || ''));
        return items.concat(item.handle.stack.reduce(reduceStack.bind(null, nextPath), []));
      }

      if (item.route) {
        nextPath = join(path, (item.route.path || ''));
        return items.concat(item.route.stack.reduce(reduceStack.bind(null, nextPath), []));
      }

      return items.concat({
        handle: item.handle,
        path: path
      });
    }

    // Filtering the actions coming from dolman
    app._router.stack
      .reduce(reduceStack.bind(null, ''), [])
      .map(function(item) {
        return {
          route: routesMap.get(item.handle),
          path: item.path
        };
      })
      .filter(function(item) {
        return item.route && item.route.name;
      })
      .forEach(function(item) {
        var route = item.route,
            method = [].concat(route.method || route.methods)[0];

        var routeData = {
          path: item.path,
          name: route.name,
          method: !method || method === 'ALL' ? 'GET' : method
        };

        ['description'].forEach(function(k) {
          if (route[k])
            routeData[k] = route[k];
        });

        routes[route.name] = routeData;
      });

    return {
      formats: ['json'],
      methods: routes
    };
  }
614739
def _build_credentials_tuple(mech, source, user, passwd, extra, database):
    
    if mech != 'MONGODB-X509' and user is None:
        raise ConfigurationError("%s requires a username." % (mech,))
    if mech == 'GSSAPI':
        if source is not None and source != '$external':
            raise ValueError(
                "authentication source must be $external or None for GSSAPI")
        properties = extra.get('authmechanismproperties', {})
        service_name = properties.get('SERVICE_NAME', 'mongodb')
        canonicalize = properties.get('CANONICALIZE_HOST_NAME', False)
        service_realm = properties.get('SERVICE_REALM')
        props = GSSAPIProperties(service_name=service_name,
                                 canonicalize_host_name=canonicalize,
                                 service_realm=service_realm)
        # Source is always $external.
        return MongoCredential(mech, '$external', user, passwd, props, None)
    elif mech == 'MONGODB-X509':
        if passwd is not None:
            raise ConfigurationError(
                "Passwords are not supported by MONGODB-X509")
        if source is not None and source != '$external':
            raise ValueError(
                "authentication source must be "
                "$external or None for MONGODB-X509")
        # user can be None.
        return MongoCredential(mech, '$external', user, None, None, None)
    elif mech == 'PLAIN':
        source_database = source or database or '$external'
        return MongoCredential(mech, source_database, user, passwd, None, None)
    else:
        source_database = source or database or 'admin'
        if passwd is None:
            raise ConfigurationError("A password is required.")
        return MongoCredential(
            mech, source_database, user, passwd, None, _Cache())
700434
def read_authentication_config (self):
        """"""
        section = "authentication"
        password_fields = []
        if self.has_option(section, "entry"):
            for val in read_multiline(self.get(section, "entry")):
                auth = val.split()
                if len(auth) == 3:
                    self.config.add_auth(pattern=auth[0], user=auth[1],
                                         password=auth[2])
                    password_fields.append("entry/%s/%s" % (auth[0], auth[1]))
                elif len(auth) == 2:
                    self.config.add_auth(pattern=auth[0], user=auth[1])
                else:
                    raise LinkCheckerError(
                       _("missing auth part in entry %(val)r") % {"val": val})
        # read login URL and field names
        if self.has_option(section, "loginurl"):
            val = self.get(section, "loginurl").strip()
            if not (val.lower().startswith("http:") or
                    val.lower().startswith("https:")):
                raise LinkCheckerError(_("invalid login URL `%s'. Only " \
                  "HTTP and HTTPS URLs are supported.") % val)
            self.config["loginurl"] = val
        self.read_string_option(section, "loginuserfield")
        self.read_string_option(section, "loginpasswordfield")
        # read login extra fields
        if self.has_option(section, "loginextrafields"):
            for val in read_multiline(self.get(section, "loginextrafields")):
                name, value = val.split(":", 1)
                self.config["loginextrafields"][name] = value
        self.check_password_readable(section, password_fields)
20965
def verify_credentials(self, delegate=None):
        ""
        parser = txml.Users(delegate)
        return self.__downloadPage('/account/verify_credentials.xml', parser)
343814
def validate(config):
    '''
    
    '''

    # Configuration for load beacon should be a list of dicts
    if not isinstance(config, list):
        return False, ('Configuration for load beacon must be a list.')
    else:
        _config = {}
        list(map(_config.update, config))

        if 'emitatstartup' in _config:
            if not isinstance(_config['emitatstartup'], bool):
                return False, ('Configuration for load beacon option '
                               'emitatstartup must be a boolean.')

        if 'onchangeonly' in _config:
            if not isinstance(_config['onchangeonly'], bool):
                return False, ('Configuration for load beacon option '
                               'onchangeonly must be a boolean.')

        if 'averages' not in _config:
            return False, ('Averages configuration is required'
                           ' for load beacon.')
        else:

            if not any(j in ['1m', '5m', '15m'] for j
                       in _config.get('averages', {})):
                return False, ('Averages configuration for load beacon '
                               'must contain 1m, 5m or 15m items.')

            for item in ['1m', '5m', '15m']:
                if not isinstance(_config['averages'][item], list):
                    return False, ('Averages configuration for load beacon: '
                                   '1m, 5m and 15m items must be '
                                   'a list of two items.')
                else:
                    if len(_config['averages'][item]) != 2:
                        return False, ('Configuration for load beacon: '
                                       '1m, 5m and 15m items must be '
                                       'a list of two items.')

    return True, 'Valid beacon configuration'
1361243
def validate(config):
    '''
    
    '''
    # Configuration for adb beacon should be a dictionary with states array
    if not isinstance(config, list):
        log.info('Configuration for adb beacon must be a list.')
        return False, ('Configuration for adb beacon must be a list.')

    _config = {}
    list(map(_config.update, config))

    if 'states' not in _config:
        log.info('Configuration for adb beacon must include a states array.')
        return False, ('Configuration for adb beacon must include a states array.')
    else:
        if not isinstance(_config['states'], list):
            log.info('Configuration for adb beacon must include a states array.')
            return False, ('Configuration for adb beacon must include a states array.')
        else:
            states = ['offline', 'bootloader', 'device', 'host',
                      'recovery', 'no permissions',
                      'sideload', 'unauthorized', 'unknown', 'missing']
            if any(s not in states for s in _config['states']):
                log.info('Need a one of the following adb '
                         'states: %s', ', '.join(states))
                return False, ('Need a one of the following adb '
                               'states: {0}'.format(', '.join(states)))
    return True, 'Valid beacon configuration'
837712
def authenticationAndCipheringResponse(
                                       AuthenticationParameterSRES_presence=0,
                                       MobileId_presence=0):
    """"""
    a = TpPd(pd=0x3)
    b = MessageType(mesType=0x13)  # 00010011
    c = AcReferenceNumberAndSpareHalfOctets()
    packet = a / b / c
    if AuthenticationParameterSRES_presence is 1:
        e = AuthenticationParameterSRES(ieiAPS=0x22)
        packet = packet / e
    if MobileId_presence is 1:
        f = MobileIdHdr(ieiMI=0x23, eightBitMI=0x0)
        packet = packet / f
    return packet