mirror of
https://github.com/coder/coder.git
synced 2026-06-03 04:58:23 +00:00
591523a078
* chore: Move httpmw to /coderd directory httpmw is specific to coderd and should be scoped under coderd * chore: Move httpapi to /coderd directory httpapi is specific to coderd and should be scoped under coderd * chore: Move database to /coderd directory database is specific to coderd and should be scoped under coderd * chore: Update codecov & gitattributes for generated files * chore: Update Makefile
55 lines
1.5 KiB
Go
55 lines
1.5 KiB
Go
package httpmw
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
"github.com/coder/coder/coderd/database"
|
|
"github.com/coder/coder/coderd/httpapi"
|
|
)
|
|
|
|
type userParamContextKey struct{}
|
|
|
|
// UserParam returns the user from the ExtractUserParam handler.
|
|
func UserParam(r *http.Request) database.User {
|
|
user, ok := r.Context().Value(userParamContextKey{}).(database.User)
|
|
if !ok {
|
|
panic("developer error: user parameter middleware not provided")
|
|
}
|
|
return user
|
|
}
|
|
|
|
// ExtractUserParam extracts a user from an ID/username in the {user} URL parameter.
|
|
func ExtractUserParam(db database.Store) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
|
userID := chi.URLParam(r, "user")
|
|
if userID == "" {
|
|
httpapi.Write(rw, http.StatusBadRequest, httpapi.Response{
|
|
Message: "user id or name must be provided",
|
|
})
|
|
return
|
|
}
|
|
apiKey := APIKey(r)
|
|
if apiKey.UserID != userID && userID != "me" {
|
|
httpapi.Write(rw, http.StatusBadRequest, httpapi.Response{
|
|
Message: "getting non-personal users isn't supported yet",
|
|
})
|
|
return
|
|
}
|
|
user, err := db.GetUserByID(r.Context(), apiKey.UserID)
|
|
if err != nil {
|
|
httpapi.Write(rw, http.StatusInternalServerError, httpapi.Response{
|
|
Message: fmt.Sprintf("get user: %s", err.Error()),
|
|
})
|
|
}
|
|
|
|
ctx := context.WithValue(r.Context(), userParamContextKey{}, user)
|
|
next.ServeHTTP(rw, r.WithContext(ctx))
|
|
})
|
|
}
|
|
}
|