From 8c42564004e3bcbd89a24a48b39dc15fd586f637 Mon Sep 17 00:00:00 2001 From: kripanshdevtron Date: Fri, 5 Aug 2022 10:59:42 +0530 Subject: [PATCH 01/14] initial commit --- .../user/UserAttributesRepository.go | 82 +++++++++++++++++++ .../sql/65_insert_user_attributes.down.sql | 1 + scripts/sql/65_insert_user_attributes.up.sql | 16 ++++ 3 files changed, 99 insertions(+) create mode 100644 internal/sql/repository/user/UserAttributesRepository.go create mode 100644 scripts/sql/65_insert_user_attributes.down.sql create mode 100644 scripts/sql/65_insert_user_attributes.up.sql diff --git a/internal/sql/repository/user/UserAttributesRepository.go b/internal/sql/repository/user/UserAttributesRepository.go new file mode 100644 index 0000000000..085e9248e7 --- /dev/null +++ b/internal/sql/repository/user/UserAttributesRepository.go @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2020 Devtron Labs + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package user + +import ( + "github.com/devtron-labs/devtron/pkg/sql" + "github.com/go-pg/pg" +) + +type UserAttributes struct { + tableName struct{} `sql:"user_attributes" pg:",discard_unknown_columns"` + emailId string `sql:"email_id,pk"` + userData string `sql:"user_data,notnull"` + sql.AuditLog +} + +type UserAttributesRepository interface { + Save(model *UserAttributes, tx *pg.Tx) (*UserAttributes, error) + Update(model *UserAttributes, tx *pg.Tx) error + FindByKey(key string) (*UserAttributes, error) + FindById(id int) (*UserAttributes, error) + FindActiveList() ([]*UserAttributes, error) + GetConnection() (dbConnection *pg.DB) +} + +type UserAttributesRepositoryImpl struct { + dbConnection *pg.DB +} + +func NewUserAttributesRepositoryImpl(dbConnection *pg.DB) *UserAttributesRepositoryImpl { + return &UserAttributesRepositoryImpl{dbConnection: dbConnection} +} + +func (impl *UserAttributesRepositoryImpl) GetConnection() (dbConnection *pg.DB) { + return impl.dbConnection +} + +func (repo UserAttributesRepositoryImpl) Save(model *UserAttributes, tx *pg.Tx) (*UserAttributes, error) { + err := tx.Insert(model) + return model, err +} + +func (repo UserAttributesRepositoryImpl) Update(model *UserAttributes, tx *pg.Tx) error { + err := tx.Update(model) + return err +} + +func (repo UserAttributesRepositoryImpl) FindByKey(key string) (*UserAttributes, error) { + model := &UserAttributes{} + err := repo.dbConnection.Model(model).Where("key = ?", key).Where("active = ?", true). + Select() + return model, err +} + +func (repo UserAttributesRepositoryImpl) FindById(id int) (*UserAttributes, error) { + model := &UserAttributes{} + err := repo.dbConnection.Model(model).Where("id = ?", id).Where("active = ?", true). + Select() + return model, err +} + +func (repo UserAttributesRepositoryImpl) FindActiveList() ([]*UserAttributes, error) { + var models []*UserAttributes + err := repo.dbConnection.Model(&models).Where("active = ?", true). + Select() + return models, err +} diff --git a/scripts/sql/65_insert_user_attributes.down.sql b/scripts/sql/65_insert_user_attributes.down.sql new file mode 100644 index 0000000000..5eccfd5d6a --- /dev/null +++ b/scripts/sql/65_insert_user_attributes.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS "public"."user_attributes"; \ No newline at end of file diff --git a/scripts/sql/65_insert_user_attributes.up.sql b/scripts/sql/65_insert_user_attributes.up.sql new file mode 100644 index 0000000000..6102ac56ca --- /dev/null +++ b/scripts/sql/65_insert_user_attributes.up.sql @@ -0,0 +1,16 @@ +-- +-- Name: user_attributes; Type: TABLE; Schema: public; Owner: postgres +-- + +CREATE TABLE public.user_attributes ( + email_id varchar(500) NOT NULL, + user_data json NOT NULL, + created_on timestamp with time zone, + updated_on timestamp with time zone, + created_by integer, + updated_by integer, + PRIMARY KEY ("email_id") +); + + +ALTER TABLE public.user_attributes OWNER TO postgres; \ No newline at end of file From 04d936c1aa964dc9a5c39e425a7a683cfc1d2281 Mon Sep 17 00:00:00 2001 From: kripanshdevtron Date: Fri, 5 Aug 2022 18:47:07 +0530 Subject: [PATCH 02/14] user attributes code commit --- Wire.go | 9 ++ api/restHandler/UserAttributesRestHandler.go | 148 ++++++++++++++++++ api/router/UserAttributesRouter.go | 47 ++++++ api/router/router.go | 7 +- .../repository/UserAttributesRepository.go | 117 ++++++++++++++ .../user/UserAttributesRepository.go | 82 ---------- pkg/attributes/UserAttributesService.go | 120 ++++++++++++++ wire_gen.go | 9 +- 8 files changed, 454 insertions(+), 85 deletions(-) create mode 100644 api/restHandler/UserAttributesRestHandler.go create mode 100644 api/router/UserAttributesRouter.go create mode 100644 internal/sql/repository/UserAttributesRepository.go delete mode 100644 internal/sql/repository/user/UserAttributesRepository.go create mode 100644 pkg/attributes/UserAttributesService.go diff --git a/Wire.go b/Wire.go index 8c9f9a018f..d5d8d6f015 100644 --- a/Wire.go +++ b/Wire.go @@ -731,6 +731,15 @@ func InitializeApp() (*App, error) { // AuthWireSet, cron.NewHelmApplicationStatusUpdateHandlerImpl, wire.Bind(new(cron.HelmApplicationStatusUpdateHandler), new(*cron.HelmApplicationStatusUpdateHandlerImpl)), + + router.NewUserAttributesRouterImpl, + wire.Bind(new(router.UserAttributesRouter), new(*router.UserAttributesRouterImpl)), + restHandler.NewUserAttributesRestHandlerImpl, + wire.Bind(new(restHandler.UserAttributesRestHandler), new(*restHandler.UserAttributesRestHandlerImpl)), + attributes.NewUserAttributesServiceImpl, + wire.Bind(new(attributes.UserAttributesService), new(*attributes.UserAttributesServiceImpl)), + repository.NewUserAttributesRepositoryImpl, + wire.Bind(new(repository.UserAttributesRepository), new(*repository.UserAttributesRepositoryImpl)), ) return &App{}, nil } diff --git a/api/restHandler/UserAttributesRestHandler.go b/api/restHandler/UserAttributesRestHandler.go new file mode 100644 index 0000000000..d06af40f17 --- /dev/null +++ b/api/restHandler/UserAttributesRestHandler.go @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2020 Devtron Labs + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package restHandler + +import ( + "encoding/json" + "errors" + "github.com/devtron-labs/devtron/api/restHandler/common" + user2 "github.com/devtron-labs/devtron/pkg/attributes" + "github.com/devtron-labs/devtron/pkg/user" + "github.com/devtron-labs/devtron/pkg/user/casbin" + "go.uber.org/zap" + "net/http" +) + +type UserAttributesRestHandler interface { + AddUserAttributes(w http.ResponseWriter, r *http.Request) + UpdateUserAttributes(w http.ResponseWriter, r *http.Request) + GetUserAttribute(w http.ResponseWriter, r *http.Request) +} + +type UserAttributesRestHandlerImpl struct { + logger *zap.SugaredLogger + enforcer casbin.Enforcer + userService user.UserService + userAttributesService user2.UserAttributesService +} + +func NewUserAttributesRestHandlerImpl(logger *zap.SugaredLogger, enforcer casbin.Enforcer, + userService user.UserService, userAttributesService user2.UserAttributesService) *UserAttributesRestHandlerImpl { + userAuthHandler := &UserAttributesRestHandlerImpl{ + logger: logger, + enforcer: enforcer, + userService: userService, + userAttributesService: userAttributesService, + } + return userAuthHandler +} +func (handler UserAttributesRestHandlerImpl) AddUserAttributes(w http.ResponseWriter, r *http.Request) { + userId, err := handler.userService.GetLoggedInUser(r) + if userId == 0 || err != nil { + common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized) + return + } + decoder := json.NewDecoder(r.Body) + var dto user2.UserAttributesDto + err = decoder.Decode(&dto) + if err != nil { + handler.logger.Errorw("request err, AddUserAttributes", "err", err, "payload", dto) + common.WriteJsonResp(w, err, nil, http.StatusBadRequest) + return + } + + dto.UserId = userId + token := r.Header.Get("token") + if ok := handler.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionCreate, "*"); !ok { + common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden) + return + } + + handler.logger.Infow("request payload, AddUserAttributes", "payload", dto) + resp, err := handler.userAttributesService.AddUserAttributes(&dto) + if err != nil { + handler.logger.Errorw("service err, AddUserAttributes", "err", err, "payload", dto) + common.WriteJsonResp(w, err, nil, http.StatusInternalServerError) + return + } + common.WriteJsonResp(w, nil, resp, http.StatusOK) +} + +func (handler UserAttributesRestHandlerImpl) UpdateUserAttributes(w http.ResponseWriter, r *http.Request) { + userId, err := handler.userService.GetLoggedInUser(r) + if userId == 0 || err != nil { + common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized) + return + } + + decoder := json.NewDecoder(r.Body) + var dto user2.UserAttributesDto + err = decoder.Decode(&dto) + if err != nil { + handler.logger.Errorw("request err, UpdateUserAttributes", "err", err, "payload", dto) + common.WriteJsonResp(w, err, nil, http.StatusBadRequest) + return + } + + dto.UserId = userId + token := r.Header.Get("token") + if ok := handler.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionUpdate, "*"); !ok { + common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden) + return + } + + handler.logger.Infow("request payload, UpdateUserAttributes", "payload", dto) + resp, err := handler.userAttributesService.UpdateUserAttributes(&dto) + if err != nil { + handler.logger.Errorw("service err, UpdateUserAttributes", "err", err, "payload", dto) + common.WriteJsonResp(w, err, nil, http.StatusInternalServerError) + return + } + common.WriteJsonResp(w, nil, resp, http.StatusOK) +} + +func (handler UserAttributesRestHandlerImpl) GetUserAttribute(w http.ResponseWriter, r *http.Request) { + userId, err := handler.userService.GetLoggedInUser(r) + if userId == 0 || err != nil { + common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized) + return + } + + decoder := json.NewDecoder(r.Body) + var dto user2.UserAttributesDto + err = decoder.Decode(&dto) + if err != nil { + handler.logger.Errorw("request err, GetUserAttribute", "err", err, "payload", dto) + common.WriteJsonResp(w, err, nil, http.StatusBadRequest) + return + } + + token := r.Header.Get("token") + if ok := handler.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionGet, "*"); !ok { + common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden) + return + } + + res, err := handler.userAttributesService.GetUserAttribute(&dto) + if err != nil { + handler.logger.Errorw("service err, GetAttributesById", "err", err) + common.WriteJsonResp(w, err, nil, http.StatusInternalServerError) + return + } + common.WriteJsonResp(w, nil, res, http.StatusOK) +} diff --git a/api/router/UserAttributesRouter.go b/api/router/UserAttributesRouter.go new file mode 100644 index 0000000000..2d20d0a6fd --- /dev/null +++ b/api/router/UserAttributesRouter.go @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2020 Devtron Labs + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package router + +import ( + user "github.com/devtron-labs/devtron/api/restHandler" + "github.com/gorilla/mux" +) + +type UserAttributesRouter interface { + initAttributesRouter(helmRouter *mux.Router) +} + +type UserAttributesRouterImpl struct { + userAttributesRestHandler user.UserAttributesRestHandler +} + +func NewUserAttributesRouterImpl(userAttributesRestHandler user.UserAttributesRestHandler) *UserAttributesRouterImpl { + router := &UserAttributesRouterImpl{ + userAttributesRestHandler: userAttributesRestHandler, + } + return router +} + +func (router UserAttributesRouterImpl) initAttributesRouter(attributesRouter *mux.Router) { + attributesRouter.Path("/create"). + HandlerFunc(router.userAttributesRestHandler.AddUserAttributes).Methods("POST") + attributesRouter.Path("/update"). + HandlerFunc(router.userAttributesRestHandler.UpdateUserAttributes).Methods("PUT") + attributesRouter.Path(""). + HandlerFunc(router.userAttributesRestHandler.GetUserAttribute).Methods("GET") +} diff --git a/api/router/router.go b/api/router/router.go index 435ba93a1f..bb55eb3292 100644 --- a/api/router/router.go +++ b/api/router/router.go @@ -89,6 +89,7 @@ type MuxRouter struct { gitOpsConfigRouter GitOpsConfigRouter dashboardRouter dashboard.DashboardRouter attributesRouter AttributesRouter + userAttributesRouter UserAttributesRouter commonRouter CommonRouter grafanaRouter GrafanaRouter ssoLoginRouter sso.SsoLoginRouter @@ -130,7 +131,7 @@ func NewMuxRouter(logger *zap.SugaredLogger, HelmRouter HelmRouter, PipelineConf ChartRefRouter ChartRefRouter, ConfigMapRouter ConfigMapRouter, AppStoreRouter appStore.AppStoreRouter, chartRepositoryRouter chartRepo.ChartRepositoryRouter, ReleaseMetricsRouter ReleaseMetricsRouter, deploymentGroupRouter DeploymentGroupRouter, batchOperationRouter BatchOperationRouter, chartGroupRouter ChartGroupRouter, testSuitRouter TestSuitRouter, imageScanRouter ImageScanRouter, - policyRouter PolicyRouter, gitOpsConfigRouter GitOpsConfigRouter, dashboardRouter dashboard.DashboardRouter, attributesRouter AttributesRouter, + policyRouter PolicyRouter, gitOpsConfigRouter GitOpsConfigRouter, dashboardRouter dashboard.DashboardRouter, attributesRouter AttributesRouter, userAttributesRouter UserAttributesRouter, commonRouter CommonRouter, grafanaRouter GrafanaRouter, ssoLoginRouter sso.SsoLoginRouter, telemetryRouter TelemetryRouter, telemetryWatcher telemetry.TelemetryEventClient, bulkUpdateRouter BulkUpdateRouter, webhookListenerRouter WebhookListenerRouter, appLabelsRouter AppLabelRouter, coreAppRouter CoreAppRouter, helmAppRouter client.HelmAppRouter, k8sApplicationRouter k8s.K8sApplicationRouter, pProfRouter PProfRouter, deploymentConfigRouter deployment.DeploymentConfigRouter, dashboardTelemetryRouter dashboardEvent.DashboardTelemetryRouter, @@ -177,6 +178,7 @@ func NewMuxRouter(logger *zap.SugaredLogger, HelmRouter HelmRouter, PipelineConf policyRouter: policyRouter, gitOpsConfigRouter: gitOpsConfigRouter, attributesRouter: attributesRouter, + userAttributesRouter: userAttributesRouter, dashboardRouter: dashboardRouter, commonRouter: commonRouter, grafanaRouter: grafanaRouter, @@ -324,6 +326,9 @@ func (r MuxRouter) Init() { attributeRouter := r.Router.PathPrefix("/orchestrator/attributes").Subrouter() r.attributesRouter.initAttributesRouter(attributeRouter) + userAttributeRouter := r.Router.PathPrefix("/orchestrator/attributes/user").Subrouter() + r.userAttributesRouter.initAttributesRouter(userAttributeRouter) + dashboardRouter := r.Router.PathPrefix("/dashboard").Subrouter() r.dashboardRouter.InitDashboardRouter(dashboardRouter) diff --git a/internal/sql/repository/UserAttributesRepository.go b/internal/sql/repository/UserAttributesRepository.go new file mode 100644 index 0000000000..b7b7976dc3 --- /dev/null +++ b/internal/sql/repository/UserAttributesRepository.go @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2020 Devtron Labs + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package repository + +import ( + "encoding/json" + "github.com/devtron-labs/devtron/pkg/sql" + "github.com/go-pg/pg" + "time" +) + +type UserAttributes struct { + tableName struct{} `sql:"user_attributes" pg:",discard_unknown_columns"` + EmailId string `sql:"email_id,pk"` + UserData string `sql:"user_data,notnull"` + sql.AuditLog +} + +type UserAttributesDao struct { + EmailId string `json:"emailId"` + Key string `json:"key"` + Value string `json:"value"` + UserId int32 `json:"-"` +} + +type UserAttributesRepository interface { + GetConnection() (dbConnection *pg.DB) + AddUserAttribute(attrDto *UserAttributesDao) (*UserAttributesDao, error) + UpdateDataValByKey(attrDto *UserAttributesDao) error + GetDataValueByKey(attrDto *UserAttributesDao) (string, error) +} + +type UserAttributesRepositoryImpl struct { + dbConnection *pg.DB +} + +func NewUserAttributesRepositoryImpl(dbConnection *pg.DB) *UserAttributesRepositoryImpl { + return &UserAttributesRepositoryImpl{dbConnection: dbConnection} +} + +func (impl *UserAttributesRepositoryImpl) GetConnection() (dbConnection *pg.DB) { + return impl.dbConnection +} + +func (repo UserAttributesRepositoryImpl) AddUserAttribute(attrDto *UserAttributesDao) (*UserAttributesDao, error) { + userDataMap := make(map[string]interface{}) + userDataMap[attrDto.Key] = attrDto.Value + userAttr := UserAttributes{} + userAttr.EmailId = attrDto.EmailId + userDataJson, err := json.Marshal(userDataMap) + if err != nil { + return nil, err + } + userAttr.UserData = string(userDataJson) + userAttr.CreatedBy = attrDto.UserId + userAttr.UpdatedBy = attrDto.UserId + userAttr.CreatedOn = time.Now() + userAttr.UpdatedOn = time.Now() + + err = repo.dbConnection.Insert(&userAttr) + if err != nil { + return nil, err + } + + return attrDto, nil +} + +func (repo UserAttributesRepositoryImpl) UpdateDataValByKey(attrDto *UserAttributesDao) error { + var userAttr = &UserAttributes{} + keyValMap := make(map[string]string) + keyValMap[attrDto.Key] = attrDto.Value + updatedValJson, err := json.Marshal(keyValMap) + if err != nil { + return err + } + query := "update user_attributes SET user_data = user_data::jsonb - ? || ? where email_id = ?" + + _, err = repo.dbConnection. + Query(userAttr, query, attrDto.Key, string(updatedValJson), attrDto.EmailId) + return err +} + +func (repo UserAttributesRepositoryImpl) GetDataValueByKey(attrDto *UserAttributesDao) (string, error) { + model := &UserAttributes{} + err := repo.dbConnection.Model(model).Where("email_id = ?", attrDto.EmailId). + Select() + if err != nil { + return "", err + } + data := model.UserData + var jsonMap map[string]interface{} + err = json.Unmarshal([]byte(data), &jsonMap) + if err != nil { + return "", err + } + dataVal := jsonMap[attrDto.Key] + var response = "" + if dataVal != nil { + response = dataVal.(string) + } + return response, err +} diff --git a/internal/sql/repository/user/UserAttributesRepository.go b/internal/sql/repository/user/UserAttributesRepository.go deleted file mode 100644 index 085e9248e7..0000000000 --- a/internal/sql/repository/user/UserAttributesRepository.go +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2020 Devtron Labs - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package user - -import ( - "github.com/devtron-labs/devtron/pkg/sql" - "github.com/go-pg/pg" -) - -type UserAttributes struct { - tableName struct{} `sql:"user_attributes" pg:",discard_unknown_columns"` - emailId string `sql:"email_id,pk"` - userData string `sql:"user_data,notnull"` - sql.AuditLog -} - -type UserAttributesRepository interface { - Save(model *UserAttributes, tx *pg.Tx) (*UserAttributes, error) - Update(model *UserAttributes, tx *pg.Tx) error - FindByKey(key string) (*UserAttributes, error) - FindById(id int) (*UserAttributes, error) - FindActiveList() ([]*UserAttributes, error) - GetConnection() (dbConnection *pg.DB) -} - -type UserAttributesRepositoryImpl struct { - dbConnection *pg.DB -} - -func NewUserAttributesRepositoryImpl(dbConnection *pg.DB) *UserAttributesRepositoryImpl { - return &UserAttributesRepositoryImpl{dbConnection: dbConnection} -} - -func (impl *UserAttributesRepositoryImpl) GetConnection() (dbConnection *pg.DB) { - return impl.dbConnection -} - -func (repo UserAttributesRepositoryImpl) Save(model *UserAttributes, tx *pg.Tx) (*UserAttributes, error) { - err := tx.Insert(model) - return model, err -} - -func (repo UserAttributesRepositoryImpl) Update(model *UserAttributes, tx *pg.Tx) error { - err := tx.Update(model) - return err -} - -func (repo UserAttributesRepositoryImpl) FindByKey(key string) (*UserAttributes, error) { - model := &UserAttributes{} - err := repo.dbConnection.Model(model).Where("key = ?", key).Where("active = ?", true). - Select() - return model, err -} - -func (repo UserAttributesRepositoryImpl) FindById(id int) (*UserAttributes, error) { - model := &UserAttributes{} - err := repo.dbConnection.Model(model).Where("id = ?", id).Where("active = ?", true). - Select() - return model, err -} - -func (repo UserAttributesRepositoryImpl) FindActiveList() ([]*UserAttributes, error) { - var models []*UserAttributes - err := repo.dbConnection.Model(&models).Where("active = ?", true). - Select() - return models, err -} diff --git a/pkg/attributes/UserAttributesService.go b/pkg/attributes/UserAttributesService.go new file mode 100644 index 0000000000..2084df7c1a --- /dev/null +++ b/pkg/attributes/UserAttributesService.go @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2020 Devtron Labs + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package attributes + +import ( + "github.com/devtron-labs/devtron/internal/sql/repository" + "github.com/go-pg/pg" + "go.uber.org/zap" +) + +type UserAttributesService interface { + AddUserAttributes(request *UserAttributesDto) (*UserAttributesDto, error) + UpdateUserAttributes(request *UserAttributesDto) (*UserAttributesDto, error) + GetUserAttribute(request *UserAttributesDto) (*UserAttributesDto, error) +} + +type UserAttributesServiceImpl struct { + logger *zap.SugaredLogger + attributesRepository repository.UserAttributesRepository +} + +type UserAttributesDto struct { + EmailId string `json:"emailId"` + Key string `json:"key"` + Value string `json:"value"` + UserId int32 `json:"-"` +} + +func NewUserAttributesServiceImpl(logger *zap.SugaredLogger, + attributesRepository repository.UserAttributesRepository) *UserAttributesServiceImpl { + serviceImpl := &UserAttributesServiceImpl{ + logger: logger, + attributesRepository: attributesRepository, + } + return serviceImpl +} + +func (impl UserAttributesServiceImpl) AddUserAttributes(request *UserAttributesDto) (*UserAttributesDto, error) { + dao := &repository.UserAttributesDao{ + EmailId: request.EmailId, + Key: request.Key, + Value: request.Value, + UserId: request.UserId, + } + _, err := impl.attributesRepository.AddUserAttribute(dao) + if err != nil { + impl.logger.Errorw("error in creating new user attributes for req", "req", request, "error", err) + return nil, err + } + return request, nil +} + +func (impl UserAttributesServiceImpl) UpdateUserAttributes(request *UserAttributesDto) (*UserAttributesDto, error) { + + userAttribute, err := impl.GetUserAttribute(request) + if err != nil { + impl.logger.Errorw("error while getting user attributes during update request", "req", request, "error", err) + return nil, err + } + if userAttribute == nil { + impl.logger.Info("not data found for request, so going to add instead of update", "req", request) + attributes, err := impl.AddUserAttributes(request) + if err != nil { + impl.logger.Errorw("error in adding new user attributes", "req", request, "error", err) + return nil, err + } + return attributes, nil + } + dao := &repository.UserAttributesDao{ + EmailId: request.EmailId, + Key: request.Key, + Value: request.Value, + UserId: request.UserId, + } + err = impl.attributesRepository.UpdateDataValByKey(dao) + if err != nil { + impl.logger.Errorw("error in update new attributes", "req", request, "error", err) + return nil, err + } + return request, nil +} + +func (impl UserAttributesServiceImpl) GetUserAttribute(request *UserAttributesDto) (*UserAttributesDto, error) { + + dao := &repository.UserAttributesDao{ + EmailId: request.EmailId, + Key: request.Key, + Value: request.Value, + UserId: request.UserId, + } + modelValue, err := impl.attributesRepository.GetDataValueByKey(dao) + if err == pg.ErrNoRows { + return nil, nil + } + if err != nil { + impl.logger.Errorw("error in fetching user attributes", "req", request, "error", err) + return nil, err + } + resAttrDto := &UserAttributesDto{ + EmailId: request.EmailId, + Key: request.Key, + Value: modelValue, + } + return resAttrDto, nil +} diff --git a/wire_gen.go b/wire_gen.go index 0bd53c9ea7..37ff02a535 100644 --- a/wire_gen.go +++ b/wire_gen.go @@ -1,7 +1,8 @@ // Code generated by Wire. DO NOT EDIT. //go:generate go run github.com/google/wire/cmd/wire -//+build !wireinject +//go:build !wireinject +// +build !wireinject package main @@ -520,6 +521,10 @@ func InitializeApp() (*App, error) { dashboardRouterImpl := dashboard.NewDashboardRouterImpl(sugaredLogger, dashboardConfig) attributesRestHandlerImpl := restHandler.NewAttributesRestHandlerImpl(sugaredLogger, enforcerImpl, userServiceImpl, attributesServiceImpl) attributesRouterImpl := router.NewAttributesRouterImpl(attributesRestHandlerImpl) + userAttributesRepositoryImpl := repository.NewUserAttributesRepositoryImpl(db) + userAttributesServiceImpl := attributes.NewUserAttributesServiceImpl(sugaredLogger, userAttributesRepositoryImpl) + userAttributesRestHandlerImpl := restHandler.NewUserAttributesRestHandlerImpl(sugaredLogger, enforcerImpl, userServiceImpl, userAttributesServiceImpl) + userAttributesRouterImpl := router.NewUserAttributesRouterImpl(userAttributesRestHandlerImpl) commonRestHanlderImpl := restHandler.NewCommonRestHanlderImpl(sugaredLogger, gitOpsConfigServiceImpl, userServiceImpl, validate, enforcerImpl, commonServiceImpl) commonRouterImpl := router.NewCommonRouterImpl(commonRestHanlderImpl) grafanaConfig, err := grafana.GetConfig() @@ -613,7 +618,7 @@ func InitializeApp() (*App, error) { webhookHelmServiceImpl := webhookHelm.NewWebhookHelmServiceImpl(sugaredLogger, helmAppServiceImpl, clusterServiceImplExtended, chartRepositoryServiceImpl, attributesServiceImpl) webhookHelmRestHandlerImpl := webhookHelm2.NewWebhookHelmRestHandlerImpl(sugaredLogger, webhookHelmServiceImpl, userServiceImpl, enforcerImpl, validate) webhookHelmRouterImpl := webhookHelm2.NewWebhookHelmRouterImpl(webhookHelmRestHandlerImpl) - muxRouter := router.NewMuxRouter(sugaredLogger, helmRouterImpl, pipelineConfigRouterImpl, migrateDbRouterImpl, appListingRouterImpl, environmentRouterImpl, clusterRouterImpl, webhookRouterImpl, userAuthRouterImpl, applicationRouterImpl, cdRouterImpl, projectManagementRouterImpl, gitProviderRouterImpl, gitHostRouterImpl, dockerRegRouterImpl, notificationRouterImpl, teamRouterImpl, gitWebhookHandlerImpl, workflowStatusUpdateHandlerImpl, applicationStatusUpdateHandlerImpl, ciEventHandlerImpl, pubSubClient, userRouterImpl, cronBasedEventReceiverImpl, chartRefRouterImpl, configMapRouterImpl, appStoreRouterImpl, chartRepositoryRouterImpl, releaseMetricsRouterImpl, deploymentGroupRouterImpl, batchOperationRouterImpl, chartGroupRouterImpl, testSuitRouterImpl, imageScanRouterImpl, policyRouterImpl, gitOpsConfigRouterImpl, dashboardRouterImpl, attributesRouterImpl, commonRouterImpl, grafanaRouterImpl, ssoLoginRouterImpl, telemetryRouterImpl, telemetryEventClientImplExtended, bulkUpdateRouterImpl, webhookListenerRouterImpl, appLabelRouterImpl, coreAppRouterImpl, helmAppRouterImpl, k8sApplicationRouterImpl, pProfRouterImpl, deploymentConfigRouterImpl, dashboardTelemetryRouterImpl, commonDeploymentRouterImpl, externalLinkRouterImpl, globalPluginRouterImpl, moduleRouterImpl, serverRouterImpl, apiTokenRouterImpl, helmApplicationStatusUpdateHandlerImpl, k8sCapacityRouterImpl, webhookHelmRouterImpl) + muxRouter := router.NewMuxRouter(sugaredLogger, helmRouterImpl, pipelineConfigRouterImpl, migrateDbRouterImpl, appListingRouterImpl, environmentRouterImpl, clusterRouterImpl, webhookRouterImpl, userAuthRouterImpl, applicationRouterImpl, cdRouterImpl, projectManagementRouterImpl, gitProviderRouterImpl, gitHostRouterImpl, dockerRegRouterImpl, notificationRouterImpl, teamRouterImpl, gitWebhookHandlerImpl, workflowStatusUpdateHandlerImpl, applicationStatusUpdateHandlerImpl, ciEventHandlerImpl, pubSubClient, userRouterImpl, cronBasedEventReceiverImpl, chartRefRouterImpl, configMapRouterImpl, appStoreRouterImpl, chartRepositoryRouterImpl, releaseMetricsRouterImpl, deploymentGroupRouterImpl, batchOperationRouterImpl, chartGroupRouterImpl, testSuitRouterImpl, imageScanRouterImpl, policyRouterImpl, gitOpsConfigRouterImpl, dashboardRouterImpl, attributesRouterImpl, userAttributesRouterImpl, commonRouterImpl, grafanaRouterImpl, ssoLoginRouterImpl, telemetryRouterImpl, telemetryEventClientImplExtended, bulkUpdateRouterImpl, webhookListenerRouterImpl, appLabelRouterImpl, coreAppRouterImpl, helmAppRouterImpl, k8sApplicationRouterImpl, pProfRouterImpl, deploymentConfigRouterImpl, dashboardTelemetryRouterImpl, commonDeploymentRouterImpl, externalLinkRouterImpl, globalPluginRouterImpl, moduleRouterImpl, serverRouterImpl, apiTokenRouterImpl, helmApplicationStatusUpdateHandlerImpl, k8sCapacityRouterImpl, webhookHelmRouterImpl) mainApp := NewApp(muxRouter, sugaredLogger, sseSSE, versionServiceImpl, syncedEnforcer, db, pubSubClient, sessionManager) return mainApp, nil } From 23e2580707c69ab9fe6bf06532e81197a5734d53 Mon Sep 17 00:00:00 2001 From: kripanshdevtron Date: Fri, 5 Aug 2022 18:50:22 +0530 Subject: [PATCH 03/14] error msg wrapped --- pkg/attributes/UserAttributesService.go | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/pkg/attributes/UserAttributesService.go b/pkg/attributes/UserAttributesService.go index 2084df7c1a..70d1cf85f4 100644 --- a/pkg/attributes/UserAttributesService.go +++ b/pkg/attributes/UserAttributesService.go @@ -18,6 +18,7 @@ package attributes import ( + "errors" "github.com/devtron-labs/devtron/internal/sql/repository" "github.com/go-pg/pg" "go.uber.org/zap" @@ -60,7 +61,7 @@ func (impl UserAttributesServiceImpl) AddUserAttributes(request *UserAttributesD _, err := impl.attributesRepository.AddUserAttribute(dao) if err != nil { impl.logger.Errorw("error in creating new user attributes for req", "req", request, "error", err) - return nil, err + return nil, errors.New("error occurred while creating user attributes") } return request, nil } @@ -70,14 +71,14 @@ func (impl UserAttributesServiceImpl) UpdateUserAttributes(request *UserAttribut userAttribute, err := impl.GetUserAttribute(request) if err != nil { impl.logger.Errorw("error while getting user attributes during update request", "req", request, "error", err) - return nil, err + return nil, errors.New("error occurred while updating user attributes") } if userAttribute == nil { impl.logger.Info("not data found for request, so going to add instead of update", "req", request) attributes, err := impl.AddUserAttributes(request) if err != nil { impl.logger.Errorw("error in adding new user attributes", "req", request, "error", err) - return nil, err + return nil, errors.New("error occurred while updating user attributes") } return attributes, nil } @@ -90,7 +91,7 @@ func (impl UserAttributesServiceImpl) UpdateUserAttributes(request *UserAttribut err = impl.attributesRepository.UpdateDataValByKey(dao) if err != nil { impl.logger.Errorw("error in update new attributes", "req", request, "error", err) - return nil, err + return nil, errors.New("error occurred while updating user attributes") } return request, nil } @@ -109,7 +110,7 @@ func (impl UserAttributesServiceImpl) GetUserAttribute(request *UserAttributesDt } if err != nil { impl.logger.Errorw("error in fetching user attributes", "req", request, "error", err) - return nil, err + return nil, errors.New("error occurred while getting user attributes") } resAttrDto := &UserAttributesDto{ EmailId: request.EmailId, From 0afb465b4518eb15baad873fccd7e55f895c9bf5 Mon Sep 17 00:00:00 2001 From: kripanshdevtron Date: Fri, 5 Aug 2022 20:30:02 +0530 Subject: [PATCH 04/14] get user attribute fix --- api/router/UserAttributesRouter.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/api/router/UserAttributesRouter.go b/api/router/UserAttributesRouter.go index 2d20d0a6fd..25924ab4f8 100644 --- a/api/router/UserAttributesRouter.go +++ b/api/router/UserAttributesRouter.go @@ -42,6 +42,6 @@ func (router UserAttributesRouterImpl) initAttributesRouter(attributesRouter *mu HandlerFunc(router.userAttributesRestHandler.AddUserAttributes).Methods("POST") attributesRouter.Path("/update"). HandlerFunc(router.userAttributesRestHandler.UpdateUserAttributes).Methods("PUT") - attributesRouter.Path(""). - HandlerFunc(router.userAttributesRestHandler.GetUserAttribute).Methods("GET") + attributesRouter.Path("/get"). + HandlerFunc(router.userAttributesRestHandler.GetUserAttribute).Methods("POST") } From a7360ff46d03b03186ee6b4b3a8ab18a4cbe9047 Mon Sep 17 00:00:00 2001 From: kripanshdevtron Date: Thu, 18 Aug 2022 19:31:50 +0530 Subject: [PATCH 05/14] update migrator file version --- ...ser_attributes.down.sql => 71_insert_user_attributes.down.sql} | 0 ...rt_user_attributes.up.sql => 71_insert_user_attributes.up.sql} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename scripts/sql/{65_insert_user_attributes.down.sql => 71_insert_user_attributes.down.sql} (100%) rename scripts/sql/{65_insert_user_attributes.up.sql => 71_insert_user_attributes.up.sql} (100%) diff --git a/scripts/sql/65_insert_user_attributes.down.sql b/scripts/sql/71_insert_user_attributes.down.sql similarity index 100% rename from scripts/sql/65_insert_user_attributes.down.sql rename to scripts/sql/71_insert_user_attributes.down.sql diff --git a/scripts/sql/65_insert_user_attributes.up.sql b/scripts/sql/71_insert_user_attributes.up.sql similarity index 100% rename from scripts/sql/65_insert_user_attributes.up.sql rename to scripts/sql/71_insert_user_attributes.up.sql From 67d6471b973cd25877502c727571156360431159 Mon Sep 17 00:00:00 2001 From: kripanshdevtron Date: Thu, 18 Aug 2022 20:35:51 +0530 Subject: [PATCH 06/14] code review comments incorporated --- api/restHandler/UserAttributesRestHandler.go | 53 +++++++++++++++----- api/router/UserAttributesRouter.go | 10 ++-- scripts/sql/71_insert_user_attributes.up.sql | 2 +- 3 files changed, 45 insertions(+), 20 deletions(-) diff --git a/api/restHandler/UserAttributesRestHandler.go b/api/restHandler/UserAttributesRestHandler.go index d06af40f17..3aec92bee7 100644 --- a/api/restHandler/UserAttributesRestHandler.go +++ b/api/restHandler/UserAttributesRestHandler.go @@ -21,9 +21,10 @@ import ( "encoding/json" "errors" "github.com/devtron-labs/devtron/api/restHandler/common" - user2 "github.com/devtron-labs/devtron/pkg/attributes" + "github.com/devtron-labs/devtron/pkg/attributes" "github.com/devtron-labs/devtron/pkg/user" "github.com/devtron-labs/devtron/pkg/user/casbin" + "github.com/gorilla/mux" "go.uber.org/zap" "net/http" ) @@ -38,11 +39,11 @@ type UserAttributesRestHandlerImpl struct { logger *zap.SugaredLogger enforcer casbin.Enforcer userService user.UserService - userAttributesService user2.UserAttributesService + userAttributesService attributes.UserAttributesService } func NewUserAttributesRestHandlerImpl(logger *zap.SugaredLogger, enforcer casbin.Enforcer, - userService user.UserService, userAttributesService user2.UserAttributesService) *UserAttributesRestHandlerImpl { + userService user.UserService, userAttributesService attributes.UserAttributesService) *UserAttributesRestHandlerImpl { userAuthHandler := &UserAttributesRestHandlerImpl{ logger: logger, enforcer: enforcer, @@ -51,14 +52,15 @@ func NewUserAttributesRestHandlerImpl(logger *zap.SugaredLogger, enforcer casbin } return userAuthHandler } -func (handler UserAttributesRestHandlerImpl) AddUserAttributes(w http.ResponseWriter, r *http.Request) { + +func (handler *UserAttributesRestHandlerImpl) AddUserAttributes(w http.ResponseWriter, r *http.Request) { userId, err := handler.userService.GetLoggedInUser(r) if userId == 0 || err != nil { common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized) return } decoder := json.NewDecoder(r.Body) - var dto user2.UserAttributesDto + var dto attributes.UserAttributesDto err = decoder.Decode(&dto) if err != nil { handler.logger.Errorw("request err, AddUserAttributes", "err", err, "payload", dto) @@ -72,6 +74,13 @@ func (handler UserAttributesRestHandlerImpl) AddUserAttributes(w http.ResponseWr common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden) return } + emailId, err := handler.userService.GetEmailFromToken(token) + if err != nil { + handler.logger.Errorw("request err, UpdateUserAttributes", "err", err, "payload", dto) + common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden) + return + } + dto.EmailId = emailId handler.logger.Infow("request payload, AddUserAttributes", "payload", dto) resp, err := handler.userAttributesService.AddUserAttributes(&dto) @@ -83,7 +92,7 @@ func (handler UserAttributesRestHandlerImpl) AddUserAttributes(w http.ResponseWr common.WriteJsonResp(w, nil, resp, http.StatusOK) } -func (handler UserAttributesRestHandlerImpl) UpdateUserAttributes(w http.ResponseWriter, r *http.Request) { +func (handler *UserAttributesRestHandlerImpl) UpdateUserAttributes(w http.ResponseWriter, r *http.Request) { userId, err := handler.userService.GetLoggedInUser(r) if userId == 0 || err != nil { common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized) @@ -91,7 +100,7 @@ func (handler UserAttributesRestHandlerImpl) UpdateUserAttributes(w http.Respons } decoder := json.NewDecoder(r.Body) - var dto user2.UserAttributesDto + var dto attributes.UserAttributesDto err = decoder.Decode(&dto) if err != nil { handler.logger.Errorw("request err, UpdateUserAttributes", "err", err, "payload", dto) @@ -106,6 +115,14 @@ func (handler UserAttributesRestHandlerImpl) UpdateUserAttributes(w http.Respons return } + emailId, err := handler.userService.GetEmailFromToken(token) + if err != nil { + handler.logger.Errorw("request err, UpdateUserAttributes", "err", err, "payload", dto) + common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden) + return + } + dto.EmailId = emailId + handler.logger.Infow("request payload, UpdateUserAttributes", "payload", dto) resp, err := handler.userAttributesService.UpdateUserAttributes(&dto) if err != nil { @@ -116,18 +133,17 @@ func (handler UserAttributesRestHandlerImpl) UpdateUserAttributes(w http.Respons common.WriteJsonResp(w, nil, resp, http.StatusOK) } -func (handler UserAttributesRestHandlerImpl) GetUserAttribute(w http.ResponseWriter, r *http.Request) { +func (handler *UserAttributesRestHandlerImpl) GetUserAttribute(w http.ResponseWriter, r *http.Request) { userId, err := handler.userService.GetLoggedInUser(r) if userId == 0 || err != nil { common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized) return } - decoder := json.NewDecoder(r.Body) - var dto user2.UserAttributesDto - err = decoder.Decode(&dto) - if err != nil { - handler.logger.Errorw("request err, GetUserAttribute", "err", err, "payload", dto) + vars := mux.Vars(r) + key := vars["key"] + if key == "" { + handler.logger.Errorw("request err, GetUserAttribute", "err", err, "key", key) common.WriteJsonResp(w, err, nil, http.StatusBadRequest) return } @@ -138,6 +154,17 @@ func (handler UserAttributesRestHandlerImpl) GetUserAttribute(w http.ResponseWri return } + dto := attributes.UserAttributesDto{} + + emailId, err := handler.userService.GetEmailFromToken(token) + if err != nil { + handler.logger.Errorw("request err, UpdateUserAttributes", "err", err, "payload", dto) + common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden) + return + } + dto.EmailId = emailId + dto.Key = key + res, err := handler.userAttributesService.GetUserAttribute(&dto) if err != nil { handler.logger.Errorw("service err, GetAttributesById", "err", err) diff --git a/api/router/UserAttributesRouter.go b/api/router/UserAttributesRouter.go index 25924ab4f8..7e1ea174ae 100644 --- a/api/router/UserAttributesRouter.go +++ b/api/router/UserAttributesRouter.go @@ -38,10 +38,8 @@ func NewUserAttributesRouterImpl(userAttributesRestHandler user.UserAttributesRe } func (router UserAttributesRouterImpl) initAttributesRouter(attributesRouter *mux.Router) { - attributesRouter.Path("/create"). - HandlerFunc(router.userAttributesRestHandler.AddUserAttributes).Methods("POST") - attributesRouter.Path("/update"). - HandlerFunc(router.userAttributesRestHandler.UpdateUserAttributes).Methods("PUT") - attributesRouter.Path("/get"). - HandlerFunc(router.userAttributesRestHandler.GetUserAttribute).Methods("POST") + attributesRouter.Path("/"). + HandlerFunc(router.userAttributesRestHandler.UpdateUserAttributes).Methods("POST") + attributesRouter.Path("/"). + HandlerFunc(router.userAttributesRestHandler.GetUserAttribute).Queries("key", "{key}").Methods("GET") } diff --git a/scripts/sql/71_insert_user_attributes.up.sql b/scripts/sql/71_insert_user_attributes.up.sql index 6102ac56ca..4bb4a151cf 100644 --- a/scripts/sql/71_insert_user_attributes.up.sql +++ b/scripts/sql/71_insert_user_attributes.up.sql @@ -2,7 +2,7 @@ -- Name: user_attributes; Type: TABLE; Schema: public; Owner: postgres -- -CREATE TABLE public.user_attributes ( +CREATE TABLE IF NOT EXISTS public.user_attributes ( email_id varchar(500) NOT NULL, user_data json NOT NULL, created_on timestamp with time zone, From b2ef4618aa444b99ca9d972f11e4b82a28a77250 Mon Sep 17 00:00:00 2001 From: kripanshdevtron Date: Thu, 18 Aug 2022 21:00:31 +0530 Subject: [PATCH 07/14] refactoring needed --- api/router/UserAttributesRouter.go | 8 ++++---- api/router/router.go | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/api/router/UserAttributesRouter.go b/api/router/UserAttributesRouter.go index 7e1ea174ae..5c195016df 100644 --- a/api/router/UserAttributesRouter.go +++ b/api/router/UserAttributesRouter.go @@ -23,7 +23,7 @@ import ( ) type UserAttributesRouter interface { - initAttributesRouter(helmRouter *mux.Router) + initUserAttributesRouter(helmRouter *mux.Router) } type UserAttributesRouterImpl struct { @@ -37,9 +37,9 @@ func NewUserAttributesRouterImpl(userAttributesRestHandler user.UserAttributesRe return router } -func (router UserAttributesRouterImpl) initAttributesRouter(attributesRouter *mux.Router) { - attributesRouter.Path("/"). +func (router UserAttributesRouterImpl) initUserAttributesRouter(attributesRouter *mux.Router) { + attributesRouter.Path("/update"). HandlerFunc(router.userAttributesRestHandler.UpdateUserAttributes).Methods("POST") - attributesRouter.Path("/"). + attributesRouter.Path("/get"). HandlerFunc(router.userAttributesRestHandler.GetUserAttribute).Queries("key", "{key}").Methods("GET") } diff --git a/api/router/router.go b/api/router/router.go index bb55eb3292..46c41a5328 100644 --- a/api/router/router.go +++ b/api/router/router.go @@ -327,7 +327,7 @@ func (r MuxRouter) Init() { r.attributesRouter.initAttributesRouter(attributeRouter) userAttributeRouter := r.Router.PathPrefix("/orchestrator/attributes/user").Subrouter() - r.userAttributesRouter.initAttributesRouter(userAttributeRouter) + r.userAttributesRouter.initUserAttributesRouter(userAttributeRouter) dashboardRouter := r.Router.PathPrefix("/dashboard").Subrouter() r.dashboardRouter.InitDashboardRouter(dashboardRouter) From cff926e7d18843f8724eb92fced0a5cdcff0b4ef Mon Sep 17 00:00:00 2001 From: kripanshdevtron Date: Thu, 18 Aug 2022 23:57:09 +0530 Subject: [PATCH 08/14] mentioned mapping for swagger generation --- api/restHandler/UserAttributesRestHandler.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/api/restHandler/UserAttributesRestHandler.go b/api/restHandler/UserAttributesRestHandler.go index 3aec92bee7..de22e7cca4 100644 --- a/api/restHandler/UserAttributesRestHandler.go +++ b/api/restHandler/UserAttributesRestHandler.go @@ -92,6 +92,12 @@ func (handler *UserAttributesRestHandlerImpl) AddUserAttributes(w http.ResponseW common.WriteJsonResp(w, nil, resp, http.StatusOK) } +// @Summary update user attributes +// @version 1.0 +// @produce application/json +// @Param payload body attributes.UserAttributesDto true "Input key" +// @Success 200 {object} attributes.UserAttributesDto +// @Router /orchestrator/attributes/user/update [POST] func (handler *UserAttributesRestHandlerImpl) UpdateUserAttributes(w http.ResponseWriter, r *http.Request) { userId, err := handler.userService.GetLoggedInUser(r) if userId == 0 || err != nil { @@ -133,6 +139,12 @@ func (handler *UserAttributesRestHandlerImpl) UpdateUserAttributes(w http.Respon common.WriteJsonResp(w, nil, resp, http.StatusOK) } +// @Summary get user attributes +// @version 1.0 +// @produce application/json +// @Param name query string true "Input key" +// @Success 200 {object} attributes.UserAttributesDto +// @Router /orchestrator/attributes/user/get [GET] func (handler *UserAttributesRestHandlerImpl) GetUserAttribute(w http.ResponseWriter, r *http.Request) { userId, err := handler.userService.GetLoggedInUser(r) if userId == 0 || err != nil { From 120db3f218422efa5788f9cff35eb8a1b283e0d1 Mon Sep 17 00:00:00 2001 From: kripanshdevtron Date: Fri, 26 Aug 2022 16:05:03 +0530 Subject: [PATCH 09/14] user attributes commited in EA mode also --- api/router/UserAttributesRouter.go | 4 ++-- api/router/router.go | 2 +- cmd/external-app/router.go | 7 +++++++ cmd/external-app/wire.go | 11 +++++++++++ cmd/external-app/wire_gen.go | 8 +++++++- 5 files changed, 28 insertions(+), 4 deletions(-) diff --git a/api/router/UserAttributesRouter.go b/api/router/UserAttributesRouter.go index 5c195016df..07ab87a1b6 100644 --- a/api/router/UserAttributesRouter.go +++ b/api/router/UserAttributesRouter.go @@ -23,7 +23,7 @@ import ( ) type UserAttributesRouter interface { - initUserAttributesRouter(helmRouter *mux.Router) + InitUserAttributesRouter(helmRouter *mux.Router) } type UserAttributesRouterImpl struct { @@ -37,7 +37,7 @@ func NewUserAttributesRouterImpl(userAttributesRestHandler user.UserAttributesRe return router } -func (router UserAttributesRouterImpl) initUserAttributesRouter(attributesRouter *mux.Router) { +func (router UserAttributesRouterImpl) InitUserAttributesRouter(attributesRouter *mux.Router) { attributesRouter.Path("/update"). HandlerFunc(router.userAttributesRestHandler.UpdateUserAttributes).Methods("POST") attributesRouter.Path("/get"). diff --git a/api/router/router.go b/api/router/router.go index 46c41a5328..e8af6c22c1 100644 --- a/api/router/router.go +++ b/api/router/router.go @@ -327,7 +327,7 @@ func (r MuxRouter) Init() { r.attributesRouter.initAttributesRouter(attributeRouter) userAttributeRouter := r.Router.PathPrefix("/orchestrator/attributes/user").Subrouter() - r.userAttributesRouter.initUserAttributesRouter(userAttributeRouter) + r.userAttributesRouter.InitUserAttributesRouter(userAttributeRouter) dashboardRouter := r.Router.PathPrefix("/dashboard").Subrouter() r.dashboardRouter.InitDashboardRouter(dashboardRouter) diff --git a/cmd/external-app/router.go b/cmd/external-app/router.go index 9d799ad0c1..b83ce8e5c8 100644 --- a/cmd/external-app/router.go +++ b/cmd/external-app/router.go @@ -13,6 +13,7 @@ import ( client "github.com/devtron-labs/devtron/api/helm-app" "github.com/devtron-labs/devtron/api/module" "github.com/devtron-labs/devtron/api/restHandler/common" + "github.com/devtron-labs/devtron/api/router" "github.com/devtron-labs/devtron/api/server" "github.com/devtron-labs/devtron/api/sso" "github.com/devtron-labs/devtron/api/team" @@ -50,6 +51,7 @@ type MuxRouter struct { apiTokenRouter apiToken.ApiTokenRouter k8sCapacityRouter k8s.K8sCapacityRouter webhookHelmRouter webhookHelm.WebhookHelmRouter + userAttributesRouter router.UserAttributesRouter } func NewMuxRouter( @@ -74,6 +76,7 @@ func NewMuxRouter( serverRouter server.ServerRouter, apiTokenRouter apiToken.ApiTokenRouter, k8sCapacityRouter k8s.K8sCapacityRouter, webhookHelmRouter webhookHelm.WebhookHelmRouter, + userAttributesRouter router.UserAttributesRouter, ) *MuxRouter { r := &MuxRouter{ Router: mux.NewRouter(), @@ -99,6 +102,7 @@ func NewMuxRouter( apiTokenRouter: apiTokenRouter, k8sCapacityRouter: k8sCapacityRouter, webhookHelmRouter: webhookHelmRouter, + userAttributesRouter: userAttributesRouter, } return r } @@ -206,4 +210,7 @@ func (r *MuxRouter) Init() { // webhook helm app router webhookHelmRouter := r.Router.PathPrefix("/orchestrator/webhook/helm").Subrouter() r.webhookHelmRouter.InitWebhookHelmRouter(webhookHelmRouter) + + userAttributeRouter := r.Router.PathPrefix("/orchestrator/attributes/user").Subrouter() + r.userAttributesRouter.InitUserAttributesRouter(userAttributeRouter) } diff --git a/cmd/external-app/wire.go b/cmd/external-app/wire.go index b16d775cca..0ed648d4b6 100644 --- a/cmd/external-app/wire.go +++ b/cmd/external-app/wire.go @@ -16,6 +16,8 @@ import ( "github.com/devtron-labs/devtron/api/externalLink" client "github.com/devtron-labs/devtron/api/helm-app" "github.com/devtron-labs/devtron/api/module" + "github.com/devtron-labs/devtron/api/restHandler" + "github.com/devtron-labs/devtron/api/router" "github.com/devtron-labs/devtron/api/server" "github.com/devtron-labs/devtron/api/sso" "github.com/devtron-labs/devtron/api/team" @@ -120,6 +122,15 @@ func InitializeApp() (*App, error) { //binding argoUserService to helm via dummy implementation(HelmUserServiceImpl) argo.NewHelmUserServiceImpl, wire.Bind(new(argo.ArgoUserService), new(*argo.HelmUserServiceImpl)), + + router.NewUserAttributesRouterImpl, + wire.Bind(new(router.UserAttributesRouter), new(*router.UserAttributesRouterImpl)), + restHandler.NewUserAttributesRestHandlerImpl, + wire.Bind(new(restHandler.UserAttributesRestHandler), new(*restHandler.UserAttributesRestHandlerImpl)), + attributes.NewUserAttributesServiceImpl, + wire.Bind(new(attributes.UserAttributesService), new(*attributes.UserAttributesServiceImpl)), + repository.NewUserAttributesRepositoryImpl, + wire.Bind(new(repository.UserAttributesRepository), new(*repository.UserAttributesRepositoryImpl)), ) return &App{}, nil } diff --git a/cmd/external-app/wire_gen.go b/cmd/external-app/wire_gen.go index 66ed6539d5..d7fbbb9a3b 100644 --- a/cmd/external-app/wire_gen.go +++ b/cmd/external-app/wire_gen.go @@ -21,6 +21,8 @@ import ( externalLink2 "github.com/devtron-labs/devtron/api/externalLink" client2 "github.com/devtron-labs/devtron/api/helm-app" module2 "github.com/devtron-labs/devtron/api/module" + "github.com/devtron-labs/devtron/api/restHandler" + "github.com/devtron-labs/devtron/api/router" server2 "github.com/devtron-labs/devtron/api/server" sso2 "github.com/devtron-labs/devtron/api/sso" team2 "github.com/devtron-labs/devtron/api/team" @@ -271,7 +273,11 @@ func InitializeApp() (*App, error) { webhookHelmServiceImpl := webhookHelm.NewWebhookHelmServiceImpl(sugaredLogger, helmAppServiceImpl, clusterServiceImpl, chartRepositoryServiceImpl, attributesServiceImpl) webhookHelmRestHandlerImpl := webhookHelm2.NewWebhookHelmRestHandlerImpl(sugaredLogger, webhookHelmServiceImpl, userServiceImpl, enforcerImpl, validate) webhookHelmRouterImpl := webhookHelm2.NewWebhookHelmRouterImpl(webhookHelmRestHandlerImpl) - muxRouter := NewMuxRouter(sugaredLogger, ssoLoginRouterImpl, teamRouterImpl, userAuthRouterImpl, userRouterImpl, clusterRouterImpl, dashboardRouterImpl, helmAppRouterImpl, environmentRouterImpl, k8sApplicationRouterImpl, chartRepositoryRouterImpl, appStoreDiscoverRouterImpl, appStoreValuesRouterImpl, appStoreDeploymentRouterImpl, dashboardTelemetryRouterImpl, commonDeploymentRouterImpl, externalLinkRouterImpl, moduleRouterImpl, serverRouterImpl, apiTokenRouterImpl, k8sCapacityRouterImpl, webhookHelmRouterImpl) + userAttributesRepositoryImpl := repository4.NewUserAttributesRepositoryImpl(db) + userAttributesServiceImpl := attributes.NewUserAttributesServiceImpl(sugaredLogger, userAttributesRepositoryImpl) + userAttributesRestHandlerImpl := restHandler.NewUserAttributesRestHandlerImpl(sugaredLogger, enforcerImpl, userServiceImpl, userAttributesServiceImpl) + userAttributesRouterImpl := router.NewUserAttributesRouterImpl(userAttributesRestHandlerImpl) + muxRouter := NewMuxRouter(sugaredLogger, ssoLoginRouterImpl, teamRouterImpl, userAuthRouterImpl, userRouterImpl, clusterRouterImpl, dashboardRouterImpl, helmAppRouterImpl, environmentRouterImpl, k8sApplicationRouterImpl, chartRepositoryRouterImpl, appStoreDiscoverRouterImpl, appStoreValuesRouterImpl, appStoreDeploymentRouterImpl, dashboardTelemetryRouterImpl, commonDeploymentRouterImpl, externalLinkRouterImpl, moduleRouterImpl, serverRouterImpl, apiTokenRouterImpl, k8sCapacityRouterImpl, webhookHelmRouterImpl, userAttributesRouterImpl) mainApp := NewApp(db, sessionManager, muxRouter, telemetryEventClientImpl, sugaredLogger) return mainApp, nil } From 7323a34147a333759ce8c506d4665b4591ce00e2 Mon Sep 17 00:00:00 2001 From: kripanshdevtron Date: Sun, 28 Aug 2022 20:29:11 +0530 Subject: [PATCH 10/14] send telemetry event API exposed --- api/restHandler/TelemetryRestHandler.go | 49 +++++++++++++++++++++++- api/router/TelemetryRouter.go | 3 ++ client/telemetry/TelemetryEventClient.go | 24 +++++++++++- wire_gen.go | 7 ++-- 4 files changed, 76 insertions(+), 7 deletions(-) diff --git a/api/restHandler/TelemetryRestHandler.go b/api/restHandler/TelemetryRestHandler.go index 1c8d807c9c..90e72e8a2d 100644 --- a/api/restHandler/TelemetryRestHandler.go +++ b/api/restHandler/TelemetryRestHandler.go @@ -18,24 +18,36 @@ package restHandler import ( + "encoding/json" + "errors" "github.com/devtron-labs/devtron/api/restHandler/common" "github.com/devtron-labs/devtron/client/telemetry" + "github.com/devtron-labs/devtron/pkg/user" + "github.com/devtron-labs/devtron/pkg/user/casbin" "go.uber.org/zap" "net/http" ) type TelemetryRestHandler interface { GetTelemetryMetaInfo(w http.ResponseWriter, r *http.Request) + SendTelemetryData(w http.ResponseWriter, r *http.Request) } type TelemetryRestHandlerImpl struct { logger *zap.SugaredLogger telemetryEventClient telemetry.TelemetryEventClient + enforcer casbin.Enforcer + userService user.UserService +} + +type TelemetryGenericEvent struct { + eventType string + eventPayload map[string]interface{} } func NewTelemetryRestHandlerImpl(logger *zap.SugaredLogger, - telemetryEventClient telemetry.TelemetryEventClient) *TelemetryRestHandlerImpl { - handler := &TelemetryRestHandlerImpl{logger: logger, telemetryEventClient: telemetryEventClient} + telemetryEventClient telemetry.TelemetryEventClient, enforcer casbin.Enforcer, userService user.UserService) *TelemetryRestHandlerImpl { + handler := &TelemetryRestHandlerImpl{logger: logger, telemetryEventClient: telemetryEventClient, enforcer: enforcer, userService: userService} return handler } @@ -48,3 +60,36 @@ func (handler TelemetryRestHandlerImpl) GetTelemetryMetaInfo(w http.ResponseWrit } common.WriteJsonResp(w, nil, res, http.StatusOK) } + +func (handler TelemetryRestHandlerImpl) SendTelemetryData(w http.ResponseWriter, r *http.Request) { + userId, err := handler.userService.GetLoggedInUser(r) + if userId == 0 || err != nil { + common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized) + return + } + decoder := json.NewDecoder(r.Body) + var payload map[string]interface{} + err = decoder.Decode(&payload) + if err != nil { + handler.logger.Errorw("request err, SendTelemetryData", "err", err, "payload", payload) + common.WriteJsonResp(w, err, nil, http.StatusBadRequest) + return + } + token := r.Header.Get("token") + if ok := handler.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionGet, "*"); !ok { + common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden) + return + } + + eventType := payload["eventType"] + eventTypeString := eventType.(string) + err = handler.telemetryEventClient.EnqueueGenericEvent(eventTypeString, payload) + + if err != nil { + handler.logger.Errorw("service err, SendTelemetryData", "err", err) + common.WriteJsonResp(w, err, nil, http.StatusInternalServerError) + return + } + common.WriteJsonResp(w, nil, "success", http.StatusOK) + +} diff --git a/api/router/TelemetryRouter.go b/api/router/TelemetryRouter.go index fdc0c168c4..822657658e 100644 --- a/api/router/TelemetryRouter.go +++ b/api/router/TelemetryRouter.go @@ -42,4 +42,7 @@ func NewTelemetryRouterImpl(logger *zap.SugaredLogger, handler restHandler.Telem func (router TelemetryRouterImpl) initTelemetryRouter(telemetryRouter *mux.Router) { telemetryRouter.Path("/meta"). HandlerFunc(router.handler.GetTelemetryMetaInfo).Methods("GET") + telemetryRouter.Path("/event"). + HandlerFunc(router.handler.SendTelemetryData).Methods("POST") + } diff --git a/client/telemetry/TelemetryEventClient.go b/client/telemetry/TelemetryEventClient.go index 7039ecf3c3..a60ba9e674 100644 --- a/client/telemetry/TelemetryEventClient.go +++ b/client/telemetry/TelemetryEventClient.go @@ -45,6 +45,7 @@ type TelemetryEventClient interface { SendTelemetryInstallEventEA() (*TelemetryEventType, error) SendTelemetryDashboardAccessEvent() error SendTelemetryDashboardLoggedInEvent() error + EnqueueGenericEvent(eventType string, prop map[string]interface{}) error } func NewTelemetryEventClientImpl(logger *zap.SugaredLogger, client *http.Client, clusterService cluster.ClusterService, @@ -205,6 +206,25 @@ func (impl *TelemetryEventClientImpl) SummaryEventForTelemetryEA() { } func (impl *TelemetryEventClientImpl) EnqueuePostHog(ucid string, eventType TelemetryEventType, prop map[string]interface{}) error { + return impl.EnqueueGenericPostHogEvent(ucid, string(eventType), prop) +} + +func (impl *TelemetryEventClientImpl) EnqueueGenericEvent(eventType string, prop map[string]interface{}) error { + ucid, err := impl.getUCID() + if err != nil { + impl.logger.Errorw("exception caught inside telemetry generic event", "err", err) + return nil + } + + if IsOptOut { + impl.logger.Warnw("client is opt-out for telemetry, there will be no events capture", "ucid", ucid) + return nil + } + + return impl.EnqueueGenericPostHogEvent(ucid, eventType, prop) +} + +func (impl *TelemetryEventClientImpl) EnqueueGenericPostHogEvent(ucid string, eventType string, prop map[string]interface{}) error { if impl.PosthogClient.Client == nil { impl.logger.Warn("no posthog client found, creating new") client, err := impl.retryPosthogClient(PosthogApiKey, PosthogEndpoint) @@ -215,11 +235,11 @@ func (impl *TelemetryEventClientImpl) EnqueuePostHog(ucid string, eventType Tele if impl.PosthogClient.Client != nil { err := impl.PosthogClient.Client.Enqueue(posthog.Capture{ DistinctId: ucid, - Event: string(eventType), + Event: eventType, Properties: prop, }) if err != nil { - impl.logger.Errorw("SummaryEventForTelemetry, failed to push event", "error", err) + impl.logger.Errorw("EnqueueGenericPostHogEvent, failed to push event", "error", err) return err } } diff --git a/wire_gen.go b/wire_gen.go index 696bb7a9f6..73622760e8 100644 --- a/wire_gen.go +++ b/wire_gen.go @@ -1,7 +1,8 @@ // Code generated by Wire. DO NOT EDIT. -//go:generate wire -//+build !wireinject +//go:generate go run github.com/google/wire/cmd/wire +//go:build !wireinject +// +build !wireinject package main @@ -544,7 +545,7 @@ func InitializeApp() (*App, error) { if err != nil { return nil, err } - telemetryRestHandlerImpl := restHandler.NewTelemetryRestHandlerImpl(sugaredLogger, telemetryEventClientImplExtended) + telemetryRestHandlerImpl := restHandler.NewTelemetryRestHandlerImpl(sugaredLogger, telemetryEventClientImplExtended, enforcerImpl, userServiceImpl) telemetryRouterImpl := router.NewTelemetryRouterImpl(sugaredLogger, telemetryRestHandlerImpl) bulkUpdateRepositoryImpl := bulkUpdate.NewBulkUpdateRepository(db, sugaredLogger) bulkUpdateServiceImpl := pipeline.NewBulkUpdateServiceImpl(bulkUpdateRepositoryImpl, chartRepositoryImpl, sugaredLogger, chartTemplateServiceImpl, chartRepoRepositoryImpl, defaultChart, utilMergeUtil, repositoryServiceClientImpl, chartRefRepositoryImpl, envConfigOverrideRepositoryImpl, pipelineConfigRepositoryImpl, configMapRepositoryImpl, environmentRepositoryImpl, pipelineRepositoryImpl, appLevelMetricsRepositoryImpl, envLevelAppMetricsRepositoryImpl, httpClient, appRepositoryImpl, deploymentTemplateHistoryServiceImpl, configMapHistoryServiceImpl) From 577cabf4e97e385e4231b1c48eb49514b4524c8b Mon Sep 17 00:00:00 2001 From: kripanshdevtron Date: Sun, 28 Aug 2022 21:20:05 +0530 Subject: [PATCH 11/14] refactoring --- api/restHandler/TelemetryRestHandler.go | 2 +- client/telemetry/TelemetryEventClient.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/api/restHandler/TelemetryRestHandler.go b/api/restHandler/TelemetryRestHandler.go index 90e72e8a2d..a0b9ca3209 100644 --- a/api/restHandler/TelemetryRestHandler.go +++ b/api/restHandler/TelemetryRestHandler.go @@ -83,7 +83,7 @@ func (handler TelemetryRestHandlerImpl) SendTelemetryData(w http.ResponseWriter, eventType := payload["eventType"] eventTypeString := eventType.(string) - err = handler.telemetryEventClient.EnqueueGenericEvent(eventTypeString, payload) + err = handler.telemetryEventClient.SendGenericTelemetryEvent(eventTypeString, payload) if err != nil { handler.logger.Errorw("service err, SendTelemetryData", "err", err) diff --git a/client/telemetry/TelemetryEventClient.go b/client/telemetry/TelemetryEventClient.go index a60ba9e674..0345d5d418 100644 --- a/client/telemetry/TelemetryEventClient.go +++ b/client/telemetry/TelemetryEventClient.go @@ -45,7 +45,7 @@ type TelemetryEventClient interface { SendTelemetryInstallEventEA() (*TelemetryEventType, error) SendTelemetryDashboardAccessEvent() error SendTelemetryDashboardLoggedInEvent() error - EnqueueGenericEvent(eventType string, prop map[string]interface{}) error + SendGenericTelemetryEvent(eventType string, prop map[string]interface{}) error } func NewTelemetryEventClientImpl(logger *zap.SugaredLogger, client *http.Client, clusterService cluster.ClusterService, @@ -209,7 +209,7 @@ func (impl *TelemetryEventClientImpl) EnqueuePostHog(ucid string, eventType Tele return impl.EnqueueGenericPostHogEvent(ucid, string(eventType), prop) } -func (impl *TelemetryEventClientImpl) EnqueueGenericEvent(eventType string, prop map[string]interface{}) error { +func (impl *TelemetryEventClientImpl) SendGenericTelemetryEvent(eventType string, prop map[string]interface{}) error { ucid, err := impl.getUCID() if err != nil { impl.logger.Errorw("exception caught inside telemetry generic event", "err", err) From f8e588bbb57b89ac926c247b1e04d97c1798417b Mon Sep 17 00:00:00 2001 From: kripanshdevtron Date: Wed, 31 Aug 2022 13:52:02 +0530 Subject: [PATCH 12/14] telemetry API for EA mode --- api/router/TelemetryRouter.go | 4 ++-- api/router/router.go | 2 +- cmd/external-app/router.go | 6 ++++++ cmd/external-app/wire.go | 5 +++++ cmd/external-app/wire_gen.go | 4 +++- 5 files changed, 17 insertions(+), 4 deletions(-) diff --git a/api/router/TelemetryRouter.go b/api/router/TelemetryRouter.go index 822657658e..c5ede43061 100644 --- a/api/router/TelemetryRouter.go +++ b/api/router/TelemetryRouter.go @@ -24,7 +24,7 @@ import ( ) type TelemetryRouter interface { - initTelemetryRouter(router *mux.Router) + InitTelemetryRouter(router *mux.Router) } type TelemetryRouterImpl struct { @@ -39,7 +39,7 @@ func NewTelemetryRouterImpl(logger *zap.SugaredLogger, handler restHandler.Telem return router } -func (router TelemetryRouterImpl) initTelemetryRouter(telemetryRouter *mux.Router) { +func (router TelemetryRouterImpl) InitTelemetryRouter(telemetryRouter *mux.Router) { telemetryRouter.Path("/meta"). HandlerFunc(router.handler.GetTelemetryMetaInfo).Methods("GET") telemetryRouter.Path("/event"). diff --git a/api/router/router.go b/api/router/router.go index e8af6c22c1..739d666c07 100644 --- a/api/router/router.go +++ b/api/router/router.go @@ -346,7 +346,7 @@ func (r MuxRouter) Init() { r.ssoLoginRouter.InitSsoLoginRouter(ssoLoginRouter) telemetryRouter := r.Router.PathPrefix("/orchestrator/telemetry").Subrouter() - r.telemetryRouter.initTelemetryRouter(telemetryRouter) + r.telemetryRouter.InitTelemetryRouter(telemetryRouter) bulkUpdateRouter := r.Router.PathPrefix("/orchestrator/batch").Subrouter() r.bulkUpdateRouter.initBulkUpdateRouter(bulkUpdateRouter) diff --git a/cmd/external-app/router.go b/cmd/external-app/router.go index b83ce8e5c8..ddfad7a296 100644 --- a/cmd/external-app/router.go +++ b/cmd/external-app/router.go @@ -52,6 +52,7 @@ type MuxRouter struct { k8sCapacityRouter k8s.K8sCapacityRouter webhookHelmRouter webhookHelm.WebhookHelmRouter userAttributesRouter router.UserAttributesRouter + telemetryRouter router.TelemetryRouter } func NewMuxRouter( @@ -77,6 +78,7 @@ func NewMuxRouter( k8sCapacityRouter k8s.K8sCapacityRouter, webhookHelmRouter webhookHelm.WebhookHelmRouter, userAttributesRouter router.UserAttributesRouter, + telemetryRouter router.TelemetryRouter, ) *MuxRouter { r := &MuxRouter{ Router: mux.NewRouter(), @@ -103,6 +105,7 @@ func NewMuxRouter( k8sCapacityRouter: k8sCapacityRouter, webhookHelmRouter: webhookHelmRouter, userAttributesRouter: userAttributesRouter, + telemetryRouter: telemetryRouter, } return r } @@ -213,4 +216,7 @@ func (r *MuxRouter) Init() { userAttributeRouter := r.Router.PathPrefix("/orchestrator/attributes/user").Subrouter() r.userAttributesRouter.InitUserAttributesRouter(userAttributeRouter) + + telemetryRouter := r.Router.PathPrefix("/orchestrator/telemetry").Subrouter() + r.telemetryRouter.InitTelemetryRouter(telemetryRouter) } diff --git a/cmd/external-app/wire.go b/cmd/external-app/wire.go index 0ed648d4b6..65106c2517 100644 --- a/cmd/external-app/wire.go +++ b/cmd/external-app/wire.go @@ -109,6 +109,11 @@ func InitializeApp() (*App, error) { wire.Value(chartRepoRepository.RefChartDir("scripts/devtron-reference-helm-charts")), + router.NewTelemetryRouterImpl, + wire.Bind(new(router.TelemetryRouter), new(*router.TelemetryRouterImpl)), + restHandler.NewTelemetryRestHandlerImpl, + wire.Bind(new(restHandler.TelemetryRestHandler), new(*restHandler.TelemetryRestHandlerImpl)), + //needed for sending events dashboardEvent.NewDashboardTelemetryRestHandlerImpl, wire.Bind(new(dashboardEvent.DashboardTelemetryRestHandler), new(*dashboardEvent.DashboardTelemetryRestHandlerImpl)), diff --git a/cmd/external-app/wire_gen.go b/cmd/external-app/wire_gen.go index d7fbbb9a3b..1c1f12ceee 100644 --- a/cmd/external-app/wire_gen.go +++ b/cmd/external-app/wire_gen.go @@ -277,7 +277,9 @@ func InitializeApp() (*App, error) { userAttributesServiceImpl := attributes.NewUserAttributesServiceImpl(sugaredLogger, userAttributesRepositoryImpl) userAttributesRestHandlerImpl := restHandler.NewUserAttributesRestHandlerImpl(sugaredLogger, enforcerImpl, userServiceImpl, userAttributesServiceImpl) userAttributesRouterImpl := router.NewUserAttributesRouterImpl(userAttributesRestHandlerImpl) - muxRouter := NewMuxRouter(sugaredLogger, ssoLoginRouterImpl, teamRouterImpl, userAuthRouterImpl, userRouterImpl, clusterRouterImpl, dashboardRouterImpl, helmAppRouterImpl, environmentRouterImpl, k8sApplicationRouterImpl, chartRepositoryRouterImpl, appStoreDiscoverRouterImpl, appStoreValuesRouterImpl, appStoreDeploymentRouterImpl, dashboardTelemetryRouterImpl, commonDeploymentRouterImpl, externalLinkRouterImpl, moduleRouterImpl, serverRouterImpl, apiTokenRouterImpl, k8sCapacityRouterImpl, webhookHelmRouterImpl, userAttributesRouterImpl) + telemetryRestHandlerImpl := restHandler.NewTelemetryRestHandlerImpl(sugaredLogger, telemetryEventClientImpl, enforcerImpl, userServiceImpl) + telemetryRouterImpl := router.NewTelemetryRouterImpl(sugaredLogger, telemetryRestHandlerImpl) + muxRouter := NewMuxRouter(sugaredLogger, ssoLoginRouterImpl, teamRouterImpl, userAuthRouterImpl, userRouterImpl, clusterRouterImpl, dashboardRouterImpl, helmAppRouterImpl, environmentRouterImpl, k8sApplicationRouterImpl, chartRepositoryRouterImpl, appStoreDiscoverRouterImpl, appStoreValuesRouterImpl, appStoreDeploymentRouterImpl, dashboardTelemetryRouterImpl, commonDeploymentRouterImpl, externalLinkRouterImpl, moduleRouterImpl, serverRouterImpl, apiTokenRouterImpl, k8sCapacityRouterImpl, webhookHelmRouterImpl, userAttributesRouterImpl, telemetryRouterImpl) mainApp := NewApp(db, sessionManager, muxRouter, telemetryEventClientImpl, sugaredLogger) return mainApp, nil } From 54f9abb9d951965756d5a314c00b832ed12dd635 Mon Sep 17 00:00:00 2001 From: kripanshdevtron Date: Wed, 31 Aug 2022 23:00:13 +0530 Subject: [PATCH 13/14] super admin permission removed --- api/restHandler/UserAttributesRestHandler.go | 24 ++++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/api/restHandler/UserAttributesRestHandler.go b/api/restHandler/UserAttributesRestHandler.go index de22e7cca4..0348ec599e 100644 --- a/api/restHandler/UserAttributesRestHandler.go +++ b/api/restHandler/UserAttributesRestHandler.go @@ -70,10 +70,10 @@ func (handler *UserAttributesRestHandlerImpl) AddUserAttributes(w http.ResponseW dto.UserId = userId token := r.Header.Get("token") - if ok := handler.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionCreate, "*"); !ok { - common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden) - return - } + //if ok := handler.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionCreate, "*"); !ok { + // common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden) + // return + //} emailId, err := handler.userService.GetEmailFromToken(token) if err != nil { handler.logger.Errorw("request err, UpdateUserAttributes", "err", err, "payload", dto) @@ -116,10 +116,10 @@ func (handler *UserAttributesRestHandlerImpl) UpdateUserAttributes(w http.Respon dto.UserId = userId token := r.Header.Get("token") - if ok := handler.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionUpdate, "*"); !ok { - common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden) - return - } + //if ok := handler.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionUpdate, "*"); !ok { + // common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden) + // return + //} emailId, err := handler.userService.GetEmailFromToken(token) if err != nil { @@ -161,10 +161,10 @@ func (handler *UserAttributesRestHandlerImpl) GetUserAttribute(w http.ResponseWr } token := r.Header.Get("token") - if ok := handler.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionGet, "*"); !ok { - common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden) - return - } + //if ok := handler.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionGet, "*"); !ok { + // common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden) + // return + //} dto := attributes.UserAttributesDto{} From a36d01d39c145f902030c209222c4545ebd8d2ef Mon Sep 17 00:00:00 2001 From: kripanshdevtron Date: Sat, 3 Sep 2022 18:45:01 +0530 Subject: [PATCH 14/14] db patch file updated --- ...ser_attributes.down.sql => 73_insert_user_attributes.down.sql} | 0 ...rt_user_attributes.up.sql => 73_insert_user_attributes.up.sql} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename scripts/sql/{71_insert_user_attributes.down.sql => 73_insert_user_attributes.down.sql} (100%) rename scripts/sql/{71_insert_user_attributes.up.sql => 73_insert_user_attributes.up.sql} (100%) diff --git a/scripts/sql/71_insert_user_attributes.down.sql b/scripts/sql/73_insert_user_attributes.down.sql similarity index 100% rename from scripts/sql/71_insert_user_attributes.down.sql rename to scripts/sql/73_insert_user_attributes.down.sql diff --git a/scripts/sql/71_insert_user_attributes.up.sql b/scripts/sql/73_insert_user_attributes.up.sql similarity index 100% rename from scripts/sql/71_insert_user_attributes.up.sql rename to scripts/sql/73_insert_user_attributes.up.sql