Generate setup token
506240
function generateSetupToken (tokenPath) {
  mkdirp.sync(path.dirname(tokenPath))

  var token = crypto.randomBytes(256).toString('hex')
  try {
    fs.writeFileSync(tokenPath, token, 'utf8')
  } catch (e) {
    throw new Error('Unable to save setup token to ' + tokenPath)
  }
  return token
}
442238
function setupResourceServer(app, options, models) {

    function checkAccessToken(req, accessToken, done) {
        debug('Verifying access token %s', accessToken);
        models.AccessTokens.find(accessToken, function (err, token) {
            if (err || !token) {
                return done(err);
            }

            debug('Access token found: %j', token);

            if (isExpired(token)) {
                return done(new TokenError('Access token is expired',
                    'invalid_grant'));
            }

            var userId = token.userId || token.resourceOwner;
            var appId = token.appId || token.clientId;

            var user, app;
            async.parallel([
                function lookupUser(done) {
                    if (userId == null) {
                        return process.nextTick(done);
                    }
                    models.Users.find(userId, function (err, u) {
                        if (err) {
                            return done(err);
                        }
                        if (!u) {
                            return done(
                                new TokenError('Access token has invalid user id: ' +
                                    userId, 'invalid_grant'));
                        }
                        debug('User found: %s', userInfo(u));
                        user = u;
                        done();
                    });
                },
                function lookupApp(done) {
                    if (appId == null) {
                        return process.nextTick(done);
                    }
                    models.Clients.find(appId, function (err, a) {
                        if (err) {
                            return done(err);
                        }
                        if (!a) {
                            return done(
                                new TokenError('Access token has invalid app id: ' + appId,
                                    'invalid_grant'));
                        }
                        debug('Client found: %s', clientInfo(a));
                        app = a;
                        done();
                    });
                }], function (err) {
                if (err) {
                    return done(err);
                }
                if (options.addHttpHeaders) {
                    var prefix = 'X-OAUTH2-';
                    if (typeof options.addHttpHeaders === 'string') {
                        prefix = options.addHttpHeaders;
                    }
                    if (appId != null) {
                        req.headers[prefix + 'CLIENT-ID'] = appId;
                    }
                    if (userId != null) {
                        req.headers[prefix + 'USER-ID'] = userId;
                    }
                }
                var authInfo =
                {accessToken: token, user: user, app: app, client: app};
                done(null, user || {}, authInfo);
            });
        });
    }

    var verifyAccessToken = checkAccessToken;
    if (typeof options.checkAccessToken === 'function') {
        verifyAccessToken = options.checkAccessToken;
    }

    function accessTokenValidator(req, accessToken, done) {
        verifyAccessToken(req, accessToken, function (err, user, info) {
            if (!err && info) {
                req.accessToken = info.accessToken;
            }
            done(err, user, info);
        });
    }

    /**
     * BearerStrategy
     *
     * This strategy is used to authenticate users based on an access token (aka a
     * bearer token).  The user must have previously authorized a client
     * application, which is issued an access token to make requests on behalf of
     * the authorizing user.
     */
    passport.use('copress-oauth2-bearer',
        new BearerStrategy({passReqToCallback: true}, accessTokenValidator)
    );

    passport.use('copress-oauth2-mac',
        new MacStrategy({passReqToCallback: true, jwtAlgorithm: 'HS256'},
            function (req, accessToken, done) {
                accessTokenValidator(req, accessToken, function (err, user, info) {
                    if (err || !user) {
                        return done(err, user, info);
                    }
                    var client = info && info.client;
                    var secret = client.clientSecret || client.restApiKey;
                    try {
                        var token = jwt.verify(accessToken, 'HS256', secret);
                        debug('JWT token verified: %j', token);
                    } catch (err) {
                        debug('Fail to verify JWT: %j', err);
                        done(err);
                    }
                    done(null, user, info);
                });
            })
    );

    /**
     * Return the middleware chain to enforce oAuth 2.0 authentication and
     * authorization
     * @param {Object} [options] Options object
     * - scope
     * - jwt
     */
    function authenticate(options) {
        options = options || {};

        var authenticators = [
            passport.authenticate(['copress-oauth2-bearer', 'copress-oauth2-mac'],
                options)];
        if (options.scopes || options.scope) {
            authenticators.push(scopeValidator(options));
        }
        authenticators.push(oauth2Provider.errorHandler());
        return authenticators;
    }

    return authenticate;
}
379538
def generate_headers(self, token):
        """"""
        headers = {}
        token = self.encode_token(token)
        if self.config["header"]:
            headers[self.config["header"]] = token
        if self.config["cookie"]:
            headers["Set-Cookie"] = dump_cookie(
                self.config["cookie"], token, httponly=True,
                max_age=self.config["expiration"]
            )
        return headers
