2018-06-11 13:13:19 +00:00
package templates
import (
"net/http"
"github.com/gorilla/mux"
2018-09-10 10:01:38 +00:00
httperror "github.com/portainer/libhttp/error"
2018-06-11 13:13:19 +00:00
"github.com/portainer/portainer"
"github.com/portainer/portainer/http/security"
)
2018-08-07 15:43:36 +00:00
const (
errTemplateManagementDisabled = portainer . Error ( "Template management is disabled" )
)
2018-06-11 13:13:19 +00:00
// Handler represents an HTTP API handler for managing templates.
type Handler struct {
* mux . Router
2018-07-03 18:31:02 +00:00
TemplateService portainer . TemplateService
2018-08-07 15:43:36 +00:00
SettingsService portainer . SettingsService
2018-06-11 13:13:19 +00:00
}
// NewHandler returns a new instance of Handler.
func NewHandler ( bouncer * security . RequestBouncer ) * Handler {
h := & Handler {
Router : mux . NewRouter ( ) ,
}
2018-08-07 15:43:36 +00:00
2018-06-11 13:13:19 +00:00
h . Handle ( "/templates" ,
2018-07-03 18:31:02 +00:00
bouncer . RestrictedAccess ( httperror . LoggerHandler ( h . templateList ) ) ) . Methods ( http . MethodGet )
h . Handle ( "/templates" ,
2018-08-07 15:43:36 +00:00
bouncer . AdministratorAccess ( h . templateManagementCheck ( httperror . LoggerHandler ( h . templateCreate ) ) ) ) . Methods ( http . MethodPost )
2018-07-03 18:31:02 +00:00
h . Handle ( "/templates/{id}" ,
2018-08-07 15:43:36 +00:00
bouncer . AdministratorAccess ( h . templateManagementCheck ( httperror . LoggerHandler ( h . templateInspect ) ) ) ) . Methods ( http . MethodGet )
2018-07-03 18:31:02 +00:00
h . Handle ( "/templates/{id}" ,
2018-08-07 15:43:36 +00:00
bouncer . AdministratorAccess ( h . templateManagementCheck ( httperror . LoggerHandler ( h . templateUpdate ) ) ) ) . Methods ( http . MethodPut )
2018-07-03 18:31:02 +00:00
h . Handle ( "/templates/{id}" ,
2018-08-07 15:43:36 +00:00
bouncer . AdministratorAccess ( h . templateManagementCheck ( httperror . LoggerHandler ( h . templateDelete ) ) ) ) . Methods ( http . MethodDelete )
2018-06-11 13:13:19 +00:00
return h
}
2018-08-07 15:43:36 +00:00
func ( handler * Handler ) templateManagementCheck ( next http . Handler ) http . Handler {
return httperror . LoggerHandler ( func ( rw http . ResponseWriter , r * http . Request ) * httperror . HandlerError {
settings , err := handler . SettingsService . Settings ( )
if err != nil {
return & httperror . HandlerError { http . StatusInternalServerError , "Unable to retrieve settings from the database" , err }
}
if settings . TemplatesURL != "" {
return & httperror . HandlerError { http . StatusServiceUnavailable , "Portainer is configured to use external templates, template management is disabled" , errTemplateManagementDisabled }
}
next . ServeHTTP ( rw , r )
return nil
} )
}