package main

import (
	"encoding/base64"
	"fmt"
	"github.com/goadesign/goa"
	"strings"
)

func getUserFromBasicAuthString(ctx *goa.RequestData) (user string, err error) {
	if len(ctx.Request.Header) == 0 {
		// running tests, goa will clobber any auth headers set in the context
		return UnknownUser, nil
	}
	authString := ctx.Request.Header.Get("Authorization")
	s := strings.SplitN(authString, " ", 2)
	err = fmt.Errorf("Invalid Authentication header.")
	if len(s) != 2 {
		return "", err
	}
	b, err := base64.StdEncoding.DecodeString(s[1])
	if err != nil {
		return "", err
	}
	pair := strings.SplitN(string(b), ":", 2)
	if len(pair) != 2 {
		return "", err
	}
	return pair[0], nil
}
