1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
| package main
import (
"context"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"golang.org/x/oauth2"
)
const htmlIndex = `<html><body>
<a href="/GoogleLogin">Log in with Google</a>
</body></html>
`
var endpotin = oauth2.Endpoint{
AuthURL: "https://accounts.google.com/o/oauth2/auth",
TokenURL: "https://oauth2.googleapis.com/token",
}
var googleOauthConfig = &oauth2.Config{
ClientID: "287161932061-gr3l32h40p1uc82m3pd81n4ubju2qqia.apps.googleusercontent.com",
ClientSecret: "GGOCSPX-H3g4W5sCWOl8V7KMXNRkywrXkJ1Y",
RedirectURL: "http://localhost:3000/GoogleCallback",
Scopes: []string{"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/analytics"},
Endpoint: endpotin,
}
const oauthStateString = "random"
func main() {
http.HandleFunc("/", handleMain)
http.HandleFunc("/GoogleLogin", handleGoogleLogin)
http.HandleFunc("/GoogleCallback", handleGoogleCallback)
log.Println(http.ListenAndServe(":3000", nil))
}
func handleMain(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, htmlIndex)
}
func handleGoogleLogin(w http.ResponseWriter, r *http.Request) {
url := googleOauthConfig.AuthCodeURL(oauthStateString)
log.Println(url)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
func handleGoogleCallback(w http.ResponseWriter, r *http.Request) {
state := r.FormValue("state")
if state != oauthStateString {
log.Printf("invalid oauth state, expected '%s', got '%s'", oauthStateString, state)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
code := r.FormValue("code")
log.Println(code)
token, err := googleOauthConfig.Exchange(context.Background(), code)
if err != nil {
log.Printf("Code exchange failed with %v", err)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
log.Println(token)
response, err := http.Get("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + token.AccessToken)
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
fmt.Fprintf(w, "Content: %s\n", contents)
}
|