Setup OAuth2 instance
519693
def client
      @client ||= ::OAuth2::Client.new(client_id, client_secret,
        {
          :site          => current_options.fetch(:site) { Github.site },
          :authorize_url => 'login/oauth/authorize',
          :token_url     => 'login/oauth/access_token',
          :ssl           => { :verify => false }
        }
      )
    end
10543
def oauth2(self):
        
        if self._url.endswith("/oauth2"):
            url = self._url
        else:
            url = self._url + "/oauth2"
        return _oauth2.oauth2(oauth_url=url,
                              securityHandler=self._securityHandler,
                              proxy_url=self._proxy_url,
                              proxy_port=self._proxy_port)
1001287
def _launch_instance(self):
        """"""
        resource = self._connect()

        instance_name = ipa_utils.generate_instance_name('ec2-ipa-test')
        kwargs = {
            'InstanceType': self.instance_type or EC2_DEFAULT_TYPE,
            'ImageId': self.image_id,
            'MaxCount': 1,
            'MinCount': 1,
            'TagSpecifications': [
                {
                    'ResourceType': 'instance',
                    'Tags': [
                        {
                            'Key': 'Name',
                            'Value': instance_name
                        }
                    ]
                }
            ]
        }

        if self.zone:
            kwargs['Placement'] = {'AvailabilityZone': self.zone}

        if self.ssh_key_name:
            kwargs['KeyName'] = self.ssh_key_name
        else:
            kwargs['UserData'] = self._get_user_data()

        if self.subnet_id:
            kwargs['SubnetId'] = self.subnet_id

        if self.security_group_id:
            kwargs['SecurityGroupIds'] = [self.security_group_id]

        try:
            instances = resource.create_instances(**kwargs)
        except Exception as error:
            raise EC2CloudException(
                'Unable to create instance: {0}.'.format(error)
            )

        self.running_instance_id = instances[0].instance_id
        self.logger.debug('ID of instance: %s' % self.running_instance_id)
        self._wait_on_instance('running', self.timeout)
157406
async function authenticate(scopes) {
  return new Promise((resolve, reject) => {
    // grab the url that will be used for authorization
    const authorizeUrl = oauth2Client.generateAuthUrl({
      access_type: 'offline',
      scope: scopes.join(' '),
    });
    const server = http
      .createServer(async (req, res) => {
        try {
          if (req.url.indexOf('/oauth2callback') > -1) {
            const qs = new url.URL(req.url, 'http://localhost:3000')
              .searchParams;
            res.end('Authentication successful! Please return to the console.');
            server.destroy();
            const {tokens} = await oauth2Client.getToken(qs.get('code'));
            oauth2Client.credentials = tokens;
            resolve(oauth2Client);
          }
        } catch (e) {
          reject(e);
        }
      })
      .listen(3000, () => {
        // open the browser to the authorize url to start the workflow
        opn(authorizeUrl, {wait: false}).then(cp => cp.unref());
      });
    destroyer(server);
  });
}
829460
def oauthgetm(method, param_dict, socket_timeout=None):
    try:
        import oauth2 # lazy import this so oauth2 is not a hard dep
    except ImportError:
        raise Exception("You must install the python-oauth2 library to use this method.")

    
    def build_request(url):
        params = {
            'oauth_version': "1.0",
            'oauth_nonce': oauth2.generate_nonce(),
            'oauth_timestamp': int(time.time())
            }
        consumer = oauth2.Consumer(key=config.ECHO_NEST_CONSUMER_KEY, secret=config.ECHO_NEST_SHARED_SECRET)
        params['oauth_consumer_key'] = config.ECHO_NEST_CONSUMER_KEY
        
        req = oauth2.Request(method='GET', url=url, parameters=params)
        signature_method = oauth2.SignatureMethod_HMAC_SHA1()
        req.sign_request(signature_method, consumer, None)
        return req
    
    param_dict['api_key'] = config.ECHO_NEST_API_KEY
    param_list = []
    if not socket_timeout:
        socket_timeout = config.CALL_TIMEOUT
    
    for key,val in param_dict.iteritems():
        if isinstance(val, list):
            param_list.extend( [(key,subval) for subval in val] )
        elif val is not None:
            if isinstance(val, unicode):
                val = val.encode('utf-8')
            param_list.append( (key,val) )

    params = urllib.urlencode(param_list)
    
    orig_timeout = socket.getdefaulttimeout()
    socket.setdefaulttimeout(socket_timeout)
    """
    just a normal GET call
    """
    url = 'http://%s/%s/%s/%s?%s' % (config.API_HOST, config.API_SELECTOR, config.API_VERSION, 
                                     method, params)
    req = build_request(url)
    f = opener.open(req.to_url())
            
    socket.setdefaulttimeout(orig_timeout)
    
    # try/except
    response_dict = get_successful_response(f)
    return response_dict