51938
def token(ctx, opts, login, password):
    """"""
    click.echo(
        "Retrieving API token for %(login)s ... "
        % {"login": click.style(login, bold=True)},
        nl=False,
    )

    context_msg = "Failed to retrieve the API token!"
    with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
        with maybe_spinner(opts):
            api_key = get_user_token(login=login, password=password)

    click.secho("OK", fg="green")

    click.echo(
        "Your API key/token is: %(token)s"
        % {"token": click.style(api_key, fg="magenta")}
    )

    create, has_errors = create_config_files(ctx, opts, api_key=api_key)

    if has_errors:
        click.echo()
        click.secho("Oops, please fix the errors and try again!", fg="red")
        return

    if opts.api_key != api_key:
        click.echo()
        if opts.api_key:
            click.secho(
                "Note: The above API key doesn't match what you have in "
                "your default credentials config file.",
                fg="yellow",
            )
        elif not create:
            click.secho(
                "Note: Don't forget to put your API key in a config file, "
                "export it on the environment, or set it via -k.",
                fg="yellow",
            )
            click.secho(
                "If you need more help please see the documentation: "
                "%(website)s" % {"website": click.style(get_help_website(), bold=True)}
            )
        click.echo()

    click.secho("You're ready to rock, let's start automating!", fg="green")
635659
public function generateToken()
	{
		$controller = new AjaxController();
		$controller->restrictAccess(Auth::isAdmin());
		
		$token = Functions::generateRandomToken();		
		$this->module->setSetting('MAJ_AT_FORCE_EXEC_TOKEN', $token);
		Log::addConfigurationLog($this->module->getTitle().' : New token generated.');
		
		$controller->pageHeader();
		echo $token;
	}
1213035
def generate_token():
    
    length = 50
    stringset = string.ascii_letters + string.digits
    token = ''.join([stringset[i % len(stringset)] for i in [ord(x) for x in os.urandom(length)]])
    return token
75706
protected function genToken()
    {
        // Generate a new random token (as random as possible)
        $rg = new RandomGenerator();
        $token = $rg->randomToken('md5');

        // Store a file in the session save path (safer than /tmp, as open_basedir might limit that)
        file_put_contents($this->pathForToken($token), $token);

        return $token;
    }
669926
def setup_incoming_webhook
      ## incoming_webhook will be used if provided, otherwise fallback to old-style url with team and token
      url = @options.fetch('incoming_webhook', false) || "https://#{@options['team']}.slack.com/services/hooks/incoming-webhook?token=#{@options['incoming_token']}"
      @uri  = URI.parse(url)
      @http = Net::HTTP.new(@uri.host, @uri.port)
      @http.use_ssl = true
      @http.verify_mode = OpenSSL::SSL::VERIFY_PEER
    end
