Skip to content

Commit

Permalink
Add auth to POST reports
Browse files Browse the repository at this point in the history
  • Loading branch information
tvrg committed Feb 25, 2021
1 parent 31724a4 commit 274bc5d
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
45 changes: 45 additions & 0 deletions route/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package route

import (
"context"
"fmt"
"net/http"

"github.com/FACT-Finder/perfably/rediskey"
"github.com/FACT-Finder/perfably/token"
"github.com/go-redis/redis/v8"
"github.com/rs/zerolog/log"
)

func BasicAuth(handler http.HandlerFunc, client *redis.Client, realm string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()

if !ok {
unauthorized(w, realm)
return
}

hash, err := client.HGet(context.Background(), rediskey.Tokens(), user).Result()

if err != nil {
log.Error().Err(err).Msg("redis")
w.WriteHeader(http.StatusBadGateway)
writeString(w, fmt.Sprintf("redis failed: %s", err))
return
}

if !token.ComparePassword([]byte(hash), []byte(pass)) {
unauthorized(w, realm)
return
}

handler(w, r)
}
}

func unauthorized(w http.ResponseWriter, realm string) {
w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
w.WriteHeader(401)
writeString(w, "unauthorized")
}
2 changes: 1 addition & 1 deletion router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func New(cfg *config.Config, client *redis.Client) *mux.Router {
router.Methods("GET").Path("/project/{project}/id").HandlerFunc(route.Ids(cfg, client))
router.Methods("GET").Path("/project/{project}/metrics").HandlerFunc(route.Metrics(cfg, client))
router.Methods("GET").Path("/config").HandlerFunc(route.Config(cfg))
router.Methods("POST").Path("/project/{project}/report/{id}").HandlerFunc(route.AddReport(cfg, client))
router.Methods("POST").Path("/project/{project}/report/{id}").HandlerFunc(route.BasicAuth(route.AddReport(cfg, client), client, "perfably"))
router.PathPrefix("/").Handler(AddPrefix("/build", http.FileServer(http.FS(ui.FS))))
return router
}
Expand Down

0 comments on commit 274bc5d

Please sign in to comment.