Verify user

This commit is contained in:
Meutel 2017-09-08 17:24:59 +02:00
parent 82ee75fc40
commit a873c0df36

View File

@ -6,7 +6,6 @@ import (
"errors"
"fmt"
"html/template"
"io/ioutil"
"log"
"math/rand"
"net/http"
@ -26,6 +25,7 @@ const (
alphanums = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
sessionName = "bouquins"
sessionOAuthState = "oauthState"
sessionUser = "username"
tplBooks = "book.html"
tplAuthors = "author.html"
@ -67,6 +67,13 @@ const (
URLCalibre = "/calibre/"
)
type GitHubEmail struct {
Email string `json:"email"`
Primary bool `json:"primary"`
Verified bool `json:"verified"`
Visibility string `json:"visibility"`
}
// Bouquins contains application common resources: templates, database
type Bouquins struct {
Tpl *template.Template
@ -484,14 +491,41 @@ func (app *Bouquins) CallbackPage(res http.ResponseWriter, req *http.Request) er
if err != nil {
return fmt.Errorf("Code exchange failed with '%s'", err)
}
// TODO header version
// TODO header token ( Authorization: token <tok> )
response, err := http.Get("https://api.github.com/user/emails?access_token=" + token.AccessToken)
apiReq, err := http.NewRequest("GET", "https://api.github.com/user/emails", nil)
apiReq.Header.Add("Accept", "application/vnd.github.v3+json")
apiReq.Header.Add("Authorization", "token "+token.AccessToken)
client := &http.Client{}
response, err := client.Do(apiReq)
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
fmt.Fprintf(res, "Content: %s\n", contents)
// TODO get User email, check allowed, redirect home page
return nil
if err != nil {
log.Println("Auth error", err)
return fmt.Errorf("Authentification error")
}
dec := json.NewDecoder(response.Body)
var emails []GitHubEmail
err = dec.Decode(&emails)
if err != nil {
log.Println("Error reading github API response", err)
return fmt.Errorf("Error reading github API response")
}
fmt.Printf("Content: %s\n", emails)
var userEmail string
for _, email := range emails {
if email.Primary && email.Verified {
userEmail = email.Email
}
}
log.Println("User email:", userEmail)
// FIXME list allowed users
if userEmail == "meutel+github@meutel.net" {
app.SessionSet(sessionUser, "Meutel", res, req)
log.Println("User logged in", userEmail)
http.Redirect(res, req, "/", http.StatusTemporaryRedirect)
return nil
} else {
return fmt.Errorf("Unknown user")
}
}
// IndexPage displays index page: list of books/authors/series