Files
portainer/api/http/handler/users/admin_init.go
T
Chaim Lev-Ari 8dba19694a feat(roles-management): integrate rbac extension (#6)
* refactor(rbac): move client extension code

* feat(app): remove checks for extension

* feat(rbac): remove checks for extensions

* feat(extensions): remove reference to rbac extensions

* feat(roles): add changes from codebase before removal of rbac

* refactor(security): remove rbac service

* refactor(security): use AdminAccess as an alias

* fix(access): rename policies type

* style(security): add comment about Aliasing AdminAccess to RestrictedAccess

* feat(bolt): add auth migration from ce to ee

* feat(stacks): use authorized access to stop/start stacks

* fix(bolt): supply right params to migrator

* feat(rbac): get authorization on client side
2020-10-07 23:21:14 +13:00

65 lines
2.0 KiB
Go

package users
import (
"errors"
"net/http"
"github.com/asaskevich/govalidator"
httperror "github.com/portainer/libhttp/error"
"github.com/portainer/libhttp/request"
"github.com/portainer/libhttp/response"
"github.com/portainer/portainer/api"
"github.com/portainer/portainer/api/internal/authorization"
)
type adminInitPayload struct {
Username string
Password string
}
func (payload *adminInitPayload) Validate(r *http.Request) error {
if govalidator.IsNull(payload.Username) || govalidator.Contains(payload.Username, " ") {
return errors.New("Invalid username. Must not contain any whitespace")
}
if govalidator.IsNull(payload.Password) {
return errors.New("Invalid password")
}
return nil
}
// POST request on /api/users/admin/init
func (handler *Handler) adminInit(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
var payload adminInitPayload
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
}
users, err := handler.DataStore.User().UsersByRole(portainer.AdministratorRole)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve users from the database", err}
}
if len(users) != 0 {
return &httperror.HandlerError{http.StatusConflict, "Unable to create administrator user", errAdminAlreadyInitialized}
}
user := &portainer.User{
Username: payload.Username,
Role: portainer.AdministratorRole,
PortainerAuthorizations: authorization.DefaultPortainerAuthorizations(),
}
user.Password, err = handler.CryptoService.Hash(payload.Password)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to hash user password", errCryptoHashFailure}
}
err = handler.DataStore.User().CreateUser(user)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist user inside the database", err}
}
return response.JSON(w, user)
}