package main

import (
	"github.com/goadesign/goa"
	"golang.org/x/net/context"
	"net/http"
	"net/url"
	"strings"
)


func NewBasicAuthMiddleware() goa.Middleware {
	return func(h goa.Handler) goa.Handler {
		return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
			// Retrieve and log basic auth info
			user, pass, ok := req.BasicAuth()

			if !ok {
				goa.LogInfo(ctx, "failed basic auth")
				return goa.ErrUnauthorized("missing auth")
			}

			// verify credentials in github
			client := &http.Client{}
			data := url.Values{}
			baseGithubUrl := config.GetString("dta/necronomicon.github.url")
			authCheckUrl := strings.TrimSuffix(baseGithubUrl, "/") + "/api/v3/user"
			req, err := http.NewRequest("GET", authCheckUrl, strings.NewReader(data.Encode()))
			if err != nil {
				return goa.ErrUnauthorized("couldn't make auth token request to " + authCheckUrl)
			}
			req.SetBasicAuth(user, pass)
			resp, err := client.Do(req)
			if err != nil {
				return goa.ErrUnauthorized("couldn't verify github token")
			}
			if resp.StatusCode != 200 {
				return goa.ErrUnauthorized("invalid credentials")
			}

			// Proceed
			goa.LogInfo(ctx, "basic", "user", user, "pass", "**********")
			return h(ctx, rw, req)
		}
	}
}
