Debian Codegraph @

plugins/gnostic-go-generator/examples/googleauth/googleauth.go

raw symbols SCIP
1 //
2 // Copyright 2017 Google Inc. All Rights Reserved.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 package googleauth
18
19 import (
20 "encoding/json"
21 "errors"
22 "flag"
23 "fmt"
24 "io/ioutil"
25 "net"
26 "net/http"
27 "os"
28 "os/exec"
29 "path/filepath"
30 "runtime"
31
32 "golang.org/x/net/context"
33 "golang.org/x/oauth2"
34 )
35
36 const missingClientSecretsMessage = `
37 Please configure OAuth 2.0
38
39 To make this sample run, you need to populate the client_secrets.json file
40 found at:
41
42 %v
43
44 with information from the {{ Google Cloud Console }}
45 {{ https://cloud.google.com/console }}
46
47 For more information about the client_secrets.json file format, please visit:
48 https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
49 `
50
51 var (
52 clientSecretsFile = flag.String("secrets", "client_secrets.json", "Client Secrets configuration")
53 cacheFile = flag.String("cache", "request.token", "Token cache file")
54 )
55
56 // ClientConfig is a data structure definition for the client_secrets.json file.
57 // The code unmarshals the JSON configuration file into this structure.
58 type ClientConfig struct {
59 ClientID string `json:"client_id"`
60 ClientSecret string `json:"client_secret"`
61 RedirectURIs []string `json:"redirect_uris"`
62 AuthURI string `json:"auth_uri"`
63 TokenURI string `json:"token_uri"`
64 }
65
66 // Config is a root-level configuration object.
67 type Config struct {
68 Installed ClientConfig `json:"installed"`
69 Web ClientConfig `json:"web"`
70 }
71
72 // openURL opens a browser window to the specified location.
73 // This code originally appeared at:
74 // http://stackoverflow.com/questions/10377243/how-can-i-launch-a-process-that-is-not-a-file-in-go
75 func openURL(url string) error {
76 var err error
77 switch runtime.GOOS {
78 case "linux":
79 err = exec.Command("xdg-open", url).Start()
80 case "windows":
81 err = exec.Command("rundll32", "url.dll,FileProtocolHandler", "http://localhost:4001/").Start()
82 case "darwin":
83 err = exec.Command("open", url).Start()
84 default:
85 err = fmt.Errorf("Cannot open URL %s on this platform", url)
86 }
87 return err
88 }
89
90 // readConfig reads the configuration from clientSecretsFile.
91 // It returns an oauth configuration object for use with the Google API client.
92 func readConfig(scopes []string) (*oauth2.Config, error) {
93 // Read the secrets file
94 data, err := ioutil.ReadFile(*clientSecretsFile)
95 if err != nil {
96 pwd, _ := os.Getwd()
97 fullPath := filepath.Join(pwd, *clientSecretsFile)
98 return nil, fmt.Errorf(missingClientSecretsMessage, fullPath)
99 }
100
101 cfg := new(Config)
102 err = json.Unmarshal(data, &cfg)
103 if err != nil {
104 return nil, err
105 }
106
107 var redirectURI string
108 if len(cfg.Web.RedirectURIs) > 0 {
109 redirectURI = cfg.Web.RedirectURIs[0]
110 } else if len(cfg.Installed.RedirectURIs) > 0 {
111 redirectURI = cfg.Installed.RedirectURIs[0]
112 } else {
113 return nil, errors.New("Must specify a redirect URI in config file or when creating OAuth client")
114 }
115
116 return &oauth2.Config{
117 ClientID: cfg.Installed.ClientID,
118 ClientSecret: cfg.Installed.ClientSecret,
119 Scopes: scopes,
120 Endpoint: oauth2.Endpoint{cfg.Installed.AuthURI, cfg.Installed.TokenURI},
121 RedirectURL: redirectURI,
122 }, nil
123 }
124
125 // startWebServer starts a web server that listens on http://localhost:8080.
126 // The webserver waits for an oauth code in the three-legged auth flow.
127 func startWebServer() (codeCh chan string, err error) {
128 listener, err := net.Listen("tcp", "localhost:8080")
129 if err != nil {
130 return nil, err
131 }
132 codeCh = make(chan string)
133 go http.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
134 code := r.FormValue("code")
135 codeCh <- code // send code to OAuth flow
136 listener.Close()
137 w.Header().Set("Content-Type", "text/plain")
138 fmt.Fprintf(w, "Received code: %v\r\nYou can now safely close this browser window.", code)
139 }))
140 return codeCh, nil
141 }
142
143 // NewOAuth2Client takes the user through the three-legged OAuth flow.
144 // It opens a browser in the native OS or outputs a URL, then blocks until
145 // the redirect completes to the /oauth2callback URI.
146 // It returns an instance of an HTTP client that can be passed to the
147 // constructor of an OAuth client.
148 // scopes is a variable number of OAuth scopes
149 func NewOAuth2Client(scopes ...string) (*http.Client, error) {
150 var ctx context.Context
151 tokenSource, err := NewOAuth2TokenSource(scopes...)
152 if err == nil {
153 return oauth2.NewClient(ctx, tokenSource), nil
154 }
155 return nil, err
156 }
157
158 // NewOAuth2TokenSource takes the user through the three-legged OAuth flow.
159 // It opens a browser in the native OS or outputs a URL, then blocks until
160 // the redirect completes to the /oauth2callback URI.
161 // It returns an instance of an OAuth token source that can be passed to the
162 // constructor of an OAuth client.
163 // scopes is a variable number of OAuth scopes
164 func NewOAuth2TokenSource(scopes ...string) (oauth2.TokenSource, error) {
165 config, err := readConfig(scopes)
166 if err != nil {
167 msg := fmt.Sprintf("Cannot read configuration file: %v", err)
168 return nil, errors.New(msg)
169 }
170
171 var ctx context.Context
172
173 // Try to read the token from the cache file.
174 // If an error occurs, do the three-legged OAuth flow because
175 // the token is invalid or doesn't exist.
176 //token, err := config.TokenCache.Token()
177
178 var token *oauth2.Token
179
180 data, err := ioutil.ReadFile(*cacheFile)
181 if err == nil {
182 err = json.Unmarshal(data, &token)
183 }
184 if (err != nil) || !token.Valid() {
185 // Start web server.
186 // This is how this program receives the authorization code
187 // when the browser redirects.
188 codeCh, err := startWebServer()
189 if err != nil {
190 return nil, err
191 }
192
193 // Open url in browser
194 url := config.AuthCodeURL("")
195 err = openURL(url)
196 if err != nil {
197 fmt.Println("Visit the URL below to get a code.",
198 " This program will pause until the site is visted.")
199 } else {
200 fmt.Println("Your browser has been opened to an authorization URL.",
201 " This program will resume once authorization has been provided.\n")
202 }
203 fmt.Println(url)
204
205 // Wait for the web server to get the code.
206 code := <-codeCh
207
208 // This code caches the authorization code on the local
209 // filesystem, if necessary, as long as the TokenCache
210 // attribute in the config is set.
211 token, err = config.Exchange(ctx, code)
212 if err != nil {
213 return nil, err
214 }
215
216 data, err := json.Marshal(token)
217 ioutil.WriteFile(*cacheFile, data, 0644)
218 }
219 return oauth2.StaticTokenSource(token), nil
220 }