Repository: devtron-labs/devtron
Pull request #3274 (2023-04-12 13:08:31)

feat: optimised user addition/creation flows
<!--
Type of change: Title of the PR should clearly mention which type of PR is this, you can select any of the below mentioned types:

- docs - The PR contains Documentation ONLY changes. 
- feat - The PR contains new feature/enhancements.
- fix - The PR contains a bug fix.
- chore - Development changes related to the build system (involving scripts, configurations or tools) and package dependencies.
- test - Development changes related to tests.
- perf - Changes related to performance improvements.

Example Title: 
docs: Webhook CI documentation changes
-->

# Description
Added new default rbac policies and role structure. Cached both of them and added own rendering logic for faster processing.


## How Has This Been Tested?
Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration
- [x] Local Environment
- [x] Test Cluster

## Checklist:

* [ ] The title of the PR states what changed and the related issues number (used for the release note).
* [ ] Does this PR requires documentation updates?
* [ ] I've updated documentation as required by this PR.
* [ ] I have performed a self-review of my own code.
* [ ] I have commented my code, particularly in hard-to-understand areas.
* [ ] I have tested it for all user roles.
* [ ] I have added all the required unit/api test cases.

## Does this PR introduce a user-facing change?
<!--
If NO, leave the release-note block blank.
If YES, a release note is required:
Enter your extended release note in the block below. If the PR requires additional manual action from users switching to the new version, include the string "action-required".

-->
```release-note

```



