Skip to content

Commit

Permalink
main-merge
Browse files Browse the repository at this point in the history
  • Loading branch information
Shivam-nagar23 committed Feb 19, 2024
2 parents f71dd4f + f88c542 commit 2ab83cf
Show file tree
Hide file tree
Showing 8 changed files with 297 additions and 13 deletions.
184 changes: 182 additions & 2 deletions api/auth/user/UserRestHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,16 @@ type UserRestHandler interface {
UpdateUser(w http.ResponseWriter, r *http.Request)
GetById(w http.ResponseWriter, r *http.Request)
GetAll(w http.ResponseWriter, r *http.Request)
GetAllV2(w http.ResponseWriter, r *http.Request)
DeleteUser(w http.ResponseWriter, r *http.Request)
GetAllDetailedUsers(w http.ResponseWriter, r *http.Request)
BulkDeleteUsers(w http.ResponseWriter, r *http.Request)
FetchRoleGroupById(w http.ResponseWriter, r *http.Request)
CreateRoleGroup(w http.ResponseWriter, r *http.Request)
UpdateRoleGroup(w http.ResponseWriter, r *http.Request)
FetchRoleGroups(w http.ResponseWriter, r *http.Request)
FetchRoleGroupsV2(w http.ResponseWriter, r *http.Request)
FetchDetailedRoleGroups(w http.ResponseWriter, r *http.Request)
FetchRoleGroupsByName(w http.ResponseWriter, r *http.Request)
DeleteRoleGroup(w http.ResponseWriter, r *http.Request)
BulkDeleteRoleGroups(w http.ResponseWriter, r *http.Request)
Expand Down Expand Up @@ -303,7 +307,7 @@ func (handler UserRestHandlerImpl) GetById(w http.ResponseWriter, r *http.Reques
common.WriteJsonResp(w, err, res, http.StatusOK)
}

func (handler UserRestHandlerImpl) GetAll(w http.ResponseWriter, r *http.Request) {
func (handler UserRestHandlerImpl) GetAllV2(w http.ResponseWriter, r *http.Request) {
var decoder = schema.NewDecoder()
userId, err := handler.userService.GetLoggedInUser(r)
if userId == 0 || err != nil {
Expand Down Expand Up @@ -374,7 +378,95 @@ func (handler UserRestHandlerImpl) GetAll(w http.ResponseWriter, r *http.Request

common.WriteJsonResp(w, err, res, http.StatusOK)
}
func (handler UserRestHandlerImpl) GetAll(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
}

// RBAC enforcer applying
token := r.Header.Get("token")
//checking superAdmin access
isAuthorised := handler.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionGet, "*")
if !isAuthorised {
user, err := handler.userService.GetById(userId)
if err != nil {
handler.logger.Errorw("error in getting user by id", "err", err)
common.WriteJsonResp(w, err, "", http.StatusInternalServerError)
return
}
var roleFilters []bean.RoleFilter
if len(user.Groups) > 0 {
groupRoleFilters, err := handler.userService.GetRoleFiltersByGroupNames(user.Groups)
if err != nil {
handler.logger.Errorw("Error in getting role filters by group names", "err", err, "groupNames", user.Groups)
common.WriteJsonResp(w, err, "", http.StatusInternalServerError)
return
}
if len(groupRoleFilters) > 0 {
roleFilters = append(roleFilters, groupRoleFilters...)
}
}
if user.RoleFilters != nil && len(user.RoleFilters) > 0 {
roleFilters = append(roleFilters, user.RoleFilters...)
}
if len(roleFilters) > 0 {
for _, filter := range roleFilters {
if len(filter.Team) > 0 {
if ok := handler.enforcer.Enforce(token, casbin.ResourceUser, casbin.ActionGet, filter.Team); ok {
isAuthorised = true
break
}
}
if filter.Entity == bean.CLUSTER_ENTITIY {
if ok := handler.userCommonService.CheckRbacForClusterEntity(filter.Cluster, filter.Namespace, filter.Group, filter.Kind, filter.Resource, token, handler.CheckManagerAuth); ok {
isAuthorised = true
break
}
}
}
}
}
if !isAuthorised {
common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)
return
}
res, err := handler.userService.GetAll()
if err != nil {
handler.logger.Errorw("service err, GetAll", "err", err)
common.WriteJsonResp(w, err, "Failed to Get", http.StatusInternalServerError)
return
}

common.WriteJsonResp(w, err, res, http.StatusOK)
}

func (handler UserRestHandlerImpl) GetAllDetailedUsers(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
}

token := r.Header.Get("token")
isActionUserSuperAdmin := false
if ok := handler.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionGet, "*"); ok {
isActionUserSuperAdmin = true
}
if !isActionUserSuperAdmin {
common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)
return
}
res, err := handler.userService.GetAllDetailedUsers()
if err != nil {
handler.logger.Errorw("service err, GetAllDetailedUsers", "err", err)
common.WriteJsonResp(w, err, "Failed to Get", http.StatusInternalServerError)
return
}