802470
function init(config) {
    var tokenConfig = config.security.token || {};
    var privateKey = tokenConfig.privateKey;
    var decryptedToken = {
        _id: tokenConfig.webserverId,
        authToken: tokenConfig.webserverToken
    };
    var jwt = jsonwebtoken.sign(decryptedToken, privateKey);

    headers = { 'Authorization': 'Bearer ' + jwt };

    admin._id =  mongo.newObjectId('000000000000000000000000');
    admin.name = 'systemAdmin';
    admin.type = 'user';
    admin.role = 'admin';

    var apiConfig = config.api || {};
    var host = apiConfig.internalHost || apiConfig.host;  // from web server to api use internalHost name
    var useSSL = apiConfig.serverUseSSL !== undefined ?
        apiConfig.serverUseSSL : config.useSSL;
    baseUrl = (useSSL ? 'https://' : 'http://') + host;

    var port = config.api.port;
    if (port !== 80 && port !== 443) {
        baseUrl += ':' + port;
    }

    baseUrl += '/' + config.api.version;

    return config;
}
1171552
function setup() {

    // check if config directory is given
    if( _config_path !== -1 ) {

      // get path
      var config_path = path.resolve( process.argv[ _config_path + 1 ] );

      // check if directory exists and is a valid directory
      fs.stat( config_path, function( err, stats ) {
        if( err && err.code === "ENOENT" ) {
          process.stdout.write( "The given directory doesn't exists.\n".red );
        } else if( err ) {

          // unknown error
          process.stdout.write( (err.message + "\n").red );
        } else if( !stats.isDirectory() ) {
          process.stdout.write( "The given config directory is not an actual directory.\n".red );
        } else {
          readConfigDir( config_path );
        }
      } );
      return;
    }

    // ask for config directory
    ask( "Where are your config files? ", function( c_path ) {
        readConfigDir( c_path );
    } );
}
135790
def generate_tokens(self):
        """"""
        if self._io_error:
            self.report_error(1, 0, 'E902 %s' % self._io_error, readlines)
        tokengen = tokenize.generate_tokens(self.readline)
        try:
            for token in tokengen:
                if token[2][0] > self.total_lines:
                    return
                self.noqa = token[4] and noqa(token[4])
                self.maybe_check_physical(token)
                yield token
        except (SyntaxError, tokenize.TokenError):
            self.report_invalid_syntax()
294947
def _generateForTokenSecurity(self,
                                  username, password,
                                  tokenUrl,
                                  expiration=None,
                                  client='requestip'):
        

        query_dict = {'username': username,
                      'password': password,
                      'expiration':str(_defaultTokenExpiration),
                      'client': client,
                      'f': 'json'}
        if client == "referer":
            query_dict['referer'] = self._referer_url
        if expiration is not None:
            query_dict['expiration'] = expiration

        secHandler = None
        if self.cookiejar is not None:
            secHandler = self
            if secHandler is not None:
                secHandler._method = "HANDLER"
        token = self._post(url=tokenUrl,
                           param_dict=query_dict,
                           securityHandler=secHandler,
                           proxy_port=self._proxy_port,
                           proxy_url=self._proxy_url)
        if self.cookiejar is not None:
            if secHandler is not None:
                secHandler._method = "TOKEN"
        if 'error' in token:
            self._token = None
            self._token_created_on = None
            self._token_expires_on = None
            self._expires_in = None

            return token
        elif 'status' in token:
            self._token = None
            self._token_created_on = None
            self._token_expires_on = None
            self._expires_in = None
            #print token['message']
            return token

        else:
            self._token = token['token']
            self._token_created_on = datetime.datetime.now()
            self._token_expires_on = datetime.datetime.fromtimestamp(token['expires'] /1000) - \
                datetime.timedelta(seconds=1)
            self._expires_in = (self._token_expires_on - self._token_created_on).total_seconds()
            return token['token']
304489
def generate(command,
             name,
             init_system,
             overwrite,
             deploy,
             start,
             verbose,
             **params):
    
    # TODO: Add a `prefix` flag which can be used to prefix
    # `COMMAND` with `su -c`, etc..
    try:
        Serv(init_system, verbose=verbose).generate(
            command, name, overwrite, deploy, start, **params)
    except ServError as ex:
        sys.exit(ex)