1195310
def authenticate():
    

    print LOGIN_INIT_MESSAGE

    username = raw_input('{0}: '.format(LOGIN_USER_MESSAGE))
    password = None

    while password is None:
        password = getpass('Password for {0}: '.format(username))

    gh = login(username, password=password)
    try:
        gh.user()
        instance = authorize(username, password, APP_SCOPE, APP_DESC, APP_URL)
    except Exception, e:
        raise e

    with open(credentials_file, 'w') as f:
        f.write(instance.token)

    return instance.token
258148
function getAuthenticationUrl(scopes, clientId, clientSecret, redirectUri = 'urn:ietf:wg:oauth:2.0:oob') {
	const oauth2Client = new OAuth2(
		clientId,
		clientSecret,
		redirectUri
	);
	const url = oauth2Client.generateAuthUrl({
		access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
		scope: scopes // If you only need one scope you can pass it as string
	});
	return url;
}
738024
def __initialize_instance(self):
        
        config = self.config

        # Initialize instance of the Authentication class
        self.instance.auth = self.authentication_class(self.app, config=config)

        init_handlers = (
            handlers if config.auth_mode() else auth_mode_agnostic_handlers
        )

        for handler in init_handlers:
            if handler.keys is None:
                self.__check_method_in_auth(handler.name, handler.exception)
            else:
                if all(map(config.get, handler.keys)):
                    self.__check_method_in_auth(
                        handler.name, handler.exception
                    )

        for handler in init_handlers:
            if handler.name in self.kwargs:
                method = self.kwargs.pop(handler.name)
                setattr(self.instance.auth, handler.name, method)
204079
def _authorize_new_tokens(self):
        '''
        
        '''
        logging.info('About to request new OAuth2 tokens from Coursera.')
        # Attempt to request new tokens from Coursera via the browser.
        state_token = uuid.uuid4().hex
        authorization_url = self._build_authorizaton_url(state_token)

        sys.stdout.write(
            'Please visit the following URL to authorize this app:\n')
        sys.stdout.write('\t%s\n\n' % authorization_url)
        if _platform == 'darwin':
            # OS X -- leverage the 'open' command present on all modern macs
            sys.stdout.write(
                'Mac OS X detected; attempting to auto-open the url '
                'in your default browser...\n')
            try:
                subprocess.check_call(['open', authorization_url])
            except:
                logging.exception('Could not call `open %(url)s`.',
                                  url=authorization_url)

        if self.local_webserver_port is not None:
            # Boot up a local webserver to retrieve the response.
            server_address = ('', self.local_webserver_port)
            code_holder = CodeHolder()

            local_server = BaseHTTPServer.HTTPServer(
                server_address,
                _make_handler(state_token, code_holder))

            while not code_holder.has_code():
                local_server.handle_request()
            coursera_code = code_holder.code
        else:
            coursera_code = raw_input('Please enter the code from Coursera: ')

        form_data = {
            'code': coursera_code,
            'client_id': self.client_id,
            'client_secret': self.client_secret,
            'redirect_uri': self._redirect_uri,
            'grant_type': 'authorization_code',
        }
        return self._request_tokens_from_token_endpoint(form_data)
743945
def oauth_token_create(self, data, **kwargs):
        ""
        api_path = "/api/v2/oauth/tokens.json"
        return self.call(api_path, method="POST", data=data, **kwargs)
