Skip to content

Instantly share code, notes, and snippets.

@jaredallard
Created May 24, 2022 19:49
Show Gist options
  • Save jaredallard/0ff282a2c9eadd7e0f363ef3e0d6772b to your computer and use it in GitHub Desktop.
Save jaredallard/0ff282a2c9eadd7e0f363ef3e0d6772b to your computer and use it in GitHub Desktop.
token, err := conf.Token.Data(ctx)
if err != nil {
log.Error(ctx, "failed to get token", events.NewErrorInfo(err))
}
tokenByt := []byte(token)
tokenLength := int32(len(tokenByt))
// Check the auth token
base.Use(mux.MiddlewareFunc(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
checkAuth, err := fflags.Bool(r.Context(), "checkAuth", false)
if err != nil {
log.Error(r.Context(), "failed to get checkAuth flag", events.Err(err))
}
// If we're not checking the auth token, just pass the request through
if !checkAuth {
next.ServeHTTP(w, r)
return
}
unauthorized := func() {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized"))
}
// if no user information, fail the request
if r.URL.User == nil {
unauthorized()
return
}
suppliedToken, ok := r.URL.User.Password()
if !ok {
unauthorized()
return
}
suppliedTokenByt := []byte(suppliedToken)
// check the length first because constant compare needs to be the same length
if subtle.ConstantTimeEq(tokenLength, int32(len(suppliedTokenByt))) == 0 {
unauthorized()
return
}
// check the token
if subtle.ConstantTimeCompare(tokenByt, suppliedTokenByt) == 0 {
unauthorized()
return
}
// pass the request through
next.ServeHTTP(w, r)
})
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment