Skip to content

Update Dependencies #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 55 additions & 23 deletions authenticator.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ package main
import (
"encoding/json"
"fmt"
"github.com/go-martini/martini"
gooauth2 "github.com/golang/oauth2"
"github.com/martini-contrib/oauth2"
"io/ioutil"
"log"
"net/http"
"strings"

"github.com/go-martini/martini"
"github.com/martini-contrib/oauth2"
gooauth2 "golang.org/x/oauth2"
)

type Authenticator interface {
Expand All @@ -21,15 +22,15 @@ func NewAuthenticator(conf *Conf) Authenticator {
var authenticator Authenticator

if conf.Auth.Info.Service == "google" {
handler := oauth2.Google(&gooauth2.Options{
handler := oauth2.Google(&gooauth2.Config{
ClientID: conf.Auth.Info.ClientId,
ClientSecret: conf.Auth.Info.ClientSecret,
RedirectURL: conf.Auth.Info.RedirectURL,
Scopes: []string{"email"},
})
authenticator = &GoogleAuth{&BaseAuth{handler, conf}}
} else if conf.Auth.Info.Service == "github" {
handler := GithubGeneral(&gooauth2.Options{
handler := GithubGeneral(&gooauth2.Config{
ClientID: conf.Auth.Info.ClientId,
ClientSecret: conf.Auth.Info.ClientSecret,
RedirectURL: conf.Auth.Info.RedirectURL,
Expand All @@ -44,11 +45,13 @@ func NewAuthenticator(conf *Conf) Authenticator {
}

// Currently, martini-contrib/oauth2 doesn't support github enterprise directly.
func GithubGeneral(opts *gooauth2.Options, conf *Conf) martini.Handler {
authUrl := fmt.Sprintf("%s/login/oauth/authorize", conf.Auth.Info.Endpoint)
tokenUrl := fmt.Sprintf("%s/login/oauth/access_token", conf.Auth.Info.Endpoint)
func GithubGeneral(cfgs *gooauth2.Config, conf *Conf) martini.Handler {
cfgs.Endpoint = gooauth2.Endpoint{
AuthURL: fmt.Sprintf("%s/login/oauth/authorize", conf.Auth.Info.Endpoint),
TokenURL: fmt.Sprintf("%s/login/oauth/access_token", conf.Auth.Info.Endpoint),
}

return oauth2.NewOAuth2Provider(opts, authUrl, tokenUrl)
return oauth2.NewOAuth2Provider(cfgs)
}

type BaseAuth struct {
Expand All @@ -64,31 +67,60 @@ type GoogleAuth struct {
*BaseAuth
}

func (a *GoogleAuth) Authenticate(domain []string, c martini.Context, tokens oauth2.Tokens, w http.ResponseWriter, r *http.Request) {
extra := tokens.ExtraData()
if _, ok := extra["id_token"]; ok == false {
log.Printf("id_token not found")
forbidden(w)
return
func fetchJSONData(url string) (map[string]interface{}, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()

keys := strings.Split(extra["id_token"], ".")
if len(keys) < 2 {
log.Printf("invalid id_token")
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}

info := map[string]interface{}{}
err = json.Unmarshal(content, &info)
if err != nil {
return nil, err
}

return info, nil
}

// see https://developers.google.com/identity/protocols/OpenIDConnect#discovery
func discoveryGoogleUserinfoEndpoint() (string, error) {
info, err := fetchJSONData(`https://accounts.google.com/.well-known/openid-configuration`)
if err != nil {
return "", err
}

if v, ok := info["userinfo_endpoint"].(string); !ok {
return "", fmt.Errorf("userinfo_endpoint is not valid:")
} else {
return v, nil
}
}

func (a *GoogleAuth) Authenticate(domain []string, c martini.Context, tokens oauth2.Tokens, w http.ResponseWriter, r *http.Request) {
accessToken := tokens.Access()
if len(accessToken) == 0 {
log.Printf("access_token not found")
forbidden(w)
return
}

data, err := base64Decode(keys[1])
userinfoUrl, err := discoveryGoogleUserinfoEndpoint()
if err != nil {
log.Printf("failed to decode base64: %s", err.Error())
log.Println("cannot discovery userinfo endpoint", err)
forbidden(w)
return
}

var info map[string]interface{}
if err := json.Unmarshal(data, &info); err != nil {
log.Printf("failed to decode json: %s", err.Error())
url := fmt.Sprintf(`%s?alt=json&access_token=%s`, userinfoUrl, accessToken)
info, err := fetchJSONData(url)
if err != nil {
log.Println("cannot fetch userinfo:", err)
forbidden(w)
return
}
Expand Down
4 changes: 2 additions & 2 deletions httpd.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ func (s *Server) Run() error {
registered[path] = true
rawPath := rawPaths[i]
if rawPath != "" {
m.Get(rawPath, func(w http.ResponseWriter, r *http.Request) {
m.Any(rawPath, func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, rawPath+"/", http.StatusFound)
})
}
Expand All @@ -111,7 +111,7 @@ func (s *Server) Run() error {

log.Printf("starting static file server for: %s", path)
fileServer := http.FileServer(http.Dir(path))
m.Get("/**", fileServer.ServeHTTP)
m.Any("/**", fileServer.ServeHTTP)

log.Printf("starting server at %s", s.Conf.Addr)

Expand Down