Skip to content

Instantly share code, notes, and snippets.

@jaredallard
Created May 24, 2022 19:49
Show Gist options
  • Select an option

  • Save jaredallard/0ff282a2c9eadd7e0f363ef3e0d6772b to your computer and use it in GitHub Desktop.

Select an option

Save jaredallard/0ff282a2c9eadd7e0f363ef3e0d6772b to your computer and use it in GitHub Desktop.

Revisions

  1. jaredallard created this gist May 24, 2022.
    55 changes: 55 additions & 0 deletions handler.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    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)
    })
    }))