diff --git a/bouquins/bouquins.go b/bouquins/bouquins.go index 3142e10..d8e011b 100644 --- a/bouquins/bouquins.go +++ b/bouquins/bouquins.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "html/template" + "io/ioutil" "log" "net/http" "net/url" @@ -38,6 +39,8 @@ const ( URLIndex = "/" // URLLogin url of login page (OAuth 2) URLLogin = "/login" + // URLCallback url of OAuth callback + URLCallback = "/callback" // URLBooks url of books page URLBooks = "/books/" // URLAuthors url of authors page @@ -429,11 +432,37 @@ 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", oauth2.AccessTypeOffline) + url := app.OAuthConf.AuthCodeURL("state") // FIXME random 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 + } + + 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 + } + + response, err := http.Get("https://api.github.com/user?access_token=" + token.AccessToken) + + defer response.Body.Close() + contents, err := ioutil.ReadAll(response.Body) + fmt.Fprintf(res, "Content: %s\n", contents) + // TODO + return nil +} + // IndexPage displays index page: list of books/authors/series func (app *Bouquins) IndexPage(res http.ResponseWriter, req *http.Request) error { count, err := app.BookCount() diff --git a/main.go b/main.go index 20d4679..ff85bf9 100644 --- a/main.go +++ b/main.go @@ -110,6 +110,7 @@ func handleURL(url string, f func(res http.ResponseWriter, req *http.Request) er func router(app *bouquins.Bouquins) { handleURL(bouquins.URLIndex, app.IndexPage) handleURL(bouquins.URLLogin, app.LoginPage) + handleURL(bouquins.URLCallback, app.CallbackPage) handleURL(bouquins.URLBooks, app.BooksPage) handleURL(bouquins.URLAuthors, app.AuthorsPage) handleURL(bouquins.URLSeries, app.SeriesPage)