Get OAuth2 token, call API

This commit is contained in:
Meutel 2017-09-08 12:32:26 +02:00
parent dfae92a039
commit 46964099f4
2 changed files with 31 additions and 1 deletions

View File

@ -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()

View File

@ -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)