2022-01-24 11:07:42 -06:00
|
|
|
package httpmw
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"database/sql"
|
|
|
|
|
"errors"
|
|
|
|
|
"fmt"
|
|
|
|
|
"net/http"
|
|
|
|
|
|
2022-01-30 19:13:14 -08:00
|
|
|
"github.com/go-chi/chi/v5"
|
2022-01-24 11:07:42 -06:00
|
|
|
|
2022-03-25 16:07:45 -05:00
|
|
|
"github.com/coder/coder/coderd/database"
|
|
|
|
|
"github.com/coder/coder/coderd/httpapi"
|
2022-01-24 11:07:42 -06:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type projectParamContextKey struct{}
|
|
|
|
|
|
2022-01-25 13:52:58 -06:00
|
|
|
// ProjectParam returns the project from the ExtractProjectParam handler.
|
2022-01-24 11:07:42 -06:00
|
|
|
func ProjectParam(r *http.Request) database.Project {
|
|
|
|
|
project, ok := r.Context().Value(projectParamContextKey{}).(database.Project)
|
|
|
|
|
if !ok {
|
|
|
|
|
panic("developer error: project param middleware not provided")
|
|
|
|
|
}
|
|
|
|
|
return project
|
|
|
|
|
}
|
|
|
|
|
|
2022-01-25 13:52:58 -06:00
|
|
|
// ExtractProjectParam grabs a project from the "project" URL parameter.
|
|
|
|
|
func ExtractProjectParam(db database.Store) func(http.Handler) http.Handler {
|
2022-01-24 11:07:42 -06:00
|
|
|
return func(next http.Handler) http.Handler {
|
|
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
2022-03-07 11:40:54 -06:00
|
|
|
projectID, parsed := parseUUID(rw, r, "project")
|
|
|
|
|
if !parsed {
|
2022-01-24 11:07:42 -06:00
|
|
|
return
|
|
|
|
|
}
|
2022-03-07 11:40:54 -06:00
|
|
|
project, err := db.GetProjectByID(r.Context(), projectID)
|
2022-01-24 11:07:42 -06:00
|
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
|
|
|
httpapi.Write(rw, http.StatusNotFound, httpapi.Response{
|
2022-03-07 11:40:54 -06:00
|
|
|
Message: fmt.Sprintf("project %q does not exist", projectID),
|
2022-01-24 11:07:42 -06:00
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
if err != nil {
|
|
|
|
|
httpapi.Write(rw, http.StatusInternalServerError, httpapi.Response{
|
2022-03-07 11:40:54 -06:00
|
|
|
Message: fmt.Sprintf("get project: %s", err),
|
2022-01-24 11:07:42 -06:00
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ctx := context.WithValue(r.Context(), projectParamContextKey{}, project)
|
2022-03-07 11:40:54 -06:00
|
|
|
chi.RouteContext(ctx).URLParams.Add("organization", project.OrganizationID)
|
2022-01-24 11:07:42 -06:00
|
|
|
next.ServeHTTP(rw, r.WithContext(ctx))
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|