common.WriteJsonResp(w, err, res, http.StatusOK)
}
func (handler UserRestHandlerImpl) DeleteUser(w http.ResponseWriter, r *http.Request) {
userId, err := handler.userService.GetLoggedInUser(r)
if userId == 0 || err != nil {
Expand Down Expand Up @@ -673,7 +765,7 @@ func (handler UserRestHandlerImpl) UpdateRoleGroup(w http.ResponseWriter, r *htt
common.WriteJsonResp(w, err, res, http.StatusOK)
}

func (handler UserRestHandlerImpl) FetchRoleGroups(w http.ResponseWriter, r *http.Request) {
func (handler UserRestHandlerImpl) FetchRoleGroupsV2(w http.ResponseWriter, r *http.Request) {
var decoder = schema.NewDecoder()
userId, err := handler.userService.GetLoggedInUser(r)
if userId == 0 || err != nil {
Expand Down Expand Up @@ -745,6 +837,94 @@ func (handler UserRestHandlerImpl) FetchRoleGroups(w http.ResponseWriter, r *htt
common.WriteJsonResp(w, err, res, http.StatusOK)
}

func (handler UserRestHandlerImpl) FetchRoleGroups(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
}
// RBAC enforcer applying
token := r.Header.Get("token")
//checking superAdmin access
isAuthorised := handler.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionGet, "*")
if !isAuthorised {
user, err := handler.userService.GetById(userId)
if err != nil {
handler.logger.Errorw("error in getting user by id", "err", err)
common.WriteJsonResp(w, err, "", http.StatusInternalServerError)
return
}
var roleFilters []bean.RoleFilter
if len(user.Groups) > 0 {
groupRoleFilters, err := handler.userService.GetRoleFiltersByGroupNames(user.Groups)
if err != nil {
handler.logger.Errorw("Error in getting role filters by group names", "err", err, "groupNames", user.Groups)
common.WriteJsonResp(w, err, "", http.StatusInternalServerError)
return
}
if len(groupRoleFilters) > 0 {
roleFilters = append(roleFilters, groupRoleFilters...)
}
}
if user.RoleFilters != nil && len(user.RoleFilters) > 0 {
roleFilters = append(roleFilters, user.RoleFilters...)
}
if len(roleFilters) > 0 {
for _, filter := range roleFilters {
if len(filter.Team) > 0 {
if ok := handler.enforcer.Enforce(token, casbin.ResourceUser, casbin.ActionGet, filter.Team); ok {
isAuthorised = true
break
}
}
if filter.Entity == bean.CLUSTER_ENTITIY {
if isValidAuth := handler.userCommonService.CheckRbacForClusterEntity(filter.Cluster, filter.Namespace, filter.Group, filter.Kind, filter.Resource, token, handler.CheckManagerAuth); isValidAuth {
isAuthorised = true
break
}
}

}
}
}
if !isAuthorised {
common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)
return
}
res, err := handler.roleGroupService.FetchRoleGroups()
if err != nil {
handler.logger.Errorw("service err, FetchRoleGroups", "err", err)
common.WriteJsonResp(w, err, "", http.StatusInternalServerError)
return
}
common.WriteJsonResp(w, err, res, http.StatusOK)
}

func (handler UserRestHandlerImpl) FetchDetailedRoleGroups(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
}
token := r.Header.Get("token")
isActionUserSuperAdmin := false
if ok := handler.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionGet, "*"); ok {
isActionUserSuperAdmin = true
}
if !isActionUserSuperAdmin {
common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)
return
}
req := &bean.ListingRequest{ShowAll: true}
res, err := handler.roleGroupService.FetchDetailedRoleGroups(req)
if err != nil {
handler.logger.Errorw("service err, FetchRoleGroups", "err", err)
common.WriteJsonResp(w, err, "", http.StatusInternalServerError)
return
}
common.WriteJsonResp(w, err, res, http.StatusOK)
}