sonarcloud[bot]: SonarCloud Quality Gate failed.&nbsp; &nbsp; [![Quality Gate failed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/failed-16px.png 'Quality Gate failed')](https://sonarcloud.io/dashboard?id=devtron-labs_devtron&pullRequest=3274)

[![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=BUG)  
[![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=VULNERABILITY)  
[![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=SECURITY_HOTSPOT)  
[![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=CODE_SMELL) [6 Code Smells](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=CODE_SMELL)

[![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=devtron-labs_devtron&pullRequest=3274) No Coverage information  
[![5.1%](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/10-16px.png '5.1%')](https://sonarcloud.io/component_measures?id=devtron-labs_devtron&pullRequest=3274&metric=new_duplicated_lines_density&view=list) [5.1% Duplication](https://sonarcloud.io/component_measures?id=devtron-labs_devtron&pullRequest=3274&metric=new_duplicated_lines_density&view=list)


sonarcloud[bot]: SonarCloud Quality Gate failed.&nbsp; &nbsp; [![Quality Gate failed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/failed-16px.png 'Quality Gate failed')](https://sonarcloud.io/dashboard?id=devtron-labs_devtron&pullRequest=3274)

[![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=BUG)  
[![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=VULNERABILITY)  
[![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=SECURITY_HOTSPOT)  
[![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=CODE_SMELL) [6 Code Smells](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=CODE_SMELL)

[![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=devtron-labs_devtron&pullRequest=3274) No Coverage information  
[![5.0%](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/10-16px.png '5.0%')](https://sonarcloud.io/component_measures?id=devtron-labs_devtron&pullRequest=3274&metric=new_duplicated_lines_density&view=list) [5.0% Duplication](https://sonarcloud.io/component_measures?id=devtron-labs_devtron&pullRequest=3274&metric=new_duplicated_lines_density&view=list)


sonarcloud[bot]: SonarCloud Quality Gate failed.&nbsp; &nbsp; [![Quality Gate failed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/failed-16px.png 'Quality Gate failed')](https://sonarcloud.io/dashboard?id=devtron-labs_devtron&pullRequest=3274)

[![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=BUG)  
[![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=VULNERABILITY)  
[![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=SECURITY_HOTSPOT)  
[![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=CODE_SMELL) [6 Code Smells](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=CODE_SMELL)

[![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=devtron-labs_devtron&pullRequest=3274) No Coverage information  
[![5.0%](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/10-16px.png '5.0%')](https://sonarcloud.io/component_measures?id=devtron-labs_devtron&pullRequest=3274&metric=new_duplicated_lines_density&view=list) [5.0% Duplication](https://sonarcloud.io/component_measures?id=devtron-labs_devtron&pullRequest=3274&metric=new_duplicated_lines_density&view=list)


sonarcloud[bot]: SonarCloud Quality Gate failed.&nbsp; &nbsp; [![Quality Gate failed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/failed-16px.png 'Quality Gate failed')](https://sonarcloud.io/dashboard?id=devtron-labs_devtron&pullRequest=3274)

[![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=BUG)  
[![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=VULNERABILITY)  
[![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=SECURITY_HOTSPOT)  
[![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=CODE_SMELL) [6 Code Smells](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=CODE_SMELL)

[![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=devtron-labs_devtron&pullRequest=3274) No Coverage information  
[![5.0%](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/10-16px.png '5.0%')](https://sonarcloud.io/component_measures?id=devtron-labs_devtron&pullRequest=3274&metric=new_duplicated_lines_density&view=list) [5.0% Duplication](https://sonarcloud.io/component_measures?id=devtron-labs_devtron&pullRequest=3274&metric=new_duplicated_lines_density&view=list)


sonarcloud[bot]: SonarCloud Quality Gate failed.&nbsp; &nbsp; [![Quality Gate failed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/failed-16px.png 'Quality Gate failed')](https://sonarcloud.io/dashboard?id=devtron-labs_devtron&pullRequest=3274)

[![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=BUG)  
[![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=VULNERABILITY)  
[![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=SECURITY_HOTSPOT)  
[![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=CODE_SMELL) [6 Code Smells](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=CODE_SMELL)

[![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=devtron-labs_devtron&pullRequest=3274) No Coverage information  
[![5.0%](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/10-16px.png '5.0%')](https://sonarcloud.io/component_measures?id=devtron-labs_devtron&pullRequest=3274&metric=new_duplicated_lines_density&view=list) [5.0% Duplication](https://sonarcloud.io/component_measures?id=devtron-labs_devtron&pullRequest=3274&metric=new_duplicated_lines_density&view=list)


sonarcloud[bot]: SonarCloud Quality Gate failed.&nbsp; &nbsp; [![Quality Gate failed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/failed-16px.png 'Quality Gate failed')](https://sonarcloud.io/dashboard?id=devtron-labs_devtron&pullRequest=3274)

[![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=BUG)  
[![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=VULNERABILITY)  
[![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=SECURITY_HOTSPOT)  
[![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=CODE_SMELL) [6 Code Smells](https://sonarcloud.io/project/issues?id=devtron-labs_devtron&pullRequest=3274&resolved=false&types=CODE_SMELL)

[![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=devtron-labs_devtron&pullRequest=3274) No Coverage information  
[![5.0%](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/10-16px.png '5.0%')](https://sonarcloud.io/component_measures?id=devtron-labs_devtron&pullRequest=3274&metric=new_duplicated_lines_density&view=list) [5.0% Duplication](https://sonarcloud.io/component_measures?id=devtron-labs_devtron&pullRequest=3274&metric=new_duplicated_lines_density&view=list)



Patch:
diff --git a/api/externalLink/ExternalLinkRestHandler.go b/api/externalLink/ExternalLinkRestHandler.go
index 997bd9dec..785eafe2b 100644
--- a/api/externalLink/ExternalLinkRestHandler.go
+++ b/api/externalLink/ExternalLinkRestHandler.go
@@ -37,6 +37,7 @@ type ExternalLinkRestHandler interface {
 	CreateExternalLinks(w http.ResponseWriter, r *http.Request)
 	GetExternalLinkMonitoringTools(w http.ResponseWriter, r *http.Request)
 	GetExternalLinks(w http.ResponseWriter, r *http.Request)
+	GetExternalLinksV2(w http.ResponseWriter, r *http.Request)
 	UpdateExternalLink(w http.ResponseWriter, r *http.Request)
 	DeleteExternalLink(w http.ResponseWriter, r *http.Request) // Update is_active to false link
 }
@@ -134,6 +135,7 @@ func (impl ExternalLinkRestHandlerImpl) GetExternalLinkMonitoringTools(w http.Re
 	}
 	common.WriteJsonResp(w, err, res, http.StatusOK)
 }
+
 func (impl ExternalLinkRestHandlerImpl) GetExternalLinks(w http.ResponseWriter, r *http.Request) {
 	userId, err := impl.userService.GetLoggedInUser(r)
 	if userId == 0 || err != nil {
@@ -146,6 +148,65 @@ func (impl ExternalLinkRestHandlerImpl) GetExternalLinks(w http.ResponseWriter,
 	linkType := v.Get("type")
 	identifier := v.Get("identifier")
 
+	token := r.Header.Get("token")
+	if len(identifier) == 0 && len(linkType) == 0 && len(clusterId) == 0 {
+		if ok := impl.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionGet, "*"); !ok {
+			common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)
+			return
+		}
+		clusterIdNumber := 0
+		res, err := impl.externalLinkService.FetchAllActiveLinksByLinkIdentifier(nil, clusterIdNumber)
+		if err != nil {
+			impl.logger.Errorw("service err, FetchAllActive", "err", err)
+			common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
+			return
+		}
+		common.WriteJsonResp(w, err, res, http.StatusOK)
+		return
+
+	} else if len(identifier) != 0 && len(linkType) != 0 { //api to get external links from app-level external links tab and from app-details page
+		clusterIdNumber := 0
+		if len(clusterId) != 0 { //api call from app-detail page
+			clusterIdNumber, err = strconv.Atoi(clusterId)
+			if err != nil {
+				impl.logger.Errorw("error occurred while parsing cluster_id", "clusterId", clusterId, "err", err)
+				common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
+				return
+			}
+		}
+		linkIdentifier := &externalLink.LinkIdentifier{
+			Type:       linkType,
+			Identifier: identifier,
+			ClusterId:  0,
+		}
+		res, err := impl.externalLinkService.FetchAllActiveLinksByLinkIdentifier(linkIdentifier, clusterIdNumber)
+		if err != nil {
+			impl.logger.Errorw("service err, FetchAllActive", "err", err)
+			common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
+			return
+		}
+		common.WriteJsonResp(w, err, res, http.StatusOK)
+		return
+	}
+
+	impl.logger.Errorw("invalid request, FetchAllActive external links", "err", err)
+	common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
+	return
+
+}
+
+func (impl ExternalLinkRestHandlerImpl) GetExternalLinksV2(w http.ResponseWriter, r *http.Request) {
+	userId, err := impl.userService.GetLoggedInUser(r)
+	if userId == 0 || err != nil {
+		common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
+		return
+	}
+
+	v := r.URL.Query()
+	clusterId := v.Get("clusterId")
+	linkType := v.Get("type")
+	identifier := v.Get("identifier")
+
 	externalLinkAndMonitoringTools := externalLink.ExternalLinkAndMonitoringToolDTO{}
 	externalLinks := []*externalLink.ExternalLinkDto{}
 
diff --git a/api/externalLink/ExternalLinkRouter.go b/api/externalLink/ExternalLinkRouter.go
index 07abfef60..93de60094 100644
--- a/api/externalLink/ExternalLinkRouter.go
+++ b/api/externalLink/ExternalLinkRouter.go
@@ -19,6 +19,7 @@ func (impl ExternalLinkRouterImpl) InitExternalLinkRouter(configRouter *mux.Rout
 	configRouter.Path("").HandlerFunc(impl.externalLinkRestHandler.CreateExternalLinks).Methods("POST")
 	configRouter.Path("/tools").HandlerFunc(impl.externalLinkRestHandler.GetExternalLinkMonitoringTools).Methods("GET")
 	configRouter.Path("").HandlerFunc(impl.externalLinkRestHandler.GetExternalLinks).Methods("GET")
+	configRouter.Path("/v2").HandlerFunc(impl.externalLinkRestHandler.GetExternalLinksV2).Methods("GET")
 	configRouter.Path("").HandlerFunc(impl.externalLinkRestHandler.UpdateExternalLink).Methods("PUT")
 	configRouter.Path("").HandlerFunc(impl.externalLinkRestHandler.DeleteExternalLink).Queries("id", "{id}").Methods("DELETE")
 }
diff --git a/api/restHandler/AppListingRestHandler.go b/api/restHandler/AppListingRestHandler.go
index d9a6ab599..c88ea33b4 100644
--- a/api/restHandler/AppListingRestHandler.go
+++ b/api/restHandler/AppListingRestHandler.go
@@ -868,7 +868,7 @@ func (handler AppListingRestHandlerImpl) FetchOverviewAppsByEnvironment(w http.R
 	rbacObjectsWithAppId := handler.enforcerUtil.GetRbacObjectsByAppIds(appIds)
 	rbacObjects := make([]string, len(rbacObjectsWithAppId))
 	itr := 0
-	for _, object := range rbacObjects {
+	for _, object := range rbacObjectsWithAppId {
 		rbacObjects[itr] = object
 		itr++
 	}
diff --git a/api/restHandler/app/PipelineConfigRestHandler.go b/api/restHandler/app/PipelineConfigRestHandler.go
index 9316252cc..6181c6fe9 100644
--- a/api/restHandler/app/PipelineConfigRestHandler.go
+++ b/api/restHandler/app/PipelineConfigRestHandler.go
@@ -521,6 +521,7 @@ func (handler PipelineConfigRestHandlerImpl) FetchAppWorkflowStatusForTriggerVie
 	}
 	//RBAC CHECK
 
+	apiVersion := vars["version"]
 	triggerWorkflowStatus := pipelineConfig.TriggerWorkflowStatus{}
 	var ciWorkflowStatus []*pipelineConfig.CiWorkflowStatus
 	var err1 error
@@ -529,7 +530,11 @@ func (handler PipelineConfigRestHandlerImpl) FetchAppWorkflowStatusForTriggerVie
 	wg := sync.WaitGroup{}
 	wg.Add(2)
 	go func() {
-		ciWorkflowStatus, err = handler.ciHandler.FetchCiStatusForTriggerView(appId)
+		if apiVersion == "v2" {
+			ciWorkflowStatus, err = handler.ciHandler.FetchCiStatusForTriggerViewV1(appId)
+		} else {
+			ciWorkflowStatus, err = handler.ciHandler.FetchCiStatusForTriggerView(appId)
+		}
 		wg.Done()
 	}()
 
diff --git a/api/router/PipelineConfigRouter.go b/api/router/PipelineConfigRouter.go
index 8cc9183f9..49296d927 100644
--- a/api/router/PipelineConfigRouter.go
+++ b/api/router/PipelineConfigRouter.go
@@ -152,6 +152,7 @@ func (router PipelineConfigRouterImpl) initPipelineConfigRouter(configRouter *mu
 	configRouter.Path("/cd/configmap-secrets/{pipelineId}").HandlerFunc(router.restHandler.GetConfigmapSecretsForDeploymentStages).Methods("GET")
 
 	configRouter.Path("/workflow/status/{appId}").HandlerFunc(router.restHandler.FetchAppWorkflowStatusForTriggerView).Methods("GET")
+	configRouter.Path("/workflow/status/{appId}/{version}").HandlerFunc(router.restHandler.FetchAppWorkflowStatusForTriggerView).Methods("GET")
 
 	configRouter.Path("/material-info/{appId}/{ciArtifactId}").HandlerFunc(router.restHandler.FetchMaterialInfo).Methods("GET")
 	configRouter.Path("/ci-pipeline/webhook-payload/{pipelineMaterialId}").HandlerFunc(router.webhookDataRestHandler.GetWebhookPayloadDataForPipelineMaterialId).Methods("GET")
diff --git a/api/user/wire_user.go b/api/user/wire_user.go
index fd2ae9eda..9f9d4bbd5 100644
--- a/api/user/wire_user.go
+++ b/api/user/wire_user.go
@@ -48,4 +48,11 @@ var UserWireSet = wire.NewSet(
 
 	auth.NewUserAuthOidcHelperImpl,
 	wire.Bind(new(auth.UserAuthOidcHelper), new(*auth.UserAuthOidcHelperImpl)),
+
+	repository.NewRbacPolicyDataRepositoryImpl,
+	wire.Bind(new(repository.RbacPolicyDataRepository), new(*repository.RbacPolicyDataRepositoryImpl)),
+	repository.NewRbacRoleDataRepositoryImpl,
+	wire.Bind(new(repository.RbacRoleDataRepository), new(*repository.RbacRoleDataRepositoryImpl)),
+	repository.NewRbacDataCacheFactoryImpl,
+	wire.Bind(new(repository.RbacDataCacheFactory), new(*repository.RbacDataCacheFactoryImpl)),
 )
diff --git a/pkg/app/AppListingService.go b/pkg/app/AppListingService.go
index ea895ed68..fbe35d5a7 100644
--- a/pkg/app/AppListingService.go
+++ b/pkg/app/AppListingService.go
@@ -386,6 +386,35 @@ func (impl AppListingServiceImpl) FetchAppsByEnvironmentV2(fetchAppListingReques
 		impl.Logger.Errorw("error in fetching app list", "error", err, "filter", appListingFilter)
 		return []*bean.AppEnvironmentContainer{}, appSize, err
 	}
+
+	envContainersMap := make(map[int][]*bean.AppEnvironmentContainer)
+	envIds := make([]int, 0)
+	envsSet := make(map[int]bool)
+
+	for _, container := range envContainers {
+		if container.EnvironmentId != 0 {
+			if _, ok := envContainersMap[container.EnvironmentId]; !ok {
+				envContainersMap[container.EnvironmentId] = make([]*bean.AppEnvironmentContainer, 0)
+			}
+			envContainersMap[container.EnvironmentId] = append(envContainersMap[container.EnvironmentId], container)
+			if _, ok := envsSet[container.EnvironmentId]; !ok {
+				envIds = append(envIds, container.EnvironmentId)
+				envsSet[container.EnvironmentId] = true
+			}
+		}
+	}
+	envClusterInfos, err := impl.environmentRepository.FindEnvClusterInfosByIds(envIds)
+	if err != nil {
+		impl.Logger.Errorw("error in envClusterInfos list", "error", err, "envIds", envIds)
+		return []*bean.AppEnvironmentContainer{}, appSize, err
+	}
+	for _, info := range envClusterInfos {
+		for _, container := range envContainersMap[info.Id] {
+			container.Namespace = info.Namespace
+			container.ClusterName = info.ClusterName
+			container.EnvironmentName = info.Name
+		}
+	}
 	return envContainers, appSize, nil
 }
 
diff --git a/pkg/bean/app.go b/pkg/bean/app.go
index edb6e81f3..23327bc68 100644
--- a/pkg/bean/app.go
+++ b/pkg/bean/app.go
@@ -299,6 +299,7 @@ type CiConfigRequest struct {
 	UpdatedOn         time.Time               `sql:"updated_on,type:timestamptz"`
 	UpdatedBy         int32                   `sql:"updated_by,type:integer"`
 	IsJob             bool                    `json:"-"`
+	CiGitMaterialId   int                     `json:"ciGitConfiguredId"`
 }
 
 type TestExecutorImageProperties struct {
diff --git a/pkg/bulkAction/BulkUpdateService.go b/pkg/bulkAction/BulkUpdateService.go
index b6a5792f7..0be2a2b95 100644
--- a/pkg/bulkAction/BulkUpdateService.go
+++ b/pkg/bulkAction/BulkUpdateService.go
@@ -26,6 +26,7 @@ import (
 	pipeline1 "github.com/devtron-labs/devtron/pkg/pipeline"
 	"github.com/devtron-labs/devtron/pkg/pipeline/history"
 	repository4 "github.com/devtron-labs/devtron/pkg/pipeline/history/repository"
+	"github.com/devtron-labs/devtron/util/argo"
 	"github.com/devtron-labs/devtron/util/rbac"
 	jsonpatch "github.com/evanphx/json-patch"
 	"github.com/go-pg/pg"
@@ -86,6 +87,7 @@ type BulkUpdateServiceImpl struct {
 	appWorkflowRepository            appWorkflow.AppWorkflowRepository
 	appWorkflowService               appWorkflow2.AppWorkflowService
 	pubsubClient                     *pubsub.PubSubClientServiceImpl
+	argoUserService                  argo.ArgoUserService
 }
 
 func NewBulkUpdateServiceImpl(bulkUpdateRepository bulkUpdate.BulkUpdateRepository,
@@ -114,7 +116,8 @@ func NewBulkUpdateServiceImpl(bulkUpdateRepository bulkUpdate.BulkUpdateReposito
 	ciPipelineRepository pipelineConfig.CiPipelineRepository,
 	appWorkflowRepository appWorkflow.AppWorkflowRepository,
 	appWorkflowService appWorkflow2.AppWorkflowService,
-	pubsubClient *pubsub.PubSubClientServiceImpl) (*BulkUpdateServiceImpl, error) {
+	pubsubClient *pubsub.PubSubClientServiceImpl,
+	argoUserService argo.ArgoUserService) (*BulkUpdateServiceImpl, error) {
 	impl := &BulkUpdateServiceImpl{
 		bulkUpdateRepository:             bulkUpdateRepository,
 		chartRepository:                  chartRepository,
@@ -147,6 +150,7 @@ func NewBulkUpdateServiceImpl(bulkUpdateRepository bulkUpdate.BulkUpdateReposito
 		appWorkflowRepository:            appWorkflowRepository,
 		appWorkflowService:               appWorkflowService,
 		pubsubClient:                     pubsubClient,
+		argoUserService:                  argoUserService,
 	}
 
 	err := impl.SubscribeToCdBulkTriggerTopic()
@@ -1283,7 +1287,14 @@ func (impl BulkUpdateServiceImpl) SubscribeToCdBulkTriggerTopic() error {
 		event.ValuesOverrideRequest.UserId = event.UserId
 
 		// trigger
-		_, err = impl.workflowDagExecutor.ManualCdTrigger(event.ValuesOverrideRequest, context.Background())
+		ctx, err := impl.buildACDContext()
+		if err != nil {
+			impl.logger.Errorw("error in creating acd context",
+				"err", err)
+			return
+		}
+
+		_, err = impl.workflowDagExecutor.ManualCdTrigger(event.ValuesOverrideRequest, ctx)
 		if err != nil {
 			impl.logger.Errorw("Error triggering CD",
 				"topic", pubsub.CD_BULK_DEPLOY_TRIGGER_TOPIC,
@@ -1301,6 +1312,18 @@ func (impl BulkUpdateServiceImpl) SubscribeToCdBulkTriggerTopic() error {
 	return nil
 }
 
+func (impl *BulkUpdateServiceImpl) buildACDContext() (acdContext context.Context, err error) {
+	//this part only accessible for acd apps hibernation, if acd configured it will fetch latest acdToken, else it will return error
+	acdToken, err := impl.argoUserService.GetLatestDevtronArgoCdUserToken()
+	if err != nil {
+		impl.logger.Errorw("error in getting acd token", "err", err)
+		return nil, err
+	}
+	ctx := context.Background()
+	ctx = context.WithValue(ctx, "token", acdToken)
+	return ctx, nil
+}
+
 func (impl BulkUpdateServiceImpl) BulkBuildTrigger(request *BulkApplicationForEnvironmentPayload, ctx context.Context, w http.ResponseWriter, token string, checkAuthForBulkActions func(token string, appObject string, envObject string) bool) (*BulkApplicationForEnvironmentResponse, error) {
 	var pipelines []*pipelineConfig.Pipeline
 	var err error
diff --git a/pkg/cluster/repository/EnvironmentRepository.go b/pkg/cluster/repository/EnvironmentRepository.go
index b58308982..fe7bb5a92 100644
--- a/pkg/cluster/repository/EnvironmentRepository.go
+++ b/pkg/cluster/repository/EnvironmentRepository.go
@@ -18,13 +18,21 @@
 package repository
 
 import (
+	"fmt"
 	"github.com/devtron-labs/devtron/internal/sql/repository/appStatus"
+	"github.com/devtron-labs/devtron/internal/sql/repository/helper"
 	"github.com/devtron-labs/devtron/pkg/sql"
 	"github.com/go-pg/pg"
 	"github.com/go-pg/pg/orm"
 	"go.uber.org/zap"
 )
 
+type EnvCluserInfo struct {
+	Id          int    `sql:"id"`
+	ClusterName string `sql:"cluster_name"`
+	Namespace   string `sql:"namespace"`
+	Name        string `sql:"name"`
+}
 type Environment struct {
 	tableName             struct{} `sql:"environment" pg:",discard_unknown_columns"`
 	Id                    int      `sql:"id,pk"`
@@ -66,6 +74,7 @@ type EnvironmentRepository interface {
 	FindByEnvNameAndClusterIds(envName string, clusterIds []int) ([]*Environment, error)
 	FindByClusterIdsWithFilter(clusterIds []int) ([]*Environment, error)
 	FindAllActiveWithFilter() ([]*Environment, error)
+	FindEnvClusterInfosByIds([]int) ([]*EnvCluserInfo, error)
 }
 
 func NewEnvironmentRepositoryImpl(dbConnection *pg.DB, logger *zap.SugaredLogger, appStatusRepository appStatus.AppStatusRepository) *EnvironmentRepositoryImpl {
@@ -96,6 +105,17 @@ func (repositoryImpl EnvironmentRepositoryImpl) FindOne(environment string) (*En
 	return environmentCluster, err
 }
 
+func (repositoryImpl EnvironmentRepositoryImpl) FindEnvClusterInfosByIds(envIds []int) ([]*EnvCluserInfo, error) {
+	query := "SELECT env.id as id,cluster.cluster_name,env.environment_name as name,env.namespace " +
+		" FROM environment env INNER JOIN  cluster ON env.cluster_id = cluster.id "
+	if len(envIds) > 0 {
+		query += fmt.Sprintf(" WHERE env.id IN (%s)", helper.GetCommaSepratedString(envIds))
+	}
+	res := make([]*EnvCluserInfo, 0)
+	_, err := repositoryImpl.dbConnection.Query(&res, query)
+	return res, err
+}
+
 func (repositoryImpl EnvironmentRepositoryImpl) FindByNamespaceAndClusterName(namespaces string, clusterName string) (*Environment, error) {
 	environmentCluster := &Environment{}
 	err := repositoryImpl.dbConnection.
diff --git a/pkg/pipeline/CiHandler.go b/pkg/pipeline/CiHandler.go
index a602b5f20..e5d49947a 100644
--- a/pkg/pipeline/CiHandler.go
+++ b/pkg/pipeline/CiHandler.go
@@ -67,6 +67,7 @@ type CiHandler interface {
 	UpdateWorkflow(workflowStatus v1alpha1.WorkflowStatus) (int, error)
 
 	FetchCiStatusForTriggerView(appId int) ([]*pipelineConfig.CiWorkflowStatus, error)
+	FetchCiStatusForTriggerViewV1(appId int) ([]*pipelineConfig.CiWorkflowStatus, error)
 	RefreshMaterialByCiPipelineMaterialId(gitMaterialId int) (refreshRes *gitSensor.RefreshGitMaterialResponse, err error)
 	FetchMaterialInfoByArtifactId(ciArtifactId int) (*GitTriggerInfoResponse, error)
 	WriteToCreateTestSuites(pipelineId int, buildId int, triggeredBy int)
@@ -1022,7 +1023,7 @@ func (impl *CiHandlerImpl) getLastSeenCommit(ciMaterialId int) (bean.GitCommit,
 	return gitCommit, nil
 }
 
-func (impl *CiHandlerImpl) FetchCiStatusForTriggerView(appId int) ([]*pipelineConfig.CiWorkflowStatus, error) {
+func (impl *CiHandlerImpl) FetchCiStatusForTriggerViewV1(appId int) ([]*pipelineConfig.CiWorkflowStatus, error) {
 	ciWorkflowStatuses, err := impl.ciWorkflowRepository.FIndCiWorkflowStatusesByAppId(appId)
 	if err != nil && !util.IsErrNoRows(err) {
 		impl.Logger.Errorw("err in fetching ciWorkflowStatuses from ciWorkflowRepository", "appId", appId, "err", err)
@@ -1032,6 +1033,39 @@ func (impl *CiHandlerImpl) FetchCiStatusForTriggerView(appId int) ([]*pipelineCo
 	return ciWorkflowStatuses, err
 }
 
+func (impl *CiHandlerImpl) FetchCiStatusForTriggerView(appId int) ([]*pipelineConfig.CiWorkflowStatus, error) {
+	var ciWorkflowStatuses []*pipelineConfig.CiWorkflowStatus
+
+	pipelines, err := impl.ciPipelineRepository.FindByAppId(appId)
+	if err != nil && err != pg.ErrNoRows {
+		impl.Logger.Errorw("error in fetching ci pipeline", "appId", appId, "err", err)
+		return ciWorkflowStatuses, err
+	}
+	for _, pipeline := range pipelines {
+		pipelineId := 0
+		if pipeline.ParentCiPipeline == 0 {
+			pipelineId = pipeline.Id
+		} else {
+			pipelineId = pipeline.ParentCiPipeline
+		}
+		workflow, err := impl.ciWorkflowRepository.FindLastTriggeredWorkflow(pipelineId)
+		if err != nil && !util.IsErrNoRows(err) {
+			impl.Logger.Errorw("err", "pipelineId", pipelineId, "err", err)
+			return ciWorkflowStatuses, err
+		}
+		ciWorkflowStatus := &pipelineConfig.CiWorkflowStatus{}
+		ciWorkflowStatus.CiPipelineId = pipeline.Id
+		if workflow.Id > 0 {
+			ciWorkflowStatus.CiPipelineName = workflow.CiPipeline.Name
+			ciWorkflowStatus.CiStatus = workflow.Status
+		} else {
+			ciWorkflowStatus.CiStatus = "Not Triggered"
+		}
+		ciWorkflowStatuses = append(ciWorkflowStatuses, ciWorkflowStatus)
+	}
+	return ciWorkflowStatuses, nil
+}
+
 func (impl *CiHandlerImpl) FetchMaterialInfoByArtifactId(ciArtifactId int) (*GitTriggerInfoResponse, error) {
 
 	ciArtifact, err := impl.ciArtifactRepository.Get(ciArtifactId)
diff --git a/pkg/pipeline/PipelineBuilder.go b/pkg/pipeline/PipelineBuilder.go
index caea61aba..f89cfce04 100644
--- a/pkg/pipeline/PipelineBuilder.go
+++ b/pkg/pipeline/PipelineBuilder.go
@@ -1154,7 +1154,7 @@ func (impl PipelineBuilderImpl) UpdateCiTemplate(updateRequest *bean.CiConfigReq
 			CreatedOn: originalCiConf.CreatedOn,
 			CreatedBy: originalCiConf.CreatedBy,
 			UpdatedOn: time.Now(),
-			UpdatedBy: updateRequest.UpdatedBy,
+			UpdatedBy: updateRequest.UserId,
 		},
 	}
 
@@ -4069,6 +4069,7 @@ func (impl PipelineBuilderImpl) GetCiPipelineByEnvironment(envId int, emailId st
 			//parentCiPipelineIds = append(parentCiPipelineIds, pipeline.ParentCiPipeline)
 		}
 		ciPipelinesConfigByApp.CiPipelines = ciPipelineResp
+		ciPipelinesConfigByApp.CiGitMaterialId = ciPipelinesConfigByApp.CiBuildConfig.GitMaterialId
 		ciPipelinesConfigByApps = append(ciPipelinesConfigByApps, ciPipelinesConfigByApp)
 	}
 
diff --git a/pkg/user/RoleGroupService.go b/pkg/user/RoleGroupService.go
index 2fb30750c..efca6e6cd 100644
--- a/pkg/user/RoleGroupService.go
+++ b/pkg/user/RoleGroupService.go
@@ -138,7 +138,7 @@ func (impl RoleGroupServiceImpl) CreateRoleGroup(request *bean.RoleGroup) (*bean
 						}
 						if roleModel.Id == 0 {
 							if roleFilter.Entity == bean2.ENTITY_APPS || roleFilter.Entity == bean.CHART_GROUP_ENTITY {
-								flag, err, policiesAdded := impl.userAuthRepository.CreateDefaultPoliciesForAllTypes(roleFilter.Team, entityName, environment, entity, "", "", "", "", "", actionType, accessType, request.UserId)
+								flag, err, policiesAdded := impl.userCommonService.CreateDefaultPoliciesForAllTypes(roleFilter.Team, entityName, environment, entity, "", "", "", "", "", actionType, accessType, request.UserId)
 								if err != nil || flag == false {
 									return nil, err
 								}
@@ -217,7 +217,7 @@ func (impl RoleGroupServiceImpl) CreateOrUpdateRoleGroupForClusterEntity(roleFil
 						return policiesToBeAdded, err
 					}
 					if roleModel.Id == 0 {
-						flag, err, policiesAdded := impl.userAuthRepository.CreateDefaultPoliciesForAllTypes("", "", "", entity, roleFilter.Cluster, namespace, group, kind, resource, actionType, accessType, userId)
+						flag, err, policiesAdded := impl.userCommonService.CreateDefaultPoliciesForAllTypes("", "", "", entity, roleFilter.Cluster, namespace, group, kind, resource, actionType, accessType, userId)
 						if err != nil || flag == false {
 							return policiesToBeAdded, err
 						}
@@ -346,7 +346,7 @@ func (impl RoleGroupServiceImpl) UpdateRoleGroup(request *bean.RoleGroup, token
 					if roleModel.Id == 0 {
 						request.Status = bean2.RoleNotFoundStatusPrefix + roleFilter.Team + "," + environment + "," + entityName + "," + actionType
 						if roleFilter.Entity == bean2.ENTITY_APPS || roleFilter.Entity == bean.CHART_GROUP_ENTITY {
-							flag, err, policiesAdded := impl.userAuthRepository.CreateDefaultPoliciesForAllTypes(roleFilter.Team, entityName, environment, entity, "", "", "", "", "", actionType, accessType, request.UserId)
+							flag, err, policiesAdded := impl.userCommonService.CreateDefaultPoliciesForAllTypes(roleFilter.Team, entityName, environment, entity, "", "", "", "", "", actionType, accessType, request.UserId)
 							policies = append(policies, policiesAdded...)
 							if err != nil || flag == false {
 								return nil, err
diff --git a/pkg/user/UserAuthService.go b/pkg/user/UserAuthService.go
index 12f4b3206..db256d624 100644
--- a/pkg/user/UserAuthService.go
+++ b/pkg/user/UserAuthService.go
@@ -442,24 +442,10 @@ func (impl UserAuthServiceImpl) CreateRole(roleData *bean.RoleData) (bool, error
 		Kind:        roleData.Kind,
 		Resource:    roleData.Resource,
 	}
-	dbConnection := impl.userRepository.GetConnection()
-	tx, err := dbConnection.Begin()
-	if err != nil {
-		return false, err
-	}
-	// Rollback tx on error.
-	defer tx.Rollback()
-
-	roleModel, err = impl.userAuthRepository.CreateRole(roleModel, tx)
+	roleModel, err := impl.userAuthRepository.CreateRole(roleModel)
 	if err != nil || roleModel == nil {
 		return false, err
 	}
-
-	err = tx.Commit()
-	if err != nil {
-		return false, err
-	}
-
 	return true, nil
 }
 
diff --git a/pkg/user/UserCommonService.go b/pkg/user/UserCommonService.go
index fce721ff9..80b71bd4b 100644
--- a/pkg/user/UserCommonService.go
+++ b/pkg/user/UserCommonService.go
@@ -2,21 +2,25 @@ package user
 
 import (
 	"fmt"
+	"github.com/caarlos0/env/v6"
 	"github.com/devtron-labs/authenticator/middleware"
 	"github.com/devtron-labs/devtron/api/bean"
+	"github.com/devtron-labs/devtron/pkg/sql"
 	bean2 "github.com/devtron-labs/devtron/pkg/user/bean"
-	casbin2 "github.com/devtron-labs/devtron/pkg/user/casbin"
+	casbin "github.com/devtron-labs/devtron/pkg/user/casbin"
 	repository2 "github.com/devtron-labs/devtron/pkg/user/repository"
 	"github.com/go-pg/pg"
 	"github.com/gorilla/sessions"
 	"go.uber.org/zap"
 	"math"
 	"strings"
+	"time"
 )
 
 type UserCommonService interface {
-	RemoveRolesAndReturnEliminatedPolicies(userInfo *bean.UserInfo, existingRoleIds map[int]repository2.UserRoleModel, eliminatedRoleIds map[int]*repository2.UserRoleModel, tx *pg.Tx, token string, managerAuth func(resource, token, object string) bool) ([]casbin2.Policy, error)
-	RemoveRolesAndReturnEliminatedPoliciesForGroups(request *bean.RoleGroup, existingRoles map[int]*repository2.RoleGroupRoleMapping, eliminatedRoles map[int]*repository2.RoleGroupRoleMapping, tx *pg.Tx, token string, managerAuth func(resource string, token string, object string) bool) ([]casbin2.Policy, error)
+	CreateDefaultPoliciesForAllTypes(team, entityName, env, entity, cluster, namespace, group, kind, resource, actionType, accessType string, userId int32) (bool, error, []casbin.Policy)
+	RemoveRolesAndReturnEliminatedPolicies(userInfo *bean.UserInfo, existingRoleIds map[int]repository2.UserRoleModel, eliminatedRoleIds map[int]*repository2.UserRoleModel, tx *pg.Tx, token string, managerAuth func(resource, token, object string) bool) ([]casbin.Policy, error)
+	RemoveRolesAndReturnEliminatedPoliciesForGroups(request *bean.RoleGroup, existingRoles map[int]*repository2.RoleGroupRoleMapping, eliminatedRoles map[int]*repository2.RoleGroupRoleMapping, tx *pg.Tx, token string, managerAuth func(resource string, token string, object string) bool) ([]casbin.Policy, error)
 	CheckRbacForClusterEntity(cluster, namespace, group, kind, resource, token string, managerAuth func(resource, token, object string) bool) bool
 	ReplacePlaceHolderForEmptyEntriesInRoleFilter(roleFilter bean.RoleFilter) bean.RoleFilter
 	RemovePlaceHolderInRoleFilterField(roleFilterField string) string
@@ -24,33 +28,185 @@ type UserCommonService interface {
 }
 
 type UserCommonServiceImpl struct {
-	userAuthRepository  repository2.UserAuthRepository
-	logger              *zap.SugaredLogger
-	userRepository      repository2.UserRepository
-	roleGroupRepository repository2.RoleGroupRepository
-	sessionManager2     *middleware.SessionManager
+	userAuthRepository          repository2.UserAuthRepository
+	logger                      *zap.SugaredLogger
+	userRepository              repository2.UserRepository
+	roleGroupRepository         repository2.RoleGroupRepository
+	sessionManager2             *middleware.SessionManager
+	defaultRbacDataCacheFactory repository2.RbacDataCacheFactory
+	userRbacConfig              *UserRbacConfig
 }
 
 func NewUserCommonServiceImpl(userAuthRepository repository2.UserAuthRepository,
 	logger *zap.SugaredLogger,
 	userRepository repository2.UserRepository,
 	userGroupRepository repository2.RoleGroupRepository,
-	sessionManager2 *middleware.SessionManager) *UserCommonServiceImpl {
+	sessionManager2 *middleware.SessionManager,
+	defaultRbacDataCacheFactory repository2.RbacDataCacheFactory) *UserCommonServiceImpl {
+	userConfig := &UserRbacConfig{}
+	err := env.Parse(userConfig)
+	if err != nil {
+		logger.Fatal("error occurred while parsing user config", err)
+	}
 	serviceImpl := &UserCommonServiceImpl{
-		userAuthRepository:  userAuthRepository,
-		logger:              logger,
-		userRepository:      userRepository,
-		roleGroupRepository: userGroupRepository,
-		sessionManager2:     sessionManager2,
+		userAuthRepository:          userAuthRepository,
+		logger:                      logger,
+		userRepository:              userRepository,
+		roleGroupRepository:         userGroupRepository,
+		sessionManager2:             sessionManager2,
+		defaultRbacDataCacheFactory: defaultRbacDataCacheFactory,
+		userRbacConfig:              userConfig,
 	}
 	cStore = sessions.NewCookieStore(randKey())
+	defaultRbacDataCacheFactory.SyncPolicyCache()
+	defaultRbacDataCacheFactory.SyncRoleDataCache()
 	return serviceImpl
 }
 
+type UserRbacConfig struct {
+	UseRbacCreationV2 bool `env:"USE_RBAC_CREATION_V2" envDefault:"false"`
+}
+
+func (impl UserCommonServiceImpl) CreateDefaultPoliciesForAllTypes(team, entityName, env, entity, cluster, namespace, group, kind, resource, actionType, accessType string, userId int32) (bool, error, []casbin.Policy) {
+	if impl.userRbacConfig.UseRbacCreationV2 {
+		impl.logger.Debugw("using rbac creation v2 for creating default policies")
+		return impl.CreateDefaultPoliciesForAllTypesV2(team, entityName, env, entity, cluster, namespace, group, kind, resource, actionType, accessType)
+	} else {
+		return impl.userAuthRepository.CreateDefaultPoliciesForAllTypes(team, entityName, env, entity, cluster, namespace, group, kind, resource, actionType, accessType, userId)
+	}
+}
+
+func (impl UserCommonServiceImpl) CreateDefaultPoliciesForAllTypesV2(team, entityName, env, entity, cluster, namespace, group, kind, resource, actionType, accessType string) (bool, error, []casbin.Policy) {
+	//TODO: below txn is making this process slow, need to do bulk operation for role creation.
+	//For detail - https://github.com/devtron-labs/devtron/blob/main/pkg/user/benchmarking-results
+
+	renderedRole, renderedPolicyDetails := impl.getRenderedRoleAndPolicy(team, entityName, env, entity, cluster, namespace, group, kind, resource, actionType, accessType)
+	_, err := impl.userAuthRepository.CreateRole(renderedRole)
+	if err != nil && strings.Contains("duplicate key value violates unique constraint", err.Error()) {
+		return false, err, nil
+	}
+	return true, nil, renderedPolicyDetails
+}
+
+func (impl UserCommonServiceImpl) getRenderedRoleAndPolicy(team, entityName, env, entity, cluster, namespace, group, kind, resource, actionType, accessType string) (*repository2.RoleModel, []casbin.Policy) {
+	//getting map of values to be used for rendering
+	pValUpdateMap := getPValUpdateMap(team, entityName, env, entity, cluster, namespace, group, kind, resource)
+
+	//getting default role data and policy
+	defaultRoleData, defaultPolicy := impl.getDefaultRbacRoleAndPolicyByRoleFilter(entity, accessType, actionType)
+
+	//getting rendered role and policy data
+	renderedRoleData := getRenderedRoleData(defaultRoleData, pValUpdateMap)
+	renderedPolicy := getRenderedPolicy(defaultPolicy, pValUpdateMap)
+
+	return renderedRoleData, renderedPolicy
+}
+
+func (impl UserCommonServiceImpl) getDefaultRbacRoleAndPolicyByRoleFilter(entity, accessType, action string) (repository2.RoleCacheDetailObj, repository2.PolicyCacheDetailObj) {
+	//getting default role and policy data from cache
+	return impl.defaultRbacDataCacheFactory.
+		GetDefaultRoleDataAndPolicyByEntityAccessTypeAndRoleType(entity, accessType, action)
+}
+
+func getRenderedRoleData(defaultRoleData repository2.RoleCacheDetailObj, pValUpdateMap map[repository2.PValUpdateKey]string) *repository2.RoleModel {
+	renderedRoleData := &repository2.RoleModel{
+		Role:        getResolvedValueFromPValDetailObject(defaultRoleData.Role, pValUpdateMap),
+		Entity:      getResolvedValueFromPValDetailObject(defaultRoleData.Entity, pValUpdateMap),
+		EntityName:  getResolvedValueFromPValDetailObject(defaultRoleData.EntityName, pValUpdateMap),
+		Team:        getResolvedValueFromPValDetailObject(defaultRoleData.Team, pValUpdateMap),
+		Environment: getResolvedValueFromPValDetailObject(defaultRoleData.Environment, pValUpdateMap),
+		AccessType:  getResolvedValueFromPValDetailObject(defaultRoleData.AccessType, pValUpdateMap),
+		Action:      getResolvedValueFromPValDetailObject(defaultRoleData.Action, pValUpdateMap),
+		Cluster:     getResolvedValueFromPValDetailObject(defaultRoleData.Cluster, pValUpdateMap),
+		Namespace:   getResolvedValueFromPValDetailObject(defaultRoleData.Namespace, pValUpdateMap),
+		Group:       getResolvedValueFromPValDetailObject(defaultRoleData.Group, pValUpdateMap),
+		Kind:        getResolvedValueFromPValDetailObject(defaultRoleData.Kind, pValUpdateMap),
+		Resource:    getResolvedValueFromPValDetailObject(defaultRoleData.Resource, pValUpdateMap),
+		AuditLog: sql.AuditLog{ //not storing user information because this role can be mapped to other users in future and hence can lead to confusion
+			CreatedOn: time.Now(),
+			UpdatedOn: time.Now(),
+		},
+	}
+	return renderedRoleData
+}
+
+func getRenderedPolicy(defaultPolicy repository2.PolicyCacheDetailObj, pValUpdateMap map[repository2.PValUpdateKey]string) []casbin.Policy {
+	renderedPolicies := make([]casbin.Policy, 0, len(defaultPolicy.ResActObjSet))
+	policyType := getResolvedValueFromPValDetailObject(defaultPolicy.Type, pValUpdateMap)
+	policySub := getResolvedValueFromPValDetailObject(defaultPolicy.Sub, pValUpdateMap)
+	for _, v := range defaultPolicy.ResActObjSet {
+		policyRes := getResolvedValueFromPValDetailObject(v.Res, pValUpdateMap)
+		policyAct := getResolvedValueFromPValDetailObject(v.Act, pValUpdateMap)
+		policyObj := getResolvedValueFromPValDetailObject(v.Obj, pValUpdateMap)
+		renderedPolicy := casbin.Policy{
+			Type: casbin.PolicyType(policyType),
+			Sub:  casbin.Subject(policySub),
+			Res:  casbin.Resource(policyRes),
+			Act:  casbin.Action(policyAct),
+			Obj:  casbin.Object(policyObj),
+		}
+		renderedPolicies = append(renderedPolicies, renderedPolicy)
+	}
+	return renderedPolicies
+}
+
+func getResolvedValueFromPValDetailObject(pValDetailObj repository2.PValDetailObj, pValUpdateMap map[repository2.PValUpdateKey]string) string {
+	if len(pValDetailObj.IndexKeyMap) == 0 {
+		return pValDetailObj.Value
+	}
+	pValBytes := []byte(pValDetailObj.Value)
+	var resolvedValueInBytes []byte
+	for i, pValByte := range pValBytes {
+		if pValByte == '%' {
+			valUpdateKey := pValDetailObj.IndexKeyMap[i]
+			val := pValUpdateMap[valUpdateKey]
+			resolvedValueInBytes = append(resolvedValueInBytes, []byte(val)...)
+		} else {
+			resolvedValueInBytes = append(resolvedValueInBytes, pValByte)
+		}
+	}
+	return string(resolvedValueInBytes)
+}
+
+func getPValUpdateMap(team, entityName, env, entity, cluster,
+	namespace, group, kind, resource string) map[repository2.PValUpdateKey]string {
+	pValUpdateMap := make(map[repository2.PValUpdateKey]string)
+	pValUpdateMap[repository2.EntityPValUpdateKey] = entity
+	if entity == bean.CLUSTER_ENTITIY {
+		pValUpdateMap[repository2.ClusterPValUpdateKey] = cluster
+		pValUpdateMap[repository2.NamespacePValUpdateKey] = namespace
+		pValUpdateMap[repository2.GroupPValUpdateKey] = group
+		pValUpdateMap[repository2.KindPValUpdateKey] = kind
+		pValUpdateMap[repository2.ResourcePValUpdateKey] = resource
+		pValUpdateMap[repository2.ClusterObjPValUpdateKey] = getResolvedPValMapValue(cluster)
+		pValUpdateMap[repository2.NamespaceObjPValUpdateKey] = getResolvedPValMapValue(namespace)
+		pValUpdateMap[repository2.GroupObjPValUpdateKey] = getResolvedPValMapValue(group)
+		pValUpdateMap[repository2.KindObjPValUpdateKey] = getResolvedPValMapValue(kind)
+		pValUpdateMap[repository2.ResourceObjPValUpdateKey] = getResolvedPValMapValue(resource)
+	} else {
+		pValUpdateMap[repository2.EntityNamePValUpdateKey] = entityName
+		pValUpdateMap[repository2.TeamPValUpdateKey] = team
+		pValUpdateMap[repository2.AppPValUpdateKey] = entityName
+		pValUpdateMap[repository2.EnvPValUpdateKey] = env
+		pValUpdateMap[repository2.TeamObjPValUpdateKey] = getResolvedPValMapValue(team)
+		pValUpdateMap[repository2.AppObjPValUpdateKey] = getResolvedPValMapValue(entityName)
+		pValUpdateMap[repository2.EnvObjPValUpdateKey] = getResolvedPValMapValue(env)
+	}
+	return pValUpdateMap
+}
+
+func getResolvedPValMapValue(rawValue string) string {
+	resolvedVal := rawValue
+	if rawValue == "" {
+		resolvedVal = "*"
+	}
+	return resolvedVal
+}
+
 func (impl UserCommonServiceImpl) RemoveRolesAndReturnEliminatedPolicies(userInfo *bean.UserInfo,
 	existingRoleIds map[int]repository2.UserRoleModel, eliminatedRoleIds map[int]*repository2.UserRoleModel,
-	tx *pg.Tx, token string, managerAuth func(resource, token, object string) bool) ([]casbin2.Policy, error) {
-	var eliminatedPolicies []casbin2.Policy
+	tx *pg.Tx, token string, managerAuth func(resource, token, object string) bool) ([]casbin.Policy, error) {
+	var eliminatedPolicies []casbin.Policy
 	// DELETE Removed Items
 	for _, roleFilter := range userInfo.RoleFilters {
 		if roleFilter.Entity == bean.CLUSTER_ENTITIY {
@@ -119,7 +275,7 @@ func (impl UserCommonServiceImpl) RemoveRolesAndReturnEliminatedPolicies(userInf
 		} else {
 			if len(roleFilter.Team) > 0 { // check auth only for apps permission, skip for chart group
 				rbacObject := fmt.Sprintf("%s", strings.ToLower(roleFilter.Team))
-				isValidAuth := managerAuth(casbin2.ResourceUser, token, rbacObject)
+				isValidAuth := managerAuth(casbin.ResourceUser, token, rbacObject)
 				if !isValidAuth {
 					continue
 				}
@@ -180,7 +336,7 @@ func (impl UserCommonServiceImpl) RemoveRolesAndReturnEliminatedPolicies(userInf
 		}
 		if len(role.Team) > 0 {
 			rbacObject := fmt.Sprintf("%s", strings.ToLower(role.Team))
-			isValidAuth := managerAuth(casbin2.ResourceUser, token, rbacObject)
+			isValidAuth := managerAuth(casbin.ResourceUser, token, rbacObject)
 			if !isValidAuth {
 				continue
 			}
@@ -196,15 +352,15 @@ func (impl UserCommonServiceImpl) RemoveRolesAndReturnEliminatedPolicies(userInf
 			impl.logger.Errorw("Error in delete user role mapping", "user", userInfo)
 			return nil, err
 		}
-		eliminatedPolicies = append(eliminatedPolicies, casbin2.Policy{Type: "g", Sub: casbin2.Subject(userInfo.EmailId), Obj: casbin2.Object(role.Role)})
+		eliminatedPolicies = append(eliminatedPolicies, casbin.Policy{Type: "g", Sub: casbin.Subject(userInfo.EmailId), Obj: casbin.Object(role.Role)})
 	}
 	// DELETE ENDS
 	return eliminatedPolicies, nil
 }
 
-func (impl UserCommonServiceImpl) RemoveRolesAndReturnEliminatedPoliciesForGroups(request *bean.RoleGroup, existingRoles map[int]*repository2.RoleGroupRoleMapping, eliminatedRoles map[int]*repository2.RoleGroupRoleMapping, tx *pg.Tx, token string, managerAuth func(resource string, token string, object string) bool) ([]casbin2.Policy, error) {
+func (impl UserCommonServiceImpl) RemoveRolesAndReturnEliminatedPoliciesForGroups(request *bean.RoleGroup, existingRoles map[int]*repository2.RoleGroupRoleMapping, eliminatedRoles map[int]*repository2.RoleGroupRoleMapping, tx *pg.Tx, token string, managerAuth func(resource string, token string, object string) bool) ([]casbin.Policy, error) {
 	// Filter out removed items in current request
-	//var policies []casbin2.Policy
+	//var policies []casbin.Policy
 	for _, roleFilter := range request.RoleFilters {
 		if roleFilter.Entity == bean.CLUSTER_ENTITIY {
 			if roleFilter.Namespace == "" {
@@ -274,7 +430,7 @@ func (impl UserCommonServiceImpl) RemoveRolesAndReturnEliminatedPoliciesForGroup
 		} else {
 			if len(roleFilter.Team) > 0 { // check auth only for apps permission, skip for chart group
 				rbacObject := fmt.Sprintf("%s", strings.ToLower(roleFilter.Team))
-				isValidAuth := managerAuth(casbin2.ResourceUser, token, rbacObject)
+				isValidAuth := managerAuth(casbin.ResourceUser, token, rbacObject)
 				if !isValidAuth {
 					continue
 				}
@@ -328,7 +484,7 @@ func (impl UserCommonServiceImpl) RemoveRolesAndReturnEliminatedPoliciesForGroup
 
 	//delete remaining Ids from casbin role mapping table in orchestrator and casbin policy db
 	// which are existing but not provided in this request
-	var eliminatedPolicies []casbin2.Policy
+	var eliminatedPolicies []casbin.Policy
 	for _, model := range eliminatedRoles {
 		role, err := impl.userAuthRepository.GetRoleById(model.RoleId)
 		if err != nil {
@@ -336,7 +492,7 @@ func (impl UserCommonServiceImpl) RemoveRolesAndReturnEliminatedPoliciesForGroup
 		}
 		if len(role.Team) > 0 {
 			rbacObject := fmt.Sprintf("%s", strings.ToLower(role.Team))
-			isValidAuth := managerAuth(casbin2.ResourceUser, token, rbacObject)
+			isValidAuth := managerAuth(casbin.ResourceUser, token, rbacObject)
 			if !isValidAuth {
 				continue
 			}
@@ -355,7 +511,7 @@ func (impl UserCommonServiceImpl) RemoveRolesAndReturnEliminatedPoliciesForGroup
 		if err != nil {
 			return nil, err
 		}
-		eliminatedPolicies = append(eliminatedPolicies, casbin2.Policy{Type: "g", Sub: casbin2.Subject(policyGroup.CasbinName), Obj: casbin2.Object(role.Role)})
+		eliminatedPolicies = append(eliminatedPolicies, casbin.Policy{Type: "g", Sub: casbin.Subject(policyGroup.CasbinName), Obj: casbin.Object(role.Role)})
 	}
 	return eliminatedPolicies, nil
 }
@@ -399,7 +555,7 @@ func (impl UserCommonServiceImpl) CheckRbacForClusterEntity(cluster, namespace,
 		resourceObj = "*"
 	}
 
-	rbacResource := fmt.Sprintf("%s/%s/%s", strings.ToLower(cluster), strings.ToLower(namespaceObj), casbin2.ResourceUser)
+	rbacResource := fmt.Sprintf("%s/%s/%s", strings.ToLower(cluster), strings.ToLower(namespaceObj), casbin.ResourceUser)
 	resourcesArray := strings.Split(resourceObj, ",")
 	for _, resourceVal := range resourcesArray {
 		rbacObject := fmt.Sprintf("%s/%s/%s", strings.ToLower(groupObj), strings.ToLower(kindObj), strings.ToLower(resourceVal))
diff --git a/pkg/user/UserService.go b/pkg/user/UserService.go
index 6ede31810..f55bfedec 100644
--- a/pkg/user/UserService.go
+++ b/pkg/user/UserService.go
@@ -440,7 +440,7 @@ func (impl UserServiceImpl) CreateOrUpdateUserRolesForAllTypes(roleFilter bean.R
 				}
 				if roleModel.Id == 0 {
 					impl.logger.Debugw("no role found for given filter", "filter", "roleFilter", roleFilter)
-					flag, err, policiesAdded := impl.userAuthRepository.CreateDefaultPoliciesForAllTypes(roleFilter.Team, entityName, environment, entity, "", "", "", "", "", actionType, accessType, userId)
+					flag, err, policiesAdded := impl.userCommonService.CreateDefaultPoliciesForAllTypes(roleFilter.Team, entityName, environment, entity, "", "", "", "", "", actionType, accessType, userId)
 					if err != nil || flag == false {
 						return policiesToBeAdded, rolesChanged, err
 					}
@@ -513,7 +513,7 @@ func (impl UserServiceImpl) createOrUpdateUserRolesForClusterEntity(roleFilter b
 					}
 					if roleModel.Id == 0 {
 						impl.logger.Infow("Creating Polices for cluster", resource, kind, namespace, group)
-						flag, err, policiesAdded := impl.userAuthRepository.CreateDefaultPoliciesForAllTypes("", "", "", entity, roleFilter.Cluster, namespace, group, kind, resource, actionType, accessType, userId)
+						flag, err, policiesAdded := impl.userCommonService.CreateDefaultPoliciesForAllTypes("", "", "", entity, roleFilter.Cluster, namespace, group, kind, resource, actionType, accessType, userId)
 						if err != nil || flag == false {
 							return policiesToBeAdded, rolesChanged, err
 						}
diff --git a/pkg/user/benchmarking-results b/pkg/user/benchmarking-results
new file mode 100644
index 000000000..17e9e3ecd
--- /dev/null
+++ b/pkg/user/benchmarking-results
@@ -0,0 +1,30 @@
+goos: darwin
+goarch: amd64
+pkg: github.com/devtron-labs/devtron/pkg/user/casbin
+cpu: Intel(R) Core(TM) i5-8257U CPU @ 1.40GHz
+
+
+Scenario 1: Results of benchmarking when roleCreation part is commented and only default role/policy fetch and rendering is judged (250k times faster)-
+
+
+With V2 function -
+BenchmarkCreateDefaultPoliciesForAllTypesV2/BenchmarkCreateDefaultPoliciesForAllTypesV2-8             504132          2361 ns/op
+
+With V1 function -
+BenchmarkCreateDefaultPoliciesForAllTypes/BenchmarkCreateDefaultPoliciesForAllTypes-8                  2     561936517 ns/op
+
+
+
+Scenario 2: Results of benchmarking when roleCreation part is not commented (4 times faster)-
+
+
+With V2 function -
+BenchmarkCreateDefaultPoliciesForAllTypesV2/BenchmarkCreateDefaultPoliciesForAllTypesV2-8                  2     561547156 ns/op
+
+With V1 function -
+BenchmarkCreateDefaultPoliciesForAllTypes/BenchmarkCreateDefaultPoliciesForAllTypes-8                  1    1956079317 ns/op
+
+
+NOTE - From the above two scenarios, we can easily deduce that the while we have got significant improvements in default role/policy
+fetching & rendering we still need to work on the time taken for every role to be saved in DB. This should be done via introducing
+bulk update operation in role saving in further iterations of work in this area.
\ No newline at end of file
diff --git a/pkg/user/repository/RbacDataCacheFactory.go b/pkg/user/repository/RbacDataCacheFactory.go
new file mode 100644
index 000000000..5b46af150
--- /dev/null
+++ b/pkg/user/repository/RbacDataCacheFactory.go
@@ -0,0 +1,144 @@
+package repository
+
+import (
+	"encoding/json"
+	"fmt"
+	"go.uber.org/zap"
+	"sync"
+)
+
+type RbacDataCacheFactory interface {
+	GetDefaultRoleDataAndPolicyByEntityAccessTypeAndRoleType(entity, accessType, roleType string) (RoleCacheDetailObj, PolicyCacheDetailObj)
+	SyncPolicyCache()
+	SyncRoleDataCache()
+}
+
+type RbacDataCacheFactoryImpl struct {
+	logger                          *zap.SugaredLogger
+	policyCache                     map[string]PolicyCacheDetailObj
+	roleCache                       map[string]RoleCacheDetailObj
+	mutex                           sync.Mutex
+	defaultRbacPolicyDataRepository RbacPolicyDataRepository
+	defaultRbacRoleDataRepository   RbacRoleDataRepository
+}
+
+type PolicyCacheDetailObj struct {
+	Type         PValDetailObj `json:"type"`
+	Sub          PValDetailObj `json:"sub"`
+	ResActObjSet []ResActObj   `json:"resActObjSet"`
+}
+
+type RoleCacheDetailObj struct {
+	Role        PValDetailObj `json:"role"`
+	Entity      PValDetailObj `json:"entity"`
+	Team        PValDetailObj `json:"team"`
+	EntityName  PValDetailObj `json:"entityName"`
+	Environment PValDetailObj `json:"environment"`
+	Action      PValDetailObj `json:"action"`
+	AccessType  PValDetailObj `json:"accessType"`
+	Cluster     PValDetailObj `json:"cluster"`
+	Namespace   PValDetailObj `json:"namespace"`
+	Group       PValDetailObj `json:"group"`
+	Kind        PValDetailObj `json:"kind"`
+	Resource    PValDetailObj `json:"resource"`
+}
+
+type ResActObj struct {
+	Res PValDetailObj `json:"res"`
+	Act PValDetailObj `json:"act"`
+	Obj PValDetailObj `json:"obj"`
+}
+
+type PValDetailObj struct {
+	Value       string                `json:"value"`
+	IndexKeyMap map[int]PValUpdateKey `json:"indexKeyMap"` //map of index at which replacement is to be done and name of key that is to for updating value
+}
+
+func NewRbacDataCacheFactoryImpl(logger *zap.SugaredLogger,
+	defaultRbacPolicyDataRepository RbacPolicyDataRepository,
+	defaultRbacRoleDataRepository RbacRoleDataRepository) *RbacDataCacheFactoryImpl {
+	policyCache := initialisePolicyDataCache()
+	roleCache := initialiseRoleDataCache()
+	return &RbacDataCacheFactoryImpl{
+		logger:                          logger,
+		policyCache:                     policyCache,
+		roleCache:                       roleCache,
+		defaultRbacPolicyDataRepository: defaultRbacPolicyDataRepository,
+		defaultRbacRoleDataRepository:   defaultRbacRoleDataRepository,
+	}
+}
+
+func (impl *RbacDataCacheFactoryImpl) GetDefaultRoleDataAndPolicyByEntityAccessTypeAndRoleType(entity, accessType, roleType string) (RoleCacheDetailObj, PolicyCacheDetailObj) {
+	defaultPolicyData := PolicyCacheDetailObj{}
+	defaultRoleData := RoleCacheDetailObj{}
+
+	//getting key for cache map
+	keyForMap := getCacheMapKey(entity, accessType, roleType)
+
+	//checking and getting default policy data from cache
+	if val, ok := impl.policyCache[keyForMap]; ok {
+		defaultPolicyData = val
+	}
+
+	//checking and getting default role data from cache
+	if val, ok := impl.roleCache[keyForMap]; ok {
+		defaultRoleData = val
+	}
+	return defaultRoleData, defaultPolicyData
+}
+
+func (impl *RbacDataCacheFactoryImpl) SyncPolicyCache() {
+	//getting all default policies
+	defaultRbacPolicies, err := impl.defaultRbacPolicyDataRepository.GetPolicyDataForAllRoles()
+	if err != nil {
+		return
+	}
+	for _, defaultRbacPolicy := range defaultRbacPolicies {
+		policyData := defaultRbacPolicy.PolicyData
+		var policyDataObj PolicyCacheDetailObj
+		err = json.Unmarshal([]byte(policyData), &policyDataObj)
+		if err != nil {
+			impl.logger.Errorw("error in unmarshalling policy data", "err", err)
+			continue
+		}
+		keyForMap := getCacheMapKey(defaultRbacPolicy.Entity, defaultRbacPolicy.AccessType, defaultRbacPolicy.Role)
+		impl.mutex.Lock()
+		impl.policyCache[keyForMap] = policyDataObj
+		impl.mutex.Unlock()
+	}
+}
+
+func (impl *RbacDataCacheFactoryImpl) SyncRoleDataCache() {
+	//getting all default policies
+	defaultRbacRoles, err := impl.defaultRbacRoleDataRepository.GetRoleDataForAllRoles()
+	if err != nil {
+		return
+	}
+	for _, defaultRbacRole := range defaultRbacRoles {
+		roleData := defaultRbacRole.RoleData
+		var roleDataObj RoleCacheDetailObj
+		err = json.Unmarshal([]byte(roleData), &roleDataObj)
+		if err != nil {
+			impl.logger.Errorw("error in unmarshalling role data", "err", err)
+			continue
+		}
+		keyForMap := getCacheMapKey(defaultRbacRole.Entity, defaultRbacRole.AccessType, defaultRbacRole.Role)
+		impl.mutex.Lock()
+		impl.roleCache[keyForMap] = roleDataObj
+		impl.mutex.Unlock()
+	}
+}
+
+func initialisePolicyDataCache() map[string]PolicyCacheDetailObj {
+	c := make(map[string]PolicyCacheDetailObj)
+	return c
+}
+
+func initialiseRoleDataCache() map[string]RoleCacheDetailObj {
+	c := make(map[string]RoleCacheDetailObj)
+	return c
+}
+
+func getCacheMapKey(entity, accessType, roleType string) string {
+	return fmt.Sprintf("%s_%s_%s", entity, accessType, roleType)
+}
diff --git a/pkg/user/repository/RbacPolicyDataRepository.go b/pkg/user/repository/RbacPolicyDataRepository.go
new file mode 100644
index 000000000..7d8cd49c1
--- /dev/null
+++ b/pkg/user/repository/RbacPolicyDataRepository.go
@@ -0,0 +1,66 @@
+package repository
+
+import (
+	"github.com/devtron-labs/devtron/pkg/sql"
+	"github.com/go-pg/pg"
+	"go.uber.org/zap"
+)
+
+type RbacPolicyDataRepository interface {
+	GetPolicyDataForAllRoles() ([]*RbacPolicyData, error)
+	CreateNewPolicyDataForRoleWithTxn(model *RbacPolicyData, tx *pg.Tx) (*RbacPolicyData, error)
+	UpdatePolicyDataForRoleWithTxn(model *RbacPolicyData, tx *pg.Tx) (*RbacPolicyData, error)
+}
+
+type RbacPolicyDataRepositoryImpl struct {
+	logger       *zap.SugaredLogger
+	dbConnection *pg.DB
+}
+
+func NewRbacPolicyDataRepositoryImpl(logger *zap.SugaredLogger,
+	dbConnection *pg.DB) *RbacPolicyDataRepositoryImpl {
+	return &RbacPolicyDataRepositoryImpl{
+		logger:       logger,
+		dbConnection: dbConnection,
+	}
+}
+
+type RbacPolicyData struct {
+	TableName    struct{} `sql:"rbac_policy_data" pg:",discard_unknown_columns"`
+	Id           int      `sql:"id"`
+	Entity       string   `sql:"entity"`
+	AccessType   string   `sql:"access_type"`
+	Role         string   `sql:"role"`
+	PolicyData   string   `sql:"policy_data"`
+	IsPresetRole bool     `sql:"is_preset_role,notnull"`
+	Deleted      bool     `sql:"deleted,notnull"`
+	sql.AuditLog
+}
+
+func (repo *RbacPolicyDataRepositoryImpl) GetPolicyDataForAllRoles() ([]*RbacPolicyData, error) {
+	var models []*RbacPolicyData
+	err := repo.dbConnection.Model(&models).Where("deleted = ?", false).Select()
+	if err != nil {
+		repo.logger.Errorw("error in getting policy data for all roles", "err", err)
+		return nil, err
+	}
+	return models, nil
+}
+
+func (repo *RbacPolicyDataRepositoryImpl) CreateNewPolicyDataForRoleWithTxn(model *RbacPolicyData, tx *pg.Tx) (*RbacPolicyData, error) {
+	_, err := tx.Model(model).Insert()
+	if err != nil {
+		repo.logger.Errorw("error in creating policy for a role", "err", err)
+		return nil, err
+	}
+	return model, nil
+}
+
+func (repo *RbacPolicyDataRepositoryImpl) UpdatePolicyDataForRoleWithTxn(model *RbacPolicyData, tx *pg.Tx) (*RbacPolicyData, error) {
+	_, err := tx.Model(model).UpdateNotNull()
+	if err != nil {
+		repo.logger.Errorw("error in updating policy for a role", "err", err)
+		return nil, err
+	}
+	return model, nil
+}
diff --git a/pkg/user/repository/RbacRoleDataRepository.go b/pkg/user/repository/RbacRoleDataRepository.go
new file mode 100644
index 000000000..5bb37f972
--- /dev/null
+++ b/pkg/user/repository/RbacRoleDataRepository.go
@@ -0,0 +1,68 @@
+package repository
+
+import (
+	"github.com/devtron-labs/devtron/pkg/sql"
+	"github.com/go-pg/pg"
+	"go.uber.org/zap"
+)
+
+type RbacRoleDataRepository interface {
+	GetRoleDataForAllRoles() ([]*RbacRoleData, error)
+	CreateNewRoleDataForRoleWithTxn(model *RbacRoleData, tx *pg.Tx) (*RbacRoleData, error)
+	UpdateRoleDataForRoleWithTxn(model *RbacRoleData, tx *pg.Tx) (*RbacRoleData, error)
+}
+
+type RbacRoleDataRepositoryImpl struct {
+	logger       *zap.SugaredLogger
+	dbConnection *pg.DB
+}
+
+func NewRbacRoleDataRepositoryImpl(logger *zap.SugaredLogger,
+	dbConnection *pg.DB) *RbacRoleDataRepositoryImpl {
+	return &RbacRoleDataRepositoryImpl{
+		logger:       logger,
+		dbConnection: dbConnection,
+	}
+}
+
+type RbacRoleData struct {
+	TableName       struct{} `sql:"rbac_role_data" pg:",discard_unknown_columns"`
+	Id              int      `sql:"id"`
+	Entity          string   `sql:"entity"`
+	AccessType      string   `sql:"access_type"`
+	Role            string   `sql:"role"`
+	RoleData        string   `sql:"role_data"`
+	RoleDisplayName string   `sql:"role_display_name"`
+	RoleDescription string   `sql:"role_description"`
+	IsPresetRole    bool     `sql:"is_preset_role,notnull"`
+	Deleted         bool     `sql:"deleted,notnull"`
+	sql.AuditLog
+}
+
+func (repo *RbacRoleDataRepositoryImpl) GetRoleDataForAllRoles() ([]*RbacRoleData, error) {
+	var models []*RbacRoleData
+	err := repo.dbConnection.Model(&models).Where("deleted = ?", false).Select()
+	if err != nil {
+		repo.logger.Errorw("error in getting role data for all roles", "err", err)
+		return nil, err
+	}
+	return models, nil
+}
+
+func (repo *RbacRoleDataRepositoryImpl) CreateNewRoleDataForRoleWithTxn(model *RbacRoleData, tx *pg.Tx) (*RbacRoleData, error) {
+	_, err := tx.Model(model).Insert()
+	if err != nil {
+		repo.logger.Errorw("error in creating role data for a role", "err", err)
+		return nil, err
+	}
+	return model, nil
+}
+
+func (repo *RbacRoleDataRepositoryImpl) UpdateRoleDataForRoleWithTxn(model *RbacRoleData, tx *pg.Tx) (*RbacRoleData, error) {
+	_, err := tx.Model(model).UpdateNotNull()
+	if err != nil {
+		repo.logger.Errorw("error in updating role data for a role", "err", err)
+		return nil, err
+	}
+	return model, nil
+}
diff --git a/pkg/user/repository/UserAuthRepository.go b/pkg/user/repository/UserAuthRepository.go
index 5b13a3004..8c5c850a7 100644
--- a/pkg/user/repository/UserAuthRepository.go
+++ b/pkg/user/repository/UserAuthRepository.go
@@ -35,7 +35,8 @@ import (
 )
 
 type UserAuthRepository interface {
-	CreateRole(userModel *RoleModel, tx *pg.Tx) (*RoleModel, error)
+	CreateRole(role *RoleModel) (*RoleModel, error)
+	CreateRoleWithTxn(userModel *RoleModel, tx *pg.Tx) (*RoleModel, error)
 	GetRoleById(id int) (*RoleModel, error)
 	GetRolesByIds(ids []int) ([]RoleModel, error)
 	GetRoleByRoles(roles []string) ([]RoleModel, error)
@@ -134,7 +135,16 @@ type ClusterRolePolicyDetails struct {
 	ResourceObj  string
 }
 
-func (impl UserAuthRepositoryImpl) CreateRole(userModel *RoleModel, tx *pg.Tx) (*RoleModel, error) {
+func (impl UserAuthRepositoryImpl) CreateRole(role *RoleModel) (*RoleModel, error) {
+	err := impl.dbConnection.Insert(role)
+	if err != nil {
+		impl.Logger.Error("error in creating role", "err", err, "role", role)
+		return role, err
+	}
+	return role, nil
+}
+
+func (impl UserAuthRepositoryImpl) CreateRoleWithTxn(userModel *RoleModel, tx *pg.Tx) (*RoleModel, error) {
 	err := tx.Insert(userModel)
 	if err != nil {
 		impl.Logger.Error(err)
@@ -142,6 +152,7 @@ func (impl UserAuthRepositoryImpl) CreateRole(userModel *RoleModel, tx *pg.Tx) (
 	}
 	return userModel, nil
 }
+
 func (impl UserAuthRepositoryImpl) GetRoleById(id int) (*RoleModel, error) {
 	var model RoleModel
 	err := impl.dbConnection.Model(&model).Where("id = ?", id).Select()
@@ -507,7 +518,7 @@ func (impl UserAuthRepositoryImpl) CreateDefaultPoliciesForAllTypes(team, entity
 		impl.Logger.Errorw("decode err", "err", err)
 		return false, err, nil
 	}
-	_, err = impl.createRole(&roleData, tx, UserId)
+	_, err = impl.createRole(&roleData, UserId)
 	if err != nil && strings.Contains("duplicate key value violates unique constraint", err.Error()) {
 		return false, err, nil
 	}
@@ -518,14 +529,6 @@ func (impl UserAuthRepositoryImpl) CreateDefaultPoliciesForAllTypes(team, entity
 	return true, nil, policiesToBeAdded
 }
 func (impl UserAuthRepositoryImpl) CreateRolesWithAccessTypeAndEntity(team, entityName, env, entity, cluster, namespace, group, kind, resource, actionType, accessType string, UserId int32, role string) (bool, error) {
-	dbConnection := impl.dbConnection
-	tx, err := dbConnection.Begin()
-	if err != nil {
-		return false, err
-	}
-	// Rollback tx on error.
-	defer tx.Rollback()
-
 	roleData := bean.RoleData{
 		Role:        role,
 		Entity:      entity,
@@ -540,14 +543,10 @@ func (impl UserAuthRepositoryImpl) CreateRolesWithAccessTypeAndEntity(team, enti
 		Kind:        kind,
 		Resource:    resource,
 	}
-	_, err = impl.createRole(&roleData, tx, UserId)
+	_, err := impl.createRole(&roleData, UserId)
 	if err != nil && strings.Contains("duplicate key value violates unique constraint", err.Error()) {
 		return false, err
 	}
-	err = tx.Commit()
-	if err != nil {
-		return false, err
-	}
 	return true, nil
 }
 
@@ -571,7 +570,7 @@ func (impl UserAuthRepositoryImpl) CreateRoleForSuperAdminIfNotExists(tx *pg.Tx,
 			impl.Logger.Errorw("decode err", "err", err)
 			return false, err
 		}
-		_, err = impl.createRole(&roleManagerData, transaction, UserId)
+		_, err = impl.createRole(&roleManagerData, UserId)
 		if err != nil && strings.Contains("duplicate key value violates unique constraint", err.Error()) {
 			return false, err
 		}
@@ -583,7 +582,7 @@ func (impl UserAuthRepositoryImpl) CreateRoleForSuperAdminIfNotExists(tx *pg.Tx,
 	return true, nil
 }
 
-func (impl UserAuthRepositoryImpl) createRole(roleData *bean.RoleData, tx *pg.Tx, UserId int32) (bool, error) {
+func (impl UserAuthRepositoryImpl) createRole(roleData *bean.RoleData, UserId int32) (bool, error) {
 	roleModel := &RoleModel{
 		Role:        roleData.Role,
 		Entity:      roleData.Entity,
@@ -604,7 +603,7 @@ func (impl UserAuthRepositoryImpl) createRole(roleData *bean.RoleData, tx *pg.Tx
 			UpdatedOn: time.Now(),
 		},
 	}
-	roleModel, err := impl.CreateRole(roleModel, tx)
+	roleModel, err := impl.CreateRole(roleModel)
 	if err != nil || roleModel == nil {
 		return false, err
 	}
diff --git a/pkg/user/repository/bean.go b/pkg/user/repository/bean.go
new file mode 100644
index 000000000..d1bb587fd
--- /dev/null
+++ b/pkg/user/repository/bean.go
@@ -0,0 +1,24 @@
+package repository
+
+type PValUpdateKey string
+
+const (
+	EntityPValUpdateKey       PValUpdateKey = "Entity"
+	EntityNamePValUpdateKey   PValUpdateKey = "EntityName"
+	AppPValUpdateKey          PValUpdateKey = "App"
+	EnvPValUpdateKey          PValUpdateKey = "Env"
+	TeamPValUpdateKey         PValUpdateKey = "Team"
+	ClusterPValUpdateKey      PValUpdateKey = "Cluster"
+	NamespacePValUpdateKey    PValUpdateKey = "Namespace"
+	GroupPValUpdateKey        PValUpdateKey = "Group"
+	KindPValUpdateKey         PValUpdateKey = "Kind"
+	ResourcePValUpdateKey     PValUpdateKey = "Resource"
+	AppObjPValUpdateKey       PValUpdateKey = "AppObj"
+	EnvObjPValUpdateKey       PValUpdateKey = "EnvObj"
+	TeamObjPValUpdateKey      PValUpdateKey = "TeamObj"
+	ClusterObjPValUpdateKey   PValUpdateKey = "ClusterObj"
+	NamespaceObjPValUpdateKey PValUpdateKey = "NamespaceObj"
+	GroupObjPValUpdateKey     PValUpdateKey = "GroupObj"
+	KindObjPValUpdateKey      PValUpdateKey = "KindObj"
+	ResourceObjPValUpdateKey  PValUpdateKey = "ResourceObj"
+)
diff --git a/scripts/sql/128_create_auth_data.down.sql b/scripts/sql/128_create_auth_data.down.sql
new file mode 100644
index 000000000..bedb09302
--- /dev/null
+++ b/scripts/sql/128_create_auth_data.down.sql
@@ -0,0 +1,2 @@
+DROP TABLE IF EXISTS "public"."rbac_policy_data";
+DROP TABLE IF EXISTS "public"."rbac_role_data";
\ No newline at end of file
diff --git a/scripts/sql/128_create_auth_data.up.sql b/scripts/sql/128_create_auth_data.up.sql
new file mode 100644
index 000000000..ac511890b
--- /dev/null
+++ b/scripts/sql/128_create_auth_data.up.sql
@@ -0,0 +1,1426 @@
+-- Sequence and defined type
+CREATE SEQUENCE IF NOT EXISTS id_seq_rbac_policy_data;
+
+-- Table Definition
+CREATE TABLE IF NOT EXISTS "public"."rbac_policy_data"
+(
+    "id"             int          NOT NULL DEFAULT nextval('id_seq_rbac_policy_data'::regclass),
+    "entity"         varchar(250) NOT NULL,
+    "access_type"    varchar(250) NOT NULL,
+    "role"           varchar(250) NOT NULL,
+    "policy_data"    jsonb        NOT NULL,
+    "created_on"     timestamptz,
+    "created_by"     integer,
+    "updated_on"     timestamptz,
+    "updated_by"     integer,
+    "is_preset_role" boolean      NOT NULL DEFAULT FALSE,
+    "deleted"        boolean      NOT NULL,
+    PRIMARY KEY ("id"),
+    UNIQUE ("entity", "access_type", "role")
+);
+
+
+INSERT INTO "public"."rbac_policy_data" ("entity", "access_type", "role", "policy_data", "created_on", "created_by",
+                                         "updated_on", "updated_by", "is_preset_role", "deleted")
+VALUES ('apps', 'devtron-app', 'manager', '{
+  "type": {
+    "value": "p",
+    "indexKeyMap": {}
+  },
+  "sub": {
+    "value": "role:manager_%_%_%",
+    "indexKeyMap": {
+      "13": "Team",
+      "15": "Env",
+      "17": "App"
+    }
+  },
+  "resActObjSet": [
+    {
+      "res": {
+        "value": "applications",
+        "indexKeyMap": {}
+      },
+      "act": {
+        "value": "*",
+        "indexKeyMap": {}
+      },
+      "obj": {
+        "value": "%/%",
+        "indexKeyMap": {
+          "0": "TeamObj",
+          "2": "AppObj"
+        }
+      }
+    },
+    {
+      "res": {
+        "value": "environment",
+        "indexKeyMap": {}
+      },
+      "act": {
+        "value": "*",
+        "indexKeyMap": {}
+      },
+      "obj": {
+        "value": "%/%",
+        "indexKeyMap": {
+          "0": "EnvObj",
+          "2": "AppObj"
+        }
+      }
+    },
+    {
+      "res": {
+        "value": "team",
+        "indexKeyMap": {}
+      },
+      "act": {
+        "value": "*",
+        "indexKeyMap": {}
+      },
+      "obj": {
+        "value": "%",
+        "indexKeyMap": {
+          "0": "TeamObj"
+        }
+      }
+    },
+    {
+      "res": {
+        "value": "user",
+        "indexKeyMap": {}
+      },
+      "act": {
+        "value": "*",
+        "indexKeyMap": {}
+      },
+      "obj": {
+        "value": "%",
+        "indexKeyMap": {
+          "0": "TeamObj"
+        }
+      }
+    },
+    {
+      "res": {
+        "value": "notification",
+        "indexKeyMap": {}
+      },
+      "act": {
+        "value": "*",
+        "indexKeyMap": {}
+      },
+      "obj": {
+        "value": "%",
+        "indexKeyMap": {
+          "0": "TeamObj"
+        }
+      }
+    },
+    {
+      "res": {
+        "value": "global-environment",
+        "indexKeyMap": {}
+      },
+      "act": {
+        "value": "*",
+        "indexKeyMap": {}
+      },
+      "obj": {
+        "value": "%",
+        "indexKeyMap": {
+          "0": "EnvObj"
+        }
+      }
+    }
+  ]
+}', 'now()', '1', 'now()', '1', true, false),
+       ('apps', 'devtron-app', 'admin', '{
+         "type": {
+           "value": "p",
+           "indexKeyMap": {}
+         },
+         "sub": {
+           "value": "role:admin_%_%_%",
+           "indexKeyMap": {
+             "11": "Team",
+             "13": "Env",
+             "15": "App"
+           }
+         },
+         "resActObjSet": [
+           {
+             "res": {
+               "value": "applications",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "*",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%/%",
+               "indexKeyMap": {
+                 "0": "TeamObj",
+                 "2": "AppObj"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "environment",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "*",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%/%",
+               "indexKeyMap": {
+                 "0": "EnvObj",
+                 "2": "AppObj"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "team",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%",
+               "indexKeyMap": {
+                 "0": "TeamObj"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "global-environment",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%",
+               "indexKeyMap": {
+                 "0": "EnvObj"
+               }
+             }
+           }
+         ]
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('apps', 'devtron-app', 'trigger', '{
+         "type": {
+           "value": "p",
+           "indexKeyMap": {}
+         },
+         "sub": {
+           "value": "role:trigger_%_%_%",
+           "indexKeyMap": {
+             "13": "Team",
+             "15": "Env",
+             "17": "App"
+           }
+         },
+         "resActObjSet": [
+           {
+             "res": {
+               "value": "applications",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%/%",
+               "indexKeyMap": {
+                 "0": "TeamObj",
+                 "2": "AppObj"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "applications",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "trigger",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%/%",
+               "indexKeyMap": {
+                 "0": "TeamObj",
+                 "2": "AppObj"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "environment",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%/%",
+               "indexKeyMap": {
+                 "0": "EnvObj",
+                 "2": "AppObj"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "environment",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "trigger",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%/%",
+               "indexKeyMap": {
+                 "0": "EnvObj",
+                 "2": "AppObj"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "team",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%",
+               "indexKeyMap": {
+                 "0": "TeamObj"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "global-environment",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%",
+               "indexKeyMap": {
+                 "0": "EnvObj"
+               }
+             }
+           }
+         ]
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('apps', 'devtron-app', 'view', '{
+         "type": {
+           "value": "p",
+           "indexKeyMap": {}
+         },
+         "sub": {
+           "value": "role:view_%_%_%",
+           "indexKeyMap": {
+             "10": "Team",
+             "12": "Env",
+             "14": "App"
+           }
+         },
+         "resActObjSet": [
+           {
+             "res": {
+               "value": "applications",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%/%",
+               "indexKeyMap": {
+                 "0": "TeamObj",
+                 "2": "AppObj"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "environment",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%/%",
+               "indexKeyMap": {
+                 "0": "EnvObj",
+                 "2": "AppObj"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "team",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%",
+               "indexKeyMap": {
+                 "0": "TeamObj"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "global-environment",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%",
+               "indexKeyMap": {
+                 "0": "EnvObj"
+               }
+             }
+           }
+         ]
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('chart-group', '', 'admin', '{
+         "type": {
+           "value": "p",
+           "indexKeyMap": {}
+         },
+         "sub": {
+           "value": "role:%_admin",
+           "indexKeyMap": {
+             "5": "Entity"
+           }
+         },
+         "resActObjSet": [
+           {
+             "res": {
+               "value": "%",
+               "indexKeyMap": {
+                 "0": "Entity"
+               }
+             },
+             "act": {
+               "value": "*",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "*",
+               "indexKeyMap": {}
+             }
+           }
+         ]
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('chart-group', '', 'view', '{
+         "type": {
+           "value": "p",
+           "indexKeyMap": {}
+         },
+         "sub": {
+           "value": "role:%_view",
+           "indexKeyMap": {
+             "5": "Entity"
+           }
+         },
+         "resActObjSet": [
+           {
+             "res": {
+               "value": "%",
+               "indexKeyMap": {
+                 "0": "Entity"
+               }
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "*",
+               "indexKeyMap": {}
+             }
+           }
+         ]
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('chart-group', '', 'update', '{
+         "type": {
+           "value": "p",
+           "indexKeyMap": {}
+         },
+         "sub": {
+           "value": "role:%_%_specific",
+           "indexKeyMap": {
+             "5": "Entity",
+             "7": "EntityName"
+           }
+         },
+         "resActObjSet": [
+           {
+             "res": {
+               "value": "%",
+               "indexKeyMap": {
+                 "0": "Entity"
+               }
+             },
+             "act": {
+               "value": "update",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%",
+               "indexKeyMap": {
+                 "0": "EntityName"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "%",
+               "indexKeyMap": {
+                 "0": "Entity"
+               }
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%",
+               "indexKeyMap": {
+                 "0": "EntityName"
+               }
+             }
+           }
+         ]
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('apps', 'helm-app', 'admin', '{
+         "type": {
+           "value": "p",
+           "indexKeyMap": {}
+         },
+         "sub": {
+           "value": "helm-app:admin_%_%_%",
+           "indexKeyMap": {
+             "15": "Team",
+             "17": "Env",
+             "19": "App"
+           }
+         },
+         "resActObjSet": [
+           {
+             "res": {
+               "value": "helm-app",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "*",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%/%/%",
+               "indexKeyMap": {
+                 "0": "TeamObj",
+                 "2": "EnvObj",
+                 "4": "AppObj"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "team",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%",
+               "indexKeyMap": {
+                 "0": "TeamObj"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "global-environment",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%",
+               "indexKeyMap": {
+                 "0": "EnvObj"
+               }
+             }
+           }
+         ]
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('apps', 'helm-app', 'edit', '{
+         "type": {
+           "value": "p",
+           "indexKeyMap": {}
+         },
+         "sub": {
+           "value": "helm-app:edit_%_%_%",
+           "indexKeyMap": {
+             "14": "Team",
+             "16": "Env",
+             "18": "App"
+           }
+         },
+         "resActObjSet": [
+           {
+             "res": {
+               "value": "helm-app",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%/%/%",
+               "indexKeyMap": {
+                 "0": "TeamObj",
+                 "2": "EnvObj",
+                 "4": "AppObj"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "helm-app",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "update",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%/%/%",
+               "indexKeyMap": {
+                 "0": "TeamObj",
+                 "2": "EnvObj",
+                 "4": "AppObj"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "global-environment",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%",
+               "indexKeyMap": {
+                 "0": "EnvObj"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "team",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%",
+               "indexKeyMap": {
+                 "0": "TeamObj"
+               }
+             }
+           }
+         ]
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('apps', 'helm-app', 'view', '{
+         "type": {
+           "value": "p",
+           "indexKeyMap": {}
+         },
+         "sub": {
+           "value": "helm-app:view_%_%_%",
+           "indexKeyMap": {
+             "14": "Team",
+             "16": "Env",
+             "18": "App"
+           }
+         },
+         "resActObjSet": [
+           {
+             "res": {
+               "value": "helm-app",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%/%/%",
+               "indexKeyMap": {
+                 "0": "TeamObj",
+                 "2": "EnvObj",
+                 "4": "AppObj"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "global-environment",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%",
+               "indexKeyMap": {
+                 "0": "EnvObj"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "team",
+               "indexKeyMap": {}
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%",
+               "indexKeyMap": {
+                 "0": "TeamObj"
+               }
+             }
+           }
+         ]
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('cluster', '', 'admin', '{
+         "type": {
+           "value": "p",
+           "indexKeyMap": {}
+         },
+         "sub": {
+           "value": "role:clusterAdmin_%_%_%_%_%",
+           "indexKeyMap": {
+             "18": "Cluster",
+             "20": "Namespace",
+             "22": "Group",
+             "24": "Kind",
+             "26": "Resource"
+           }
+         },
+         "resActObjSet": [
+           {
+             "res": {
+               "value": "%/%",
+               "indexKeyMap": {
+                 "0": "ClusterObj",
+                 "2": "NamespaceObj"
+               }
+             },
+             "act": {
+               "value": "*",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%/%/%",
+               "indexKeyMap": {
+                 "0": "GroupObj",
+                 "2": "KindObj",
+                 "4": "ResourceObj"
+               }
+             }
+           },
+           {
+             "res": {
+               "value": "%/%/user",
+               "indexKeyMap": {
+                 "0": "ClusterObj",
+                 "2": "NamespaceObj"
+               }
+             },
+             "act": {
+               "value": "*",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%/%/%",
+               "indexKeyMap": {
+                 "0": "GroupObj",
+                 "2": "KindObj",
+                 "4": "ResourceObj"
+               }
+             }
+           }
+         ]
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('cluster', '', 'edit', '{
+         "type": {
+           "value": "p",
+           "indexKeyMap": {}
+         },
+         "sub": {
+           "value": "role:clusterEdit_%_%_%_%_%",
+           "indexKeyMap": {
+             "17": "Cluster",
+             "19": "Namespace",
+             "21": "Group",
+             "23": "Kind",
+             "25": "Resource"
+           }
+         },
+         "resActObjSet": [
+           {
+             "res": {
+               "value": "%/%",
+               "indexKeyMap": {
+                 "0": "ClusterObj",
+                 "2": "NamespaceObj"
+               }
+             },
+             "act": {
+               "value": "*",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%/%/%",
+               "indexKeyMap": {
+                 "0": "GroupObj",
+                 "2": "KindObj",
+                 "4": "ResourceObj"
+               }
+             }
+           }
+         ]
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('cluster', '', 'view', '{
+         "type": {
+           "value": "p",
+           "indexKeyMap": {}
+         },
+         "sub": {
+           "value": "role:clusterView_%_%_%_%_%",
+           "indexKeyMap": {
+             "17": "Cluster",
+             "19": "Namespace",
+             "21": "Group",
+             "23": "Kind",
+             "25": "Resource"
+           }
+         },
+         "resActObjSet": [
+           {
+             "res": {
+               "value": "%/%",
+               "indexKeyMap": {
+                 "0": "ClusterObj",
+                 "2": "NamespaceObj"
+               }
+             },
+             "act": {
+               "value": "get",
+               "indexKeyMap": {}
+             },
+             "obj": {
+               "value": "%/%/%",
+               "indexKeyMap": {
+                 "0": "GroupObj",
+                 "2": "KindObj",
+                 "4": "ResourceObj"
+               }
+             }
+           }
+         ]
+       }', 'now()', '1', 'now()', '1', true, false);
+
+
+-- Sequence and defined type
+CREATE SEQUENCE IF NOT EXISTS id_seq_rbac_role_data;
+
+-- Table Definition
+CREATE TABLE IF NOT EXISTS "public"."rbac_role_data"
+(
+    "id"                int          NOT NULL DEFAULT nextval('id_seq_rbac_role_data'::regclass),
+    "entity"            varchar(250) NOT NULL,
+    "access_type"       varchar(250) NOT NULL,
+    "role"              varchar(250) NOT NULL,
+    "role_display_name" varchar(250) NOT NULL,
+    "role_data"         jsonb        NOT NULL,
+    "role_description"  text,
+    "created_on"        timestamptz,
+    "created_by"        integer,
+    "updated_on"        timestamptz,
+    "updated_by"        integer,
+    "is_preset_role"    boolean      NOT NULL DEFAULT FALSE,
+    "deleted"           boolean      NOT NULL,
+    PRIMARY KEY ("id"),
+    UNIQUE ("entity", "access_type", "role")
+);
+
+
+INSERT INTO "public"."rbac_role_data" ("entity", "access_type", "role", "role_display_name", "role_description",
+                                       "role_data", "created_on", "created_by", "updated_on", "updated_by",
+                                       "is_preset_role", "deleted")
+VALUES ('apps', 'devtron-app', 'manager', 'Manager',
+        'Can view, trigger and edit selected applications. Can also manage user access.', '{
+    "role": {
+      "value": "role:manager_%_%_%",
+      "indexKeyMap": {
+        "13": "Team",
+        "15": "Env",
+        "17": "App"
+      }
+    },
+    "team": {
+      "value": "%",
+      "indexKeyMap": {
+        "0": "Team"
+      }
+    },
+    "entityName": {
+      "value": "%",
+      "indexKeyMap": {
+        "0": "App"
+      }
+    },
+    "environment": {
+      "value": "%",
+      "indexKeyMap": {
+        "0": "Env"
+      }
+    },
+    "action": {
+      "value": "manager",
+      "indexKeyMap": {}
+    },
+    "entity": {
+      "value": "%",
+      "indexKeyMap": {
+        "0": "Entity"
+      }
+    },
+    "accessType": {
+      "value": "devtron-app",
+      "indexKeyMap": {}
+    }
+  }', 'now()', '1', 'now()', '1', true, false),
+       ('apps', 'devtron-app', 'admin', 'Admin', 'Can view, trigger and edit selected applications', '{
+         "role": {
+           "value": "role:admin_%_%_%",
+           "indexKeyMap": {
+             "11": "Team",
+             "13": "Env",
+             "15": "App"
+           }
+         },
+         "team": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Team"
+           }
+         },
+         "entityName": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "App"
+           }
+         },
+         "environment": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Env"
+           }
+         },
+         "action": {
+           "value": "admin",
+           "indexKeyMap": {}
+         },
+         "entity": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Entity"
+           }
+         },
+         "accessType": {
+           "value": "devtron-app",
+           "indexKeyMap": {}
+         }
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('apps', 'devtron-app', 'trigger', 'Build and deploy', 'Can build and deploy apps on selected environments', '{
+         "role": {
+           "value": "role:trigger_%_%_%",
+           "indexKeyMap": {
+             "13": "Team",
+             "15": "Env",
+             "17": "App"
+           }
+         },
+         "team": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Team"
+           }
+         },
+         "entityName": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "App"
+           }
+         },
+         "environment": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Env"
+           }
+         },
+         "action": {
+           "value": "trigger",
+           "indexKeyMap": {}
+         },
+         "entity": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Entity"
+           }
+         },
+         "accessType": {
+           "value": "devtron-app",
+           "indexKeyMap": {}
+         }
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('apps', 'devtron-app', 'view', 'View only', 'Can view selected applications', '{
+         "role": {
+           "value": "role:view_%_%_%",
+           "indexKeyMap": {
+             "10": "Team",
+             "12": "Env",
+             "14": "App"
+           }
+         },
+         "team": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Team"
+           }
+         },
+         "entityName": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "App"
+           }
+         },
+         "environment": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Env"
+           }
+         },
+         "action": {
+           "value": "view",
+           "indexKeyMap": {}
+         },
+         "entity": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Entity"
+           }
+         },
+         "accessType": {
+           "value": "devtron-app",
+           "indexKeyMap": {}
+         }
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('chart-group', '', 'admin', 'Admin', '', '{
+         "role": {
+           "value": "role:%_admin",
+           "indexKeyMap": {
+             "5": "Entity"
+           }
+         },
+         "entity": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Entity"
+           }
+         },
+         "action": {
+           "value": "admin",
+           "indexKeyMap": {}
+         }
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('chart-group', '', 'view', 'View', '', '{
+         "role": {
+           "value": "role:%_view",
+           "indexKeyMap": {
+             "5": "Entity"
+           }
+         },
+         "entity": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Entity"
+           }
+         },
+         "action": {
+           "value": "view",
+           "indexKeyMap": {}
+         }
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('chart-group', '', 'update', 'Update', '', '{
+         "role": {
+           "value": "role:%_%_specific",
+           "indexKeyMap": {
+             "5": "Entity",
+             "7": "EntityName"
+           }
+         },
+         "entityName": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "EntityName"
+           }
+         },
+         "entity": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Entity"
+           }
+         },
+         "action": {
+           "value": "update",
+           "indexKeyMap": {}
+         }
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('apps', 'helm-app', 'admin', 'Admin', 'Complete access on selected applications', '{
+         "role": {
+           "value": "helm-app:admin_%_%_%",
+           "indexKeyMap": {
+             "15": "Team",
+             "17": "Env",
+             "19": "App"
+           }
+         },
+         "team": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Team"
+           }
+         },
+         "entityName": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "App"
+           }
+         },
+         "environment": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Env"
+           }
+         },
+         "action": {
+           "value": "admin",
+           "indexKeyMap": {}
+         },
+         "entity": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Entity"
+           }
+         },
+         "accessType": {
+           "value": "helm-app",
+           "indexKeyMap": {}
+         }
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('apps', 'helm-app', 'edit', 'View & Edit', 'Can also edit resource manifests of selected application(s)', '{
+         "role": {
+           "value": "helm-app:edit_%_%_%",
+           "indexKeyMap": {
+             "14": "Team",
+             "16": "Env",
+             "18": "App"
+           }
+         },
+         "team": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Team"
+           }
+         },
+         "entityName": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "App"
+           }
+         },
+         "environment": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Env"
+           }
+         },
+         "action": {
+           "value": "edit",
+           "indexKeyMap": {}
+         },
+         "entity": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Entity"
+           }
+         },
+         "accessType": {
+           "value": "helm-app",
+           "indexKeyMap": {}
+         }
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('apps', 'helm-app', 'view', 'View only',
+        'Can view selected application(s) and resource manifests of selected application(s)', '{
+         "role": {
+           "value": "helm-app:view_%_%_%",
+           "indexKeyMap": {
+             "14": "Team",
+             "16": "Env",
+             "18": "App"
+           }
+         },
+         "team": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Team"
+           }
+         },
+         "entityName": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "App"
+           }
+         },
+         "environment": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Env"
+           }
+         },
+         "action": {
+           "value": "view",
+           "indexKeyMap": {}
+         },
+         "entity": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Entity"
+           }
+         },
+         "accessType": {
+           "value": "helm-app",
+           "indexKeyMap": {}
+         }
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('cluster', '', 'admin', 'Manager',
+        'Create, view, edit & delete allowed K8s resources. Can also manage user access.', '{
+         "role": {
+           "value": "role:clusterAdmin_%_%_%_%_%",
+           "indexKeyMap": {
+             "18": "Cluster",
+             "20": "Namespace",
+             "22": "Group",
+             "24": "Kind",
+             "26": "Resource"
+           }
+         },
+         "entity": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Entity"
+           }
+         },
+         "cluster": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Cluster"
+           }
+         },
+         "namespace": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Namespace"
+           }
+         },
+         "group": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Group"
+           }
+         },
+         "kind": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Kind"
+           }
+         },
+         "resource": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Resource"
+           }
+         },
+         "action": {
+           "value": "admin",
+           "indexKeyMap": {}
+         }
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('cluster', '', 'edit', 'Admin', 'Create, view, edit & delete allowed K8s resources.', '{
+         "role": {
+           "value": "role:clusterEdit_%_%_%_%_%",
+           "indexKeyMap": {
+             "17": "Cluster",
+             "19": "Namespace",
+             "21": "Group",
+             "23": "Kind",
+             "25": "Resource"
+           }
+         },
+         "entity": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Entity"
+           }
+         },
+         "cluster": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Cluster"
+           }
+         },
+         "namespace": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Namespace"
+           }
+         },
+         "group": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Group"
+           }
+         },
+         "kind": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Kind"
+           }
+         },
+         "resource": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Resource"
+           }
+         },
+         "action": {
+           "value": "edit",
+           "indexKeyMap": {}
+         }
+       }', 'now()', '1', 'now()', '1', true, false),
+       ('cluster', '', 'view', 'View', 'View allowed K8s resources.', '{
+         "role": {
+           "value": "role:clusterView_%_%_%_%_%",
+           "indexKeyMap": {
+             "17": "Cluster",
+             "19": "Namespace",
+             "21": "Group",
+             "23": "Kind",
+             "25": "Resource"
+           }
+         },
+         "entity": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Entity"
+           }
+         },
+         "cluster": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Cluster"
+           }
+         },
+         "namespace": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Namespace"
+           }
+         },
+         "group": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Group"
+           }
+         },
+         "kind": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Kind"
+           }
+         },
+         "resource": {
+           "value": "%",
+           "indexKeyMap": {
+             "0": "Resource"
+           }
+         },
+         "action": {
+           "value": "view",
+           "indexKeyMap": {}
+         }
+       }', 'now()', '1', 'now()', '1', true, false);
\ No newline at end of file
diff --git a/wire_gen.go b/wire_gen.go
index 53f3605b2..3fd0bfd37 100644
--- a/wire_gen.go
+++ b/wire_gen.go
@@ -233,7 +233,10 @@ func InitializeApp() (*App, error) {
 	apiTokenSecretStore := apiTokenAuth.InitApiTokenSecretStore()
 	sessionManager := middleware.NewSessionManager(settings, dexConfig, apiTokenSecretStore)
 	loginService := middleware.NewUserLogin(sessionManager, k8sClient)
-	userCommonServiceImpl := user.NewUserCommonServiceImpl(userAuthRepositoryImpl, sugaredLogger, userRepositoryImpl, roleGroupRepositoryImpl, sessionManager)
+	defaultRbacPolicyDataRepositoryImpl := repository4.NewRbacPolicyDataRepositoryImpl(sugaredLogger, db)
+	defaultRbacRoleDataRepositoryImpl := repository4.NewRbacRoleDataRepositoryImpl(sugaredLogger, db)
+	defaultRbacDataCacheFactoryImpl := repository4.NewRbacDataCacheFactoryImpl(sugaredLogger, defaultRbacPolicyDataRepositoryImpl, defaultRbacRoleDataRepositoryImpl)
+	userCommonServiceImpl := user.NewUserCommonServiceImpl(userAuthRepositoryImpl, sugaredLogger, userRepositoryImpl, roleGroupRepositoryImpl, sessionManager, defaultRbacDataCacheFactoryImpl)
 	userAuditRepositoryImpl := repository4.NewUserAuditRepositoryImpl(db)
 	userAuditServiceImpl := user.NewUserAuditServiceImpl(sugaredLogger, userAuditRepositoryImpl)
 	userServiceImpl := user.NewUserServiceImpl(userAuthRepositoryImpl, sugaredLogger, userRepositoryImpl, roleGroupRepositoryImpl, sessionManager, userCommonServiceImpl, userAuditServiceImpl)
@@ -614,7 +617,7 @@ func InitializeApp() (*App, error) {
 	telemetryRestHandlerImpl := restHandler.NewTelemetryRestHandlerImpl(sugaredLogger, telemetryEventClientImplExtended, enforcerImpl, userServiceImpl)
 	telemetryRouterImpl := router.NewTelemetryRouterImpl(sugaredLogger, telemetryRestHandlerImpl)
 	bulkUpdateRepositoryImpl := bulkUpdate.NewBulkUpdateRepository(db, sugaredLogger)
-	bulkUpdateServiceImpl, err := bulkAction.NewBulkUpdateServiceImpl(bulkUpdateRepositoryImpl, chartRepositoryImpl, sugaredLogger, chartTemplateServiceImpl, chartRepoRepositoryImpl, defaultChart, utilMergeUtil, repositoryServiceClientImpl, chartRefRepositoryImpl, envConfigOverrideRepositoryImpl, pipelineConfigRepositoryImpl, configMapRepositoryImpl, environmentRepositoryImpl, pipelineRepositoryImpl, appLevelMetricsRepositoryImpl, envLevelAppMetricsRepositoryImpl, httpClient, appRepositoryImpl, deploymentTemplateHistoryServiceImpl, configMapHistoryServiceImpl, workflowDagExecutorImpl, cdWorkflowRepositoryImpl, pipelineBuilderImpl, helmAppServiceImpl, enforcerUtilImpl, enforcerUtilHelmImpl, ciHandlerImpl, ciPipelineRepositoryImpl, appWorkflowRepositoryImpl, appWorkflowServiceImpl, pubSubClientServiceImpl)
+	bulkUpdateServiceImpl, err := bulkAction.NewBulkUpdateServiceImpl(bulkUpdateRepositoryImpl, chartRepositoryImpl, sugaredLogger, chartTemplateServiceImpl, chartRepoRepositoryImpl, defaultChart, utilMergeUtil, repositoryServiceClientImpl, chartRefRepositoryImpl, envConfigOverrideRepositoryImpl, pipelineConfigRepositoryImpl, configMapRepositoryImpl, environmentRepositoryImpl, pipelineRepositoryImpl, appLevelMetricsRepositoryImpl, envLevelAppMetricsRepositoryImpl, httpClient, appRepositoryImpl, deploymentTemplateHistoryServiceImpl, configMapHistoryServiceImpl, workflowDagExecutorImpl, cdWorkflowRepositoryImpl, pipelineBuilderImpl, helmAppServiceImpl, enforcerUtilImpl, enforcerUtilHelmImpl, ciHandlerImpl, ciPipelineRepositoryImpl, appWorkflowRepositoryImpl, appWorkflowServiceImpl, pubSubClientServiceImpl, argoUserServiceImpl)
 	if err != nil {
 		return nil, err
 	}


Test patch:
diff --git a/pkg/user/UserFlows_test.go b/pkg/user/UserFlows_test.go
new file mode 100644
index 000000000..7dc889e79
--- /dev/null
+++ b/pkg/user/UserFlows_test.go
@@ -0,0 +1,79 @@
+package user
+
+import (
+	"fmt"
+	"github.com/devtron-labs/devtron/internal/util"
+	"github.com/devtron-labs/devtron/pkg/sql"
+	repository2 "github.com/devtron-labs/devtron/pkg/user/repository"
+	"log"
+	"testing"
+	"time"
+)
+
+const it = 100
+
+func BenchmarkCreateDefaultPoliciesForAllTypesV2(b *testing.B) {
+	config, err := sql.GetConfig()
+	if err != nil {
+		log.Fatal("error in sql config parsing")
+	}
+	logger, err := util.NewSugardLogger()
+	if err != nil {
+		log.Fatal("error in getting logger")
+	}
+	dbConnection, err := sql.NewDbConnection(config, logger)
+	userAuthRepository := repository2.NewUserAuthRepositoryImpl(dbConnection, logger, nil, nil)
+	userRepo := repository2.NewUserRepositoryImpl(dbConnection, logger)
+	defaultRbacPolicyRepo := repository2.NewRbacPolicyDataRepositoryImpl(logger, dbConnection)
+	defaultRbacRoleRepo := repository2.NewRbacRoleDataRepositoryImpl(logger, dbConnection)
+	defaultRbacCacheFactory := repository2.NewRbacDataCacheFactoryImpl(logger, defaultRbacPolicyRepo, defaultRbacRoleRepo)
+	userCommonService := NewUserCommonServiceImpl(userAuthRepository, logger, userRepo, nil, nil, defaultRbacCacheFactory)
+	teams := make(map[int]string, it)
+	apps := make(map[int]string, it)
+	envs := make(map[int]string, it)
+	for i := 0; i < it; i++ {
+		teams[i] = fmt.Sprintf("team-%d-%v", i, time.Now().Nanosecond())
+		apps[i] = fmt.Sprintf("app-%d-%v", i, time.Now().Nanosecond())
+		envs[i] = fmt.Sprintf("env-%d-%v", i, time.Now().Nanosecond())
+	}
+	entity := fmt.Sprintf("apps")
+	accessType := fmt.Sprintf("devtron-app")
+	action := fmt.Sprintf("manager")
+	b.Run(fmt.Sprintf("BenchmarkCreateDefaultPoliciesForAllTypesV2"), func(b *testing.B) {
+		for i := 0; i < b.N; i++ {
+			userCommonService.CreateDefaultPoliciesForAllTypesV2(teams[i], apps[i], envs[i], entity, "", "", "", "", "", action, accessType)
+		}
+	})
+}
+
+func BenchmarkCreateDefaultPoliciesForAllTypes(b *testing.B) {
+	config, err := sql.GetConfig()
+	if err != nil {
+		log.Fatal("error in sql config parsing")
+	}
+	logger, err := util.NewSugardLogger()
+	if err != nil {
+		log.Fatal("error in getting logger")
+	}
+	dbConnection, err := sql.NewDbConnection(config, logger)
+	defaultRoleRepo := repository2.NewDefaultAuthRoleRepositoryImpl(dbConnection, logger)
+	defaultPolicyRepo := repository2.NewDefaultAuthPolicyRepositoryImpl(dbConnection, logger)
+	userAuthRepository := repository2.NewUserAuthRepositoryImpl(dbConnection, logger, defaultPolicyRepo, defaultRoleRepo)
+	teams := make(map[int]string, it)
+	apps := make(map[int]string, it)
+	envs := make(map[int]string, it)
+	for i := 0; i < it; i++ {
+		teams[i] = fmt.Sprintf("team-%d-%v", i, time.Now().Nanosecond())
+		apps[i] = fmt.Sprintf("app-%d-%v", i, time.Now().Nanosecond())
+		envs[i] = fmt.Sprintf("env-%d-%v", i, time.Now().Nanosecond())
+	}
+	entity := fmt.Sprintf("apps")
+	accessType := fmt.Sprintf("devtron-app")
+	action := fmt.Sprintf("manager")
+	b.Run(fmt.Sprintf("BenchmarkCreateDefaultPoliciesForAllTypes"), func(b *testing.B) {
+		for i := 0; i < b.N; i++ {
+			userAuthRepository.CreateDefaultPoliciesForAllTypes(teams[i], apps[i], envs[i], entity, "", "", "", "", "", action, accessType, 1)
+		}
+	})
+
+}