-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
73 lines (63 loc) · 2.15 KB
/
main.go
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
// Sumber asli https://github.com/plutov/packagemain/tree/master/11-oauth2
package main
import (
"fmt"
"io/ioutil"
"net/http"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
var (
googleOAuthConfig = &oauth2.Config{
RedirectURL: "http://localhost:8080/callback", //URL ini harus sama dengan redirect_uri pada google developer console
ClientID: "YOUR CLIENT ID HERE",
ClientSecret: "YOUR CLIENT SECRET HERE",
// scopes API URL bisa didapatkan di https://developers.google.com/identity/protocols/oauth2/scopes
Scopes: []string{"https://www.googleapis.com/auth/userinfo.profile"},
Endpoint: google.Endpoint,
}
randomState = "random"
)
func main() {
http.HandleFunc("/", handleHome)
http.HandleFunc("/login", handleLogin)
http.HandleFunc("/callback", handleCallback)
http.ListenAndServe(":8080", nil)
}
func handleHome(w http.ResponseWriter, r *http.Request) {
halaman := "/login"
html := "<html><body><a href=" + halaman + ">Login using google</a></body></html>"
fmt.Fprint(w, html)
}
func handleLogin(w http.ResponseWriter, r *http.Request) {
url := googleOAuthConfig.AuthCodeURL(randomState)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
func handleCallback(w http.ResponseWriter, r *http.Request) {
if r.FormValue("state") != randomState {
fmt.Println("State is not valid")
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
token, err := googleOAuthConfig.Exchange(oauth2.NoContext, r.FormValue("code"))
if err != nil {
fmt.Println("could not get token \n", err.Error())
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
// fmt.Println(token.AccessToken)
resp, err := http.Get("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + token.AccessToken)
if err != nil {
fmt.Println("could not create request \n", err.Error())
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("could not read response body \n", err.Error())
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
fmt.Fprintf(w, "Content: %s", content) //Menampilkan data yang didapat
}