mirror of https://github.com/gophish/gophish
Add support for authenticating to the API via an Authorization Bearer token.
parent
e1d5c809b2
commit
5f3c94d0cf
|
@ -109,6 +109,23 @@ func (s *ControllersSuite) TestRequireAPIKey() {
|
|||
s.Equal(resp.StatusCode, http.StatusBadRequest)
|
||||
}
|
||||
|
||||
func (s *ControllersSuite) TestInvalidAPIKey() {
|
||||
resp, err := http.Get(fmt.Sprintf("%s/api/groups/?api_key=%s", as.URL, "bogus-api-key"))
|
||||
s.Nil(err)
|
||||
defer resp.Body.Close()
|
||||
s.Equal(resp.StatusCode, http.StatusBadRequest)
|
||||
}
|
||||
|
||||
func (s *ControllersSuite) TestBearerToken() {
|
||||
req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/groups/", as.URL), nil)
|
||||
s.Nil(err)
|
||||
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", s.ApiKey))
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
s.Nil(err)
|
||||
defer resp.Body.Close()
|
||||
s.Equal(resp.StatusCode, http.StatusOK)
|
||||
}
|
||||
|
||||
func (s *ControllersSuite) TestSiteImportBaseHref() {
|
||||
h := "<html><head></head><body><img src=\"/test.png\"/></body></html>"
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
|
|
@ -62,8 +62,6 @@ func GetContext(handler http.Handler) http.HandlerFunc {
|
|||
|
||||
func RequireAPIKey(handler http.Handler) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
ak := r.Form.Get("api_key")
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
if r.Method == "OPTIONS" {
|
||||
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
|
||||
|
@ -71,10 +69,21 @@ func RequireAPIKey(handler http.Handler) http.HandlerFunc {
|
|||
w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
|
||||
return
|
||||
}
|
||||
r.ParseForm()
|
||||
ak := r.Form.Get("api_key")
|
||||
// If we can't get the API key, we'll also check for the
|
||||
// Authorization Bearer token
|
||||
if ak == "" {
|
||||
tokens, ok := r.Header["Authorization"]
|
||||
if ok && len(tokens) >= 1 {
|
||||
ak = tokens[0]
|
||||
ak = strings.TrimPrefix(ak, "Bearer ")
|
||||
}
|
||||
}
|
||||
if ak == "" {
|
||||
JSONError(w, 400, "API Key not set")
|
||||
return
|
||||
} else {
|
||||
}
|
||||
u, err := models.GetUserByAPIKey(ak)
|
||||
if err != nil {
|
||||
JSONError(w, 400, "Invalid API Key")
|
||||
|
@ -85,7 +94,6 @@ func RequireAPIKey(handler http.Handler) http.HandlerFunc {
|
|||
handler.ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RequireLogin is a simple middleware which checks to see if the user is currently logged in.
|
||||
// If not, the function returns a 302 redirect to the login page.
|
||||
|
|
Loading…
Reference in New Issue