98284
def setup_dotcloud_account(cli):
    """"""
    client = RESTClient(endpoint=cli.client.endpoint)
    client.authenticator = NullAuth()
    urlmap = client.get('/auth/discovery').item
    username = cli.prompt('dotCloud email')
    password = cli.prompt('Password', noecho=True)
    credential = {'token_url': urlmap.get('token'),
        'key': CLIENT_KEY, 'secret': CLIENT_SECRET}
    try:
        token = cli.authorize_client(urlmap.get('token'), credential, username, password)
    except Exception as e:
        cli.die('Username and password do not match. Try again.')
    token['url'] = credential['token_url']
    config = GlobalConfig()
    config.data = {'token': token}
    config.save()
    cli.global_config = GlobalConfig()  # reload
    cli.setup_auth()
    cli.get_keys()
1148906
private function setupGoogleClient()
    {
        $client = new Google_Client();

        $client->setClientId($this->getConfig('oauth2_client_id'));
        $client->setClientSecret($this->getConfig('oauth2_client_secret'));
        $client->setRedirectUri($this->getConfig('oauth2_redirect_uri'));
        $client->setScopes($this->getConfig('services'));
        $client->setAccessType($this->getConfig('access_type'));
        $client->setApprovalPrompt($this->getConfig('approval_prompt'));

        return $client;
    }
522824
def setup(cls, client_id, client_secret):
        
        cls.client_id = client_id
        cls.client_secret = client_secret
432720
async function authenticate(options) {
    const tokenFile = path.join(constants.GLOBAL_DIR, constants.GLOBAL_TOKEN);
    const configFile = path.join(constants.GLOBAL_DIR, constants.GLOBAL_CONFIG);

    // Ensure a config file exists
    if (!fs.pathExistsSync(configFile)) {
        createFile({
            name: configFile,
            source: `{}\n`,
        });
    }

    // Remove the token file if we are forcing reauth
    if (options.force) {
        fs.removeSync(tokenFile);
    }

    // get Oauth client
    const oauth2ClientResult = await getAuthClient();
    const oauth2Client = oauth2ClientResult.client;
    const isCustomClient = oauth2ClientResult.custom;
    let newOauth2Client;

    // Check if we have previously stored a token.
    let token;
    try {
        token = fs.readFileSync(tokenFile, 'utf8');
    } catch (err) {
        newOauth2Client = await getNewToken(oauth2Client, isCustomClient, options);
        await firebase.setUserInfo(newOauth2Client);
        return newOauth2Client;
    }

    // If we can find the token, refresh it, get a new one or do nothing
    const tokenObject = JSON.parse(token);
    oauth2Client.credentials = tokenObject;
    const ttl = oauth2Client.credentials.expiry_date - Date.now();

    if (ttl < 10 * 1000 || options.refresh) {
        try {
            newOauth2Client = await getToken(null, token, oauth2Client, isCustomClient);
            await firebase.setUserInfo(newOauth2Client);
            return newOauth2Client;
        } catch (err) {
            newOauth2Client = await getNewToken(oauth2Client, isCustomClient, options);
            await firebase.setUserInfo(newOauth2Client);
            return newOauth2Client;
        }
    } else {
        return oauth2Client;
    }
}
467431
function oauth(id, username, email, req, done) {
	if (req.params["0"] === "/link") {
		return done(null, {
			__linkUser: true,
			email: email,
			username: username,
			id: id
		});
	}
	fileUtil.getMetastoreSafe(req).then(function(store) {
		store.getUserByOAuth(id, function(err, user) {
			if (err) {
				return done(err);
			}
			if (!user) {
				return done(null, {
					__newUser: true,
					email: email,
					username: username,
					id: id
				});
			}
			done(null, user);
		}, function noMetastore(err) {
			done(err);
		});
	});
}
533752
def set_auth(uri, username = nil, password = nil)
      connection = Faraday.new url: uri, ssl: {verify: false} do |faraday|
        faraday.adapter http_engine
        faraday.proxy(ENV['http_proxy']) if ENV['http_proxy']
      end
      connection.basic_auth username, password if username
      connection
    end
19791
def client
      @client ||= ::OAuth2::Client.new(GoogleAPI.client_id, GoogleAPI.client_secret,
        site: 'https://accounts.google.com',
        token_url: '/o/oauth2/token',
        raise_errors: false
      )
    end