Auth works

This commit is contained in:
2015-03-05 19:57:36 +07:00
parent 7fc7b1889b
commit 4295811647
12 changed files with 185 additions and 74 deletions
+20 -35
View File
@@ -1,18 +1,14 @@
package server
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"github.com/localhots/empact/config"
)
const (
authURL = "https://github.com/login/oauth/authorize"
accessTokenURL = "https://github.com/login/oauth/access_token"
"github.com/localhots/empact/db"
"github.com/localhots/empact/job"
"github.com/localhots/empact/task"
)
func authSigninHandler(w http.ResponseWriter, r *http.Request) {
@@ -20,39 +16,28 @@ func authSigninHandler(w http.ResponseWriter, r *http.Request) {
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)
http.Redirect(w, r, config.C().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))
code := r.FormValue("code")
fmt.Println("Got code: ", code)
res := make(chan string)
job.Enqueue(&task.FetchAccessTokenTask{
Code: code,
Result: res,
Task: &db.Task{},
})
if token, ok := <-res; ok {
fmt.Println("Got access token: ", token)
w.Write([]byte(token))
} else {
panic("Failed to fetch 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")
}
+28
View File
@@ -1,11 +1,39 @@
package server
import (
"fmt"
"net/http"
"time"
"code.google.com/p/go-uuid/uuid"
)
const (
sessionCookie = "session_id"
)
func Start() {
fmt.Println("Starting server at http://localhost:8080")
http.HandleFunc("/", sessionHandler)
http.HandleFunc("/auth/signin", authSigninHandler)
http.HandleFunc("/auth/callback", authCallbackHandler)
http.ListenAndServe(":8080", nil)
}
func sessionHandler(w http.ResponseWriter, r *http.Request) {
if cook, err := r.Cookie(sessionCookie); err != nil {
cook = &http.Cookie{
Name: sessionCookie,
Value: uuid.New(),
Path: "/",
Expires: time.Now().Add(365 * 24 * time.Hour),
HttpOnly: true,
}
http.SetCookie(w, cook)
}
}
func sessionID(r *http.Request) string {
cook, _ := r.Cookie(sessionCookie)
return cook.Value
}