func (handler UserRestHandlerImpl) FetchRoleGroupsByName(w http.ResponseWriter, r *http.Request) {
userId, err := handler.userService.GetLoggedInUser(r)
if userId == 0 || err != nil {
Expand Down
8 changes: 8 additions & 0 deletions api/auth/user/UserRouter.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ func NewUserRouterImpl(userRestHandler UserRestHandler) *UserRouterImpl {

func (router UserRouterImpl) InitUserRouter(userAuthRouter *mux.Router) {
//User management
userAuthRouter.Path("/v2").
HandlerFunc(router.userRestHandler.GetAllV2).Methods("GET")
userAuthRouter.Path("/{id}").
HandlerFunc(router.userRestHandler.GetById).Methods("GET")
userAuthRouter.Path("").
Expand All @@ -50,7 +52,11 @@ func (router UserRouterImpl) InitUserRouter(userAuthRouter *mux.Router) {
HandlerFunc(router.userRestHandler.BulkDeleteUsers).Methods("DELETE")
userAuthRouter.Path("/{id}").
HandlerFunc(router.userRestHandler.DeleteUser).Methods("DELETE")
userAuthRouter.Path("/detail/get").
HandlerFunc(router.userRestHandler.GetAllDetailedUsers).Methods("GET")

userAuthRouter.Path("/role/group/v2").
HandlerFunc(router.userRestHandler.FetchRoleGroupsV2).Methods("GET")
userAuthRouter.Path("/role/group/{id}").
HandlerFunc(router.userRestHandler.FetchRoleGroupById).Methods("GET")
userAuthRouter.Path("/role/group").
Expand All @@ -59,6 +65,8 @@ func (router UserRouterImpl) InitUserRouter(userAuthRouter *mux.Router) {
HandlerFunc(router.userRestHandler.UpdateRoleGroup).Methods("PUT")
userAuthRouter.Path("/role/group").
HandlerFunc(router.userRestHandler.FetchRoleGroups).Methods("GET")
userAuthRouter.Path("/role/group/detailed/get").
HandlerFunc(router.userRestHandler.FetchDetailedRoleGroups).Methods("GET")
userAuthRouter.Path("/role/group/search").
Queries("name", "{name}").
HandlerFunc(router.userRestHandler.FetchRoleGroupsByName).Methods("GET")
Expand Down
2 changes: 1 addition & 1 deletion api/bean/UserRequest.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ type UserRole struct {

type UserInfo struct {
Id int32 `json:"id" validate:"number,not-system-admin-userid"`
EmailId string `json:"emailId" validate:"required,not-system-admin-user"`
EmailId string `json:"email_id" validate:"required,not-system-admin-user"` // TODO : have to migrate json key to emailId and also handle backward compatibility
Roles []string `json:"roles,omitempty"`
AccessToken string `json:"access_token,omitempty"`
RoleFilters []RoleFilter `json:"roleFilters"`
Expand Down
35 changes: 30 additions & 5 deletions pkg/auth/user/RoleGroupService.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@ import (
type RoleGroupService interface {
CreateRoleGroup(request *bean.RoleGroup) (*bean.RoleGroup, error)
UpdateRoleGroup(request *bean.RoleGroup, token string, managerAuth func(resource, token string, object string) bool) (*bean.RoleGroup, error)
FetchDetailedRoleGroups(req *bean.ListingRequest) ([]*bean.RoleGroup, error)
FetchRoleGroupsById(id int32) (*bean.RoleGroup, error)
FetchRoleGroups(req *bean.ListingRequest) (*bean.RoleGroupListingResponse, error)
FetchRoleGroups() ([]*bean.RoleGroup, error)
FetchRoleGroupsV2(req *bean.ListingRequest) (*bean.RoleGroupListingResponse, error)
FetchRoleGroupsWithFilters(request *bean.ListingRequest) (*bean.RoleGroupListingResponse, error)
FetchRoleGroupsByName(name string) ([]*bean.RoleGroup, error)
DeleteRoleGroup(model *bean.RoleGroup) (bool, error)
Expand Down Expand Up @@ -588,7 +590,7 @@ func (impl RoleGroupServiceImpl) getRoleGroupMetadata(roleGroup *repository.Role
return roleFilters, isSuperAdmin
}

func (impl RoleGroupServiceImpl) fetchDetailedRoleGroups(req *bean.ListingRequest) ([]*bean.RoleGroup, error) {
func (impl RoleGroupServiceImpl) FetchDetailedRoleGroups(req *bean.ListingRequest) ([]*bean.RoleGroup, error) {
query := helper.GetQueryForGroupListingWithFilters(req)
roleGroups, err := impl.roleGroupRepository.GetAllExecutingQuery(query)
if err != nil {
Expand Down Expand Up @@ -622,8 +624,31 @@ func (impl RoleGroupServiceImpl) fetchDetailedRoleGroups(req *bean.ListingReques
return list, nil
}

func (impl RoleGroupServiceImpl) FetchRoleGroups(req *bean.ListingRequest) (*bean.RoleGroupListingResponse, error) {
list, err := impl.fetchDetailedRoleGroups(req)
func (impl RoleGroupServiceImpl) FetchRoleGroups() ([]*bean.RoleGroup, error) {
roleGroup, err := impl.roleGroupRepository.GetAllRoleGroup()
if err != nil {
impl.logger.Errorw("error while fetching user from db", "error", err)
return nil, err
}
var list []*bean.RoleGroup
for _, item := range roleGroup {
bean := &bean.RoleGroup{
Id: item.Id,
Name: item.Name,
Description: item.Description,
RoleFilters: make([]bean.RoleFilter, 0),
}
list = append(list, bean)
}

if len(list) == 0 {
list = make([]*bean.RoleGroup, 0)
}
return list, nil
}

func (impl RoleGroupServiceImpl) FetchRoleGroupsV2(req *bean.ListingRequest) (*bean.RoleGroupListingResponse, error) {
list, err := impl.FetchDetailedRoleGroups(req)
if err != nil {
impl.logger.Errorw("error in FetchDetailedRoleGroups", "err", err)
return nil, err
Expand All @@ -640,7 +665,7 @@ func (impl RoleGroupServiceImpl) FetchRoleGroupsWithFilters(request *bean.Listin
// default values will be used if not provided
impl.userCommonService.SetDefaultValuesIfNotPresent(request, true)
if request.ShowAll {
return impl.FetchRoleGroups(request)
return impl.FetchRoleGroupsV2(request)
}

// setting count check to true for getting only count
Expand Down
32 changes: 32 additions & 0 deletions pkg/auth/user/UserService.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ type UserService interface {
GetById(id int32) (*bean.UserInfo, error)
GetAll() ([]bean.UserInfo, error)
GetAllWithFilters(request *bean.ListingRequest) (*bean.UserListingResponse, error)
GetAllDetailedUsers() ([]bean.UserInfo, error)
GetEmailFromToken(token string) (string, error)
GetEmailById(userId int32) (string, error)
GetLoggedInUser(r *http.Request) (int32, error)
Expand Down Expand Up @@ -1055,6 +1056,37 @@ func (impl *UserServiceImpl) getAllDetailedUsers(req *bean.ListingRequest) ([]be
return response, nil
}

func (impl *UserServiceImpl) GetAllDetailedUsers() ([]bean.UserInfo, error) {
models, err := impl.userRepository.GetAllExcludingApiTokenUser()
if err != nil {
impl.logger.Errorw("error while fetching user from db", "error", err)
return nil, err
}
var response []bean.UserInfo
for _, model := range models {
isSuperAdmin, roleFilters, filterGroups := impl.getUserMetadata(&model)
for index, roleFilter := range roleFilters {
if roleFilter.Entity == "" {
roleFilters[index].Entity = bean2.ENTITY_APPS
}
if roleFilter.Entity == bean2.ENTITY_APPS && roleFilter.AccessType == "" {
roleFilters[index].AccessType = bean2.DEVTRON_APP
}
}
response = append(response, bean.UserInfo{
Id: model.Id,
EmailId: model.EmailId,
RoleFilters: roleFilters,
Groups: filterGroups,
SuperAdmin: isSuperAdmin,
})
}
if len(response) == 0 {
response = make([]bean.UserInfo, 0)
}
return response, nil
}

func (impl *UserServiceImpl) UserExists(emailId string) bool {
model, err := impl.userRepository.FetchActiveUserByEmail(emailId)
if err != nil {
Expand Down
Loading

0 comments on commit 2ab83cf

Please sign in to comment.