Add support for authenticating to the API via an Authorization Bearer token.

pull/504/merge
Jordan Wright 2018-04-21 12:19:58 -05:00
parent e1d5c809b2
commit 5f3c94d0cf
No known key found for this signature in database
GPG Key ID: 138D5AD2331B3C11
2 changed files with 36 additions and 11 deletions

View File

@ -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) {

View File

@ -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,19 +69,29 @@ 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")
return
}
r = ctx.Set(r, "user_id", u.Id)
r = ctx.Set(r, "api_key", ak)
handler.ServeHTTP(w, r)
}
u, err := models.GetUserByAPIKey(ak)
if err != nil {
JSONError(w, 400, "Invalid API Key")
return
}
r = ctx.Set(r, "user_id", u.Id)
r = ctx.Set(r, "api_key", ak)
handler.ServeHTTP(w, r)
}
}