// Client returns clients for accessing github. func (c *Config) Clients() (*Clients, error) { orgClient := github.NewClient( oauth2.NewClient( oauth2.NoContext, oauth2.StaticTokenSource( &oauth2.Token{ AccessToken: c.OrganizationKey, }, ), ), ) userClient := github.NewClient( oauth2.NewClient( oauth2.NoContext, oauth2.StaticTokenSource( &oauth2.Token{ AccessToken: c.UserKey, }, ), ), ) return &Clients{ OrgClient: orgClient, UserClient: userClient, }, nil }
func main() { log.SetFlags(0) plugin.Param("workspace", &workspace) plugin.Param("build", &build) plugin.Param("repo", &repo) plugin.Param("vargs", &vargs) plugin.MustParse() sort.Strings(vargs.Gzip) // need for matchGzip // context for all clients ctx := context.Background() // GitHub client gts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: vargs.GitHubToken}) client.ghub = github.NewClient(oauth2.NewClient(ctx, gts)) // GCS client auth, err := google.JWTConfigFromJSON([]byte(vargs.AuthKey), storage.ScopeFullControl) if err != nil { fatalf("auth: %v", err) } tsrc := auth.TokenSource(ctx) client.gcs, err = storage.NewClient(ctx, cloud.WithTokenSource(auth.TokenSource(ctx))) if err != nil { fatalf("storage client: %v", err) } // http client with service account authorization client.http = oauth2.NewClient(ctx, tsrc) run() if ecode != 0 { msg := fmt.Sprintf("exited with code %d", ecode) updateStatus("error", msg, stagingURL) } os.Exit(ecode) }
// NewClient returns a new client func NewClient(config *Config) (client *Client, err error) { // bootstrap the config defConfig := DefaultConfig() if len(config.ApiAddress) == 0 { config.ApiAddress = defConfig.ApiAddress } if len(config.Username) == 0 { config.Username = defConfig.Username } if len(config.Password) == 0 { config.Password = defConfig.Password } if len(config.Token) == 0 { config.Token = defConfig.Token } ctx := oauth2.NoContext if config.SkipSslValidation == false { ctx = context.WithValue(ctx, oauth2.HTTPClient, defConfig.HttpClient) } else { tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } ctx = context.WithValue(ctx, oauth2.HTTPClient, &http.Client{Transport: tr}) } endpoint, err := getInfo(config.ApiAddress, oauth2.NewClient(ctx, nil)) if err != nil { return nil, fmt.Errorf("Could not get api /v2/info: %v", err) } authConfig := &oauth2.Config{ ClientID: "cf", Scopes: []string{""}, Endpoint: oauth2.Endpoint{ AuthURL: endpoint.AuthEndpoint + "/oauth/auth", TokenURL: endpoint.TokenEndpoint + "/oauth/token", }, } token, err := authConfig.PasswordCredentialsToken(ctx, config.Username, config.Password) if err != nil { return nil, fmt.Errorf("Error getting token: %v", err) } config.TokenSource = authConfig.TokenSource(ctx, token) config.HttpClient = oauth2.NewClient(ctx, config.TokenSource) client = &Client{ config: *config, Endpoint: *endpoint, } return client, nil }
func mainhandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") ctx := appengine.NewContext(r) //src := google.AppEngineTokenSource(ctx, oauthsvc.UserinfoEmailScope) src, err := google.DefaultTokenSource(ctx, oauthsvc.UserinfoEmailScope) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } client := &http.Client{ Transport: &oauth2.Transport{ Source: src, Base: &urlfetch.Transport{Context: ctx}, }, } client = oauth2.NewClient(ctx, src) service, err := oauthsvc.New(client) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } ui, err := service.Userinfo.Get().Do() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } log.Infof(ctx, "UserInfo: %v", ui.Email) fmt.Fprintln(w, "UserInfo: ", ui.Email) }
func GetOauthClient(token string) *http.Client { tokenSource := &TokenSource{ AccessToken: token, } return oauth2.NewClient(oauth2.NoContext, tokenSource) }
func GetClient() *godo.Client { token := &oauth2.Token{AccessToken: token} t := oauth2.StaticTokenSource(token) oauthClient := oauth2.NewClient(oauth2.NoContext, t) return godo.NewClient(oauthClient) }
func init() { flag.BoolVar(&isVerbose, "v", false, "") flag.BoolVar(&isVerbose, "verbose", false, "") flag.Usage = func() { fmt.Println(path.Base(os.Args[0]), "- Print DNSPOD table changes") fmt.Println() fmt.Println("Options:") fmt.Println(" -v, --verbose Show more output") fmt.Println() fmt.Println("Source: https://github.com/caiguanhao/dnspodd") } flag.Parse() githubClient = github.NewClient(oauth2.NewClient(oauth2.NoContext, oauth2.StaticTokenSource( &oauth2.Token{AccessToken: string(GITHUB_TOKEN)}, ))) if PROXY_URL != "" { proxy, err := url.Parse(PROXY_URL) if err == nil { http.DefaultTransport = &http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { if req.URL.Host == "api.github.com" { return proxy, nil } return nil, nil }, } } } }
func init() { bucket := os.Getenv("REGISTRY_STORAGE_GCS_BUCKET") credentials := os.Getenv("GOOGLE_APPLICATION_CREDENTIALS") // Skip GCS storage driver tests if environment variable parameters are not provided skipGCS = func() string { if bucket == "" || credentials == "" { return "The following environment variables must be set to enable these tests: REGISTRY_STORAGE_GCS_BUCKET, GOOGLE_APPLICATION_CREDENTIALS" } return "" } if skipGCS() != "" { return } root, err := ioutil.TempDir("", "driver-") if err != nil { panic(err) } defer os.Remove(root) var ts oauth2.TokenSource var email string var privateKey []byte ts, err = google.DefaultTokenSource(ctx.Background(), storage.ScopeFullControl) if err != nil { // Assume that the file contents are within the environment variable since it exists // but does not contain a valid file path jwtConfig, err := google.JWTConfigFromJSON([]byte(credentials), storage.ScopeFullControl) if err != nil { panic(fmt.Sprintf("Error reading JWT config : %s", err)) } email = jwtConfig.Email privateKey = []byte(jwtConfig.PrivateKey) if len(privateKey) == 0 { panic("Error reading JWT config : missing private_key property") } if email == "" { panic("Error reading JWT config : missing client_email property") } ts = jwtConfig.TokenSource(ctx.Background()) } gcsDriverConstructor = func(rootDirectory string) (storagedriver.StorageDriver, error) { parameters := driverParameters{ bucket: bucket, rootDirectory: root, email: email, privateKey: privateKey, client: oauth2.NewClient(ctx.Background(), ts), } return New(parameters) } testsuites.RegisterSuite(func() (storagedriver.StorageDriver, error) { return gcsDriverConstructor(root) }, skipGCS) }
// NewProtoClient returns a ProtoClient for communicating with a Google cloud service, // configured with the given ClientOptions. func NewProtoClient(ctx context.Context, opt ...cloud.ClientOption) (*ProtoClient, error) { var o opts.DialOpt for _, opt := range opt { opt.Resolve(&o) } if o.GRPCClient != nil { return nil, errors.New("unsupported GRPC base transport specified") } var client *http.Client switch { case o.HTTPClient != nil: if o.TokenSource != nil { return nil, errors.New("at most one of WithTokenSource or WithBaseHTTP may be provided") } client = o.HTTPClient case o.TokenSource != nil: client = oauth2.NewClient(ctx, o.TokenSource) default: var err error client, err = google.DefaultClient(ctx, o.Scopes...) if err != nil { return nil, err } } return &ProtoClient{ client: client, endpoint: o.Endpoint, userAgent: o.UserAgent, }, nil }
func getClient(token string) *github.Client { ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: token}, ) tc := oauth2.NewClient(oauth2.NoContext, ts) return github.NewClient(tc) }
// DefaultClient returns an HTTP Client that uses the // DefaultTokenSource to obtain authentication credentials. // // This client should be used when developing services // that run on Google App Engine or Google Compute Engine // and use "Application Default Credentials." // // For more details, see: // https://developers.google.com/accounts/docs/application-default-credentials // func DefaultClient(ctx context.Context, scope ...string) (*http.Client, error) { ts, err := DefaultTokenSource(ctx, scope...) if err != nil { return nil, err } return oauth2.NewClient(ctx, ts), nil }
// New returns a new instance of DoImages func New(conf *DoConfig) (*DoImages, error) { if conf.Token == "" { return nil, errors.New("Access Token is not set. Please check your configuration.") } // increase the timeout timeout := time.Second * 30 client := &http.Client{ Transport: &http.Transport{TLSHandshakeTimeout: timeout}, Timeout: timeout, } // we need to pass the client with the context itself ctx := context.WithValue(oauth2.NoContext, oauth2.HTTPClient, client) oauthClient := oauth2.NewClient(ctx, &tokenSource{ AccessToken: conf.Token, }) godoClient := godo.NewClient(oauthClient) return &DoImages{ client: godoClient, images: make([]godo.Image, 0), }, nil }
// VerifyCredential verifies whether the users DO credentials (access token) is // valid or not func (s *Stack) VerifyCredential(c *stack.Credential) error { cred := c.Credential.(*Credential) if err := cred.Valid(); err != nil { return err } oauthClient := oauth2.NewClient( oauth2.NoContext, oauth2.StaticTokenSource(&oauth2.Token{AccessToken: cred.AccessToken}), ) client := godo.NewClient(oauthClient) // let's retrieve our Account information. If it's successful, we're good // to go _, _, err := client.Account.Get() if err != nil { return &stack.Error{ Err: err, } } return nil }
func authWithGitHub(tkn string) *github.Client { ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: tkn}, ) tc := oauth2.NewClient(oauth2.NoContext, ts) return github.NewClient(tc) }
// Reads google storage config and creates a Client. Exits on error. func doConfig(t *testing.T) (gsa *Client, bucket string) { if *gsConfigPath == "" { t.Skip("Skipping manual test. Set flag --gs_config_path to test Google Storage.") } cf, err := osutil.NewJSONConfigParser().ReadFile(*gsConfigPath) if err != nil { t.Fatalf("Failed to read config: %v", err) } var config jsonconfig.Obj config = cf.RequiredObject("gsconf") if err := cf.Validate(); err != nil { t.Fatalf("Invalid config: %v", err) } auth := config.RequiredObject("auth") bucket = config.RequiredString("bucket") if err := config.Validate(); err != nil { t.Fatalf("Invalid config: %v", err) } gsa = NewClient(oauth2.NewClient(oauth2.NoContext, oauthutil.NewRefreshTokenSource(&oauth2.Config{ Scopes: []string{Scope}, Endpoint: google.Endpoint, ClientID: auth.RequiredString("client_id"), ClientSecret: auth.RequiredString("client_secret"), RedirectURL: oauthutil.TitleBarRedirectURL, }, auth.RequiredString("refresh_token")))) if err := auth.Validate(); err != nil { t.Fatalf("Invalid config: %v", err) } return }
// newSlackServer returns an http handler for handling Slack slash commands at <url>/slack. func newSlackServer(q conveyor.BuildQueue, c *cli.Context) http.Handler { ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: c.String("github.token")}, ) tc := oauth2.NewClient(oauth2.NoContext, ts) cy := github.NewClient(tc) r := slash.NewMux() r.Match(slash.MatchSubcommand(`help`), slack.Help) r.MatchText( regexp.MustCompile(`enable (?P<owner>\S+?)/(?P<repo>\S+)`), slack.NewEnable( cy, slack.NewHook(c.String("url"), c.String("github.secret")), ), ) r.MatchText( regexp.MustCompile(`build (?P<owner>\S+?)/(?P<repo>\S+)@(?P<branch>\S+)`), slack.NewBuild( cy, q, fmt.Sprintf(logsURLTemplate, c.String("url")), ), ) return slash.NewServer(slash.ValidateToken(r, c.String("slack.token"))) }
func maybeRemapCloudSQL(host string) (out string, err error) { if !strings.HasSuffix(host, cloudSQLSuffix) { return host, nil } inst := strings.TrimSuffix(host, cloudSQLSuffix) if !metadata.OnGCE() { return "", errors.New("CloudSQL support only available when running on Google Compute Engine.") } proj, err := metadata.ProjectID() if err != nil { return "", fmt.Errorf("Failed to lookup GCE project ID: %v", err) } admin, _ := sqladmin.New(oauth2.NewClient(context.Background(), google.ComputeTokenSource(""))) listRes, err := admin.Instances.List(proj).Do() if err != nil { return "", fmt.Errorf("error enumerating Cloud SQL instances: %v", err) } for _, it := range listRes.Items { if !strings.EqualFold(it.Instance, inst) { continue } js, _ := json.Marshal(it) log.Printf("Found Cloud SQL instance %s: %s", inst, js) for _, ipm := range it.IpAddresses { return ipm.IpAddress, nil } return "", fmt.Errorf("No external IP address for Cloud SQL instances %s", inst) } var found []string for _, it := range listRes.Items { found = append(found, it.Instance) } return "", fmt.Errorf("Cloud SQL instance %q not found. Found: %q", inst, found) }
func (gh *Client) Authenticate(username string, password string) error { var token []byte gh.User = &User{ Login: username, Password: password, } // conf := &oauth2.Config{ // Endpoint: githubOauth2.Endpoint, // } gh.Store.Get(s.ConfigBucket, "gh_token", &token) if len(token) == 0 { var err error token, err = gh.createToken() if err != nil { return errwrap.Wrapf("[Github] Authentication error: %v", err) } } ts := oauth2.StaticTokenSource( &oauth2.Token{ AccessToken: string(token), }, ) tc := oauth2.NewClient(oauth2.NoContext, ts) gh.client = github.NewClient(tc) user, _, _ := gh.client.Users.Get("") gh.User.Login = *user.Login gh.User.issues = map[string][]*github.Issue{} gh.User.Password = "" gh.Fetch() return nil }
func getVersions() ([]*github.RepositoryRelease, error) { if githubClient == nil { token := os.Getenv("GH_TOKEN") var tc *http.Client if len(token) > 0 { ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: token}, ) tc = oauth2.NewClient(oauth2.NoContext, ts) } githubClient = github.NewClient(tc) } client := githubClient releases, resp, err := client.Repositories.ListReleases(githubOwner, githubRepo, nil) if err != nil { return nil, err } defer resp.Body.Close() if len(releases) == 0 { return nil, fmt.Errorf("There were no OpenShift Releases available") } return releases, nil }
func main() { flag.Usage = usage flag.Parse() cachingHTTPClient = util.CachingHttpClient() if *tokenFlag == "" || cachingHTTPClient == nil { flag.Usage() return } ds = clientFlags.CreateDataset() if ds == nil { flag.Usage() return } defer ds.Store().Close() if err := clientFlags.CreateProgressFile(); err != nil { fmt.Println(err) } else { defer clientFlags.CloseProgressFile() } token := oauth2.Token{AccessToken: *tokenFlag} authHTTPClient = oauth2.NewClient(oauth2.NoContext, oauth2.StaticTokenSource(&token)) start = time.Now() var user = getUser() printStats(user) userRef := ds.Store().WriteValue(user) fmt.Printf("userRef: %s\n", userRef.TargetRef()) _, err := ds.Commit(userRef) d.Exp.NoError(err) }
func clientFromToken(pat string) *godo.Client { tokenSrc := &tokenSource{ AccessToken: pat, } return godo.NewClient(oauth2.NewClient(oauth2.NoContext, tokenSrc)) }
// borrowed from minishift until it supports install / download binaries func getLatestVersionFromGitHub(githubOwner, githubRepo string) (semver.Version, error) { if githubClient == nil { token := os.Getenv("GH_TOKEN") var tc *http.Client if len(token) > 0 { ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: token}, ) tc = oauth2.NewClient(oauth2.NoContext, ts) } githubClient = github.NewClient(tc) } client := githubClient var ( release *github.RepositoryRelease resp *github.Response err error ) release, resp, err = client.Repositories.GetLatestRelease(githubOwner, githubRepo) if err != nil { return semver.Version{}, err } defer resp.Body.Close() latestVersionString := release.TagName if latestVersionString != nil { return semver.Make(strings.TrimPrefix(*latestVersionString, "v")) } return semver.Version{}, fmt.Errorf("Cannot get release name") }
func (d *Driver) getClient() *godo.Client { token := &oauth2.Token{AccessToken: d.AccessToken} tokenSource := oauth2.StaticTokenSource(token) client := oauth2.NewClient(oauth2.NoContext, tokenSource) return godo.NewClient(client) }
func downloadReleaseFromGithub(r repo, artifact string, alias string) { client := github.NewClient(nil) config, err := loadConfig() if err != nil { DieWithError(err, "Could not load user config") } if token, ok := config.Config["token"]; ok { log.Debug("Using Github token from config.") // if the user has a token stored, use it ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: token}, ) tc := oauth2.NewClient(oauth2.NoContext, ts) client = github.NewClient(tc) } else { log.Debug("No Github token found in config. Add it with `mup config` if you need it") } // with a provided token, this will also get repos for the authenticated user // TODO: support pagination releases, resp, err := client.Repositories.ListReleases(r.Owner, r.Repo, nil) if resp.StatusCode == 404 { Die("Could not find repository %s/%s. Maybe it doesn't exist, or you need to add your token for μpdater to have access.", r.Owner, r.Repo) } else if err != nil { DieWithError(err, "Error reaching Github") } updateFromGithubReleases(client, r, releases, "", artifact, alias) }
func main() { ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: GITHUB_TOKEN}, ) tc := oauth2.NewClient(oauth2.NoContext, ts) githubClient := github.NewClient(tc) release, err := githubClient.Repositories.GetLatestRelease("FRC1360", "Stronghold2016") if err != nil { panic(err) } if downloadFromUrl(release.ZipballURL) { message := "Code Release Downloaded: " + release.AssetsURL + "\nSaved to Backup Server - Running copy cron job now." api := slack.New(SLACK_TOKEN) channel, err := api.FindChannelByName(SLACK_CHANNEL) if err != nil { panic(err) } err = api.ChatPostMessage(channel.Id, message, nil) if err != nil { panic(err) } } }
// retrieveCommits fetches the latest deployed commits as well // as the latest GitHub commits for a given Project. // it will also check if the user has permission to pull. func retrieveCommits(r *http.Request, project goship.Project, deployUser string) (goship.Project, error) { // define a wait group to wait for all goroutines to finish var wg sync.WaitGroup githubToken := os.Getenv(gitHubAPITokenEnvVar) ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: githubToken}) client := github.NewClient(oauth2.NewClient(oauth2.NoContext, ts)) for i, environment := range project.Environments { for j, host := range environment.Hosts { // start a goroutine for SSHing on to the machine wg.Add(1) go getCommit(&wg, project, environment, host, deployUser, i, j) } wg.Add(1) go getLatestGitHubCommit(&wg, project, environment, client, project.RepoOwner, project.RepoName, i) } // wait for goroutines to finish wg.Wait() for i, e := range project.Environments { project.Environments[i] = e for j, host := range e.Hosts { host.GitHubCommitURL = host.LatestGitHubCommitURL(project) host.GitHubDiffURL = host.LatestGitHubDiffURL(project, e) host.ShortCommitHash = host.LatestShortCommitHash() project.Environments[i].Hosts[j] = host } } u, err := getUser(r) if err != nil { log.Printf("Failed to get user %s", err) } return filterProject(project, r, u), err }
//RegisterResult registers the supplied result func (githubClient *GitHubClient) RegisterResult(result Result) error { ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: githubClient.Token}, ) tc := oauth2.NewClient(oauth2.NoContext, ts) client := github.NewClient(tc) if githubClient.BaseUrl != nil { client.BaseURL = githubClient.BaseUrl } log.Info("Submitting result") repositories := client.Repositories status, _, err := repositories.CreateStatus( githubClient.From, githubClient.Repo, result.SHA, &github.RepoStatus{ State: github.String(result.State), TargetURL: github.String(result.Url), Description: github.String(result.Message), Context: github.String("continuous-integraion/walter"), }) log.Infof("Submit status: %s", status) if err != nil { log.Errorf("Failed to register result: %s", err) } return err }
func insertEntry(env, owner, repoName, fromRevision, toRevision, user string, success bool, time time.Time) error { path := path.Join(*dataPath, env+".json") err := prepareDataFiles(path) if err != nil { return err } e, err := readEntries(env) if err != nil { return err } gt := os.Getenv(gitHubAPITokenEnvVar) ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: gt}) c := github.NewClient(oauth2.NewClient(oauth2.NoContext, ts)) com, _, err := c.Git.GetCommit(owner, repoName, toRevision) if err != nil { log.Println("Error getting commit msg: ", err) } var m string if com.Message != nil { m = *com.Message } diffURL := diffURL(owner, repoName, fromRevision, toRevision) d := DeployLogEntry{DiffURL: diffURL, ToRevisionMsg: m, User: user, Time: time, Success: success} e = append(e, d) err = writeJSON(e, path) if err != nil { return err } return nil }
func gistHandler(w http.ResponseWriter, r *http.Request) { log.Debug("gistHandler()") // get access token c, err := r.Cookie("access_token") if err != nil { log.Error("get cookie error: ", err) http.Error(w, "Github Auth Error", http.StatusInternalServerError) return } ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: c.Value}, ) tc := oauth2.NewClient(oauth2.NoContext, ts) // github api client := github.NewClient(tc) gist, err := makeGist(r.Body) if err != nil { log.Errorf("make gist error: %v", err) http.Error(w, "Server Error", http.StatusInternalServerError) return } retGist, _, err := client.Gists.Create(&gist) if err != nil { log.Error("create gist error: ", err) http.Error(w, "Post Gist Error", http.StatusInternalServerError) return } io.WriteString(w, *retGist.HTMLURL) }
func (pc *NodeController) getNodeAddDOAction(c *gin.Context) { a, err := models.AccessMapper.FetchOne("do") if err != nil { panic(err) } if a == nil { c.HTML(http.StatusOK, "node_add_do.html", map[string]interface{}{}) return } oauthClient := oauth2.NewClient(oauth2.NoContext, &DOTokenSource{ AccessToken: a.AccessKey, }) client := godo.NewClient(oauthClient) regions, _, err := client.Regions.List(&godo.ListOptions{}) if err != nil { panic(err) } sizes, _, err := client.Sizes.List(&godo.ListOptions{}) if err != nil { panic(err) } c.HTML(http.StatusOK, "node_add_do.html", map[string]interface{}{ "AccessKey": true, "DORegions": regions, "DOSizes": sizes, }) }