1193113
def generateSetupFile(self, outpath='.', egg=False):
        
        outpath = os.path.abspath(outpath)
        outfile = os.path.join(outpath, 'setup.py')

        opts = {
            'name': self.name(),
            'distname': self.distributionName(),
            'version': self.version(),
            'author': self.author(),
            'author_email': self.authorEmail(),
            'keywords': self.keywords(),
            'license': self.license(),
            'brief': self.brief(),
            'description': self.description(),
            'url': self.companyUrl()
        }

        wrap_dict = lambda x: map(lambda k: "r'{0}': [{1}]".format(k[0],
                                                                   ',\n'.join(wrap_str(k[1]))),
                                  x.items())

        opts['dependencies'] = ',\n'.join(wrap_str(self.dependencies()))
        opts['classifiers'] = ',\n'.join(wrap_str(self.classifiers()))

        if os.path.isfile(self.sourcePath()):
            basepath = os.path.normpath(os.path.dirname(self.sourcePath()))
        else:
            basepath = os.path.normpath(self.sourcePath())

        self.generatePlugins(basepath)

        exts = set()
        for root, folders, files in os.walk(basepath):
            for file_ in files:
                _, ext = os.path.splitext(file_)
                if ext not in ('.py', '.pyc', '.pyo'):
                    exts.add('*' + ext)

        exts = list(exts)
        text = templ.SETUPFILE.format(**opts)

        # generate the file
        if not os.path.exists(outfile):
            f = open(outfile, 'w')
            f.write(text)
            f.close()

        # generate the manifest file
        manfile = os.path.join(outpath, 'MANIFEST.in')
        if not os.path.exists(manfile):
            f = open(manfile, 'w')
            f.write('include *.md *.txt *.ini *.cfg *.rst\n')
            f.write('recursive-include {0} {1}\n'.format(self.name(), ' '.join(exts)))
            f.close()

        # generate the egg
        if egg:
            cmd = 'cd {0} && $PYTHON setup.py bdist_egg'.format(outpath)
            cmd = os.path.expandvars(cmd)
            cmdexec(cmd)
1170888
def make_bench_generate_token(alg):
    
    def f(_):
        """ Generate token """
        privk = priv_keys[alg].get('default', priv_key)
        jwt.generate_jwt(payload, privk, alg, timedelta(seconds=5))
    return f
1206409
def setup (self):
        ''' 
        '''
        mainaccount = self.add_quotes(self.enter_config_value("mainaccount", 'ned'))
        keys = self.enter_config_value("keys", '[]')
        nodes = self.enter_config_value("nodes", 
                '["https://steemd.minnowsupportproject.org",'
                + '"https://rpc.buildteam.io",'
                + '"https://rpc.curiesteem.com",'
                + '"https://gtg.steem.house:8090",'
                + '"https://rpc.steemliberator.com",'
                + '"https://rpc.steemviz.com",'
                + '"https://steemd.privex.io"]')
        client_id = self.add_quotes(self.enter_config_value("client_id"))
        client_secret = self.add_quotes(self.enter_config_value("client_secret"))
        callback_url = self.add_quotes(self.enter_config_value("callback_url"))
        permissions = self.add_quotes(self.enter_config_value("permissions", "login,offline,vote"))
        logpath = self.add_quotes(self.enter_config_value("logpath", ""))
        screenmode = self.add_quotes(self.enter_config_value("screenmode", "quiet"))
        self.make(mainaccount=mainaccount, keys=keys, nodes=nodes, client_id=client_id, 
            client_secret=client_secret, callback_url=callback_url, permissions=permissions,
            logpath=logpath, screenmode=screenmode)
524318
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token), function(err) {
    if (err) throw err;
    console.log('Token stored to ' + TOKEN_PATH);
  });
}