-
Notifications
You must be signed in to change notification settings - Fork 0
/
testGithubOauth.go
73 lines (59 loc) · 1.77 KB
/
testGithubOauth.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
package main
import (
"authtest/authentication"
"fmt"
"golang.org/x/oauth2"
"io/ioutil"
"net/http"
)
func main() {
var c authtest.auth
auth := c.getAuth()
clientID :=auth.account.clientID
fmt.Println(clientID)
http.HandleFunc("/", handleMain)
http.HandleFunc("/login", handleGithubLogin)
http.HandleFunc("/oauth2", handleGithubCallback)
fmt.Println(http.ListenAndServe(":9094", nil))
}
func handleMain(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, htmlIndex)
}
//https://github.com/login
func handleGithubLogin(w http.ResponseWriter, r *http.Request) {
url := githubOauthConfig.AuthCodeURL(oauthStateString)
fmt.Println(url)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
func handleGithubCallback(w http.ResponseWriter, r *http.Request) {
state := r.FormValue("state")
if state != oauthStateString {
fmt.Printf("invalid oauth state, expected '%s', got '%s'\n", oauthStateString, state)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
fmt.Println(state)
code := r.FormValue("code")
fmt.Println(code)
token, err := githubOauthConfig.Exchange(oauth2.NoContext, code)
fmt.Println(token)
if err != nil {
fmt.Println("Code exchange failed with '%s'\n", err)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
header := http.Header{}
header.Set("Accept", "application/json")
header.Set("Content-Type", "application/json")
header.Set("Authorization","token "+token.AccessToken)
req, err := http.NewRequest(http.MethodGet, "https://api.github.com/user", nil)
if err != nil {
fmt.Println("new request failed", err)
return
}
req.Header = header
response, err := http.DefaultClient.Do(req)
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
fmt.Fprintf(w, "Content: %s\n", contents)
}