From d7b35f05a5f64a167224369762aa4bd2b297686a Mon Sep 17 00:00:00 2001 From: Gregory Eremin Date: Thu, 5 Mar 2015 14:46:19 +0700 Subject: [PATCH] Server auth draft --- server/auth.go | 58 ++++++++++++++++++++++++++++++++++++++++++++++++ server/server.go | 11 +++++++++ 2 files changed, 69 insertions(+) create mode 100644 server/auth.go create mode 100644 server/server.go diff --git a/server/auth.go b/server/auth.go new file mode 100644 index 0000000..060a015 --- /dev/null +++ b/server/auth.go @@ -0,0 +1,58 @@ +package server + +import ( + "bytes" + "fmt" + "io/ioutil" + "net/http" + "net/url" + + "github.com/localhots/steward/config" +) + +const ( + authURL = "https://github.com/login/oauth/authorize" + accessTokenURL = "https://github.com/login/oauth/access_token" +) + +func authSigninHandler(w http.ResponseWriter, r *http.Request) { + params := url.Values{} + params.Set("client_id", config.C().ClientID) + params.Set("redirect_uri", config.C().RedirectURI) + params.Set("scope", "repo") + http.Redirect(w, r, authURL+"?"+params.Encode(), 302) +} + +func authCallbackHandler(w http.ResponseWriter, r *http.Request) { + if r.FormValue("error") != "" { + w.Write([]byte(r.FormValue("error_description"))) + } else { + fmt.Println("Got code: ", r.FormValue("code")) + token := getAccessToken(r.FormValue("code")) + fmt.Println("Got access token: ", token) + w.Write([]byte(token)) + } +} + +func getAccessToken(code string) string { + payload := url.Values{} + payload.Set("client_id", config.C().ClientID) + payload.Set("client_secret", config.C().ClientSecret) + payload.Set("code", code) + payload.Set("redirect_uri", config.C().RedirectURI) + + buf := bytes.NewBuffer([]byte(payload.Encode())) + resp, err := http.Post(accessTokenURL, "application/x-www-form-urlencoded", buf) + if err != nil { + panic(err) + } + + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + panic(err) + } + + pairs, _ := url.ParseQuery(string(body)) + return pairs.Get("access_token") +} diff --git a/server/server.go b/server/server.go new file mode 100644 index 0000000..d33fc9d --- /dev/null +++ b/server/server.go @@ -0,0 +1,11 @@ +package server + +import ( + "net/http" +) + +func Start() { + http.HandleFunc("/auth/signin", authSigninHandler) + http.HandleFunc("/auth/callback", authCallbackHandler) + http.ListenAndServe(":8080", nil) +}