diff --git a/bouquins/bouquins.go b/bouquins/bouquins.go index d8e011b..6bc0b11 100644 --- a/bouquins/bouquins.go +++ b/bouquins/bouquins.go @@ -8,6 +8,7 @@ import ( "html/template" "io/ioutil" "log" + "math/rand" "net/http" "net/url" "strconv" @@ -16,11 +17,16 @@ import ( "golang.org/x/oauth2" "github.com/c2h5oh/datasize" + "github.com/gorilla/sessions" ) const ( Version = "master" + alphanums = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + sessionName = "bouquins" + sessionOAuthState = "oauthState" + tplBooks = "book.html" tplAuthors = "author.html" tplSeries = "series.html" @@ -66,6 +72,7 @@ type Bouquins struct { Tpl *template.Template DB *sql.DB OAuthConf *oauth2.Config + Cookies *sessions.CookieStore } // Series is a book series. @@ -263,6 +270,28 @@ func TemplatesFunc(prod bool) *template.Template { }) } +// generates a 16 characters long random string +func securedRandString() string { + b := make([]byte, 16) + for i := range b { + b[i] = alphanums[rand.Intn(len(alphanums))] + } + return string(b) +} + +// current session +func (app *Bouquins) Session(req *http.Request) *sessions.Session { + session, _ := app.Cookies.Get(req, sessionName) + return session +} + +// sets value in session +func (app *Bouquins) SessionSet(name string, value string, res http.ResponseWriter, req *http.Request) { + session := app.Session(req) + session.Values[name] = value + session.Save(req, res) +} + // output page with template func (app *Bouquins) render(res http.ResponseWriter, tpl string, model interface{}) error { return app.Tpl.ExecuteTemplate(res, tpl, model) @@ -432,39 +461,42 @@ func (app *Bouquins) AboutPage(res http.ResponseWriter, req *http.Request) error // LoginPage redirects to OAuth login page (github) func (app *Bouquins) LoginPage(res http.ResponseWriter, req *http.Request) error { - url := app.OAuthConf.AuthCodeURL("state") // FIXME random state + // TODO choose provider + state := securedRandString() + app.SessionSet(sessionOAuthState, state, res, req) + url := app.OAuthConf.AuthCodeURL(state) http.Redirect(res, req, url, http.StatusTemporaryRedirect) return nil } // CallbackPage handle OAuth 2 callback func (app *Bouquins) CallbackPage(res http.ResponseWriter, req *http.Request) error { - state := req.FormValue("state") - if state != "state" { // FIXME random state - fmt.Printf("invalid oauth state, expected '%s', got '%s'\n", "state", state) - http.Redirect(res, req, "/", http.StatusTemporaryRedirect) - return nil + savedState := app.Session(req).Values[sessionOAuthState] + if savedState == "" { + return fmt.Errorf("missing saved oauth state") + } + state := req.FormValue("state") + if state != savedState { + return fmt.Errorf("invalid oauth state, expected '%s', got '%s'", "state", state) } - code := req.FormValue("code") token, err := app.OAuthConf.Exchange(oauth2.NoContext, code) if err != nil { - fmt.Println("Code exchange failed with '%s'\n", err) - http.Redirect(res, req, "/", http.StatusTemporaryRedirect) - return nil + return fmt.Errorf("Code exchange failed with '%s'", err) } - - response, err := http.Get("https://api.github.com/user?access_token=" + token.AccessToken) - + // TODO header version + // TODO header token ( Authorization: token ) + response, err := http.Get("https://api.github.com/user/emails?access_token=" + token.AccessToken) defer response.Body.Close() contents, err := ioutil.ReadAll(response.Body) fmt.Fprintf(res, "Content: %s\n", contents) - // TODO + // TODO get User email, check allowed, redirect home page return nil } // IndexPage displays index page: list of books/authors/series func (app *Bouquins) IndexPage(res http.ResponseWriter, req *http.Request) error { + // TODO display logged in/link login count, err := app.BookCount() if err != nil { return err diff --git a/main.go b/main.go index ff85bf9..d9eece1 100644 --- a/main.go +++ b/main.go @@ -10,6 +10,7 @@ import ( "golang.org/x/oauth2" "golang.org/x/oauth2/github" + "github.com/gorilla/sessions" _ "github.com/mattn/go-sqlite3" "meutel.net/meutel/go-bouquins/bouquins" @@ -69,14 +70,16 @@ func initApp() *BouquinsConf { log.Fatalln(err) } + // TODO conf by provider, client ID and secret in conf file oauthConf := &oauth2.Config{ ClientID: "8b0aedf07828f06918a0", ClientSecret: "eb26ec9c986fc28bd169bdddf169b794861e0d65", - Scopes: []string{"user"}, + Scopes: []string{"user:email"}, Endpoint: github.Endpoint, } - app := &bouquins.Bouquins{Tpl: tpl, DB: db, OAuthConf: oauthConf} + // FIXME constructor, conf cookies secret + app := &bouquins.Bouquins{Tpl: tpl, DB: db, OAuthConf: oauthConf, Cookies: sessions.NewCookieStore([]byte("flQ6QzM/c3Jtdl9ycDx6OXRIfFgK"))} err = app.PrepareAll() if err != nil { log.Fatalln(err)