From c80f7920b65d8a6f9a040e24c9de84bb56bc02ac Mon Sep 17 00:00:00 2001 From: vrag99 Date: Sat, 23 Dec 2023 15:50:33 +0530 Subject: [PATCH] implement rbac on test route --- api/rbac.go | 45 ++++++++++++++++++++++++++++++++++++++++++++- config/keto.go | 4 +++- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/api/rbac.go b/api/rbac.go index facb153..39824cc 100644 --- a/api/rbac.go +++ b/api/rbac.go @@ -1,7 +1,10 @@ package api import ( + "bytes" "context" + "encoding/json" + "io" "net/http" "strconv" "strings" @@ -12,6 +15,26 @@ import ( "github.com/sdslabs/nymeria/log" ) +func getResponse(method string, endpoint string, query *bytes.Buffer) (string, error) { + req, _ := http.NewRequest(method, endpoint, query) + req.Header.Set("Content-Type", "application/json") + + client := http.Client{} + res, err := client.Do(req) + + if err != nil { + return "", err + } + defer res.Body.Close() + + body, err := io.ReadAll(res.Body) + if err != nil { + return "", err + } + + return string(body), nil +} + func HandleRbac(c *gin.Context) { log.Logger.Debug("RBAC") cookie, err := c.Cookie("sdslabs_session") @@ -41,9 +64,29 @@ func HandleRbac(c *gin.Context) { traits := identity.GetTraits() role := traits.(map[string]interface{})["role"] + queryRelationEndpoint := config.KetoReadURL + "/relation-tuples" + query, _ := json.Marshal(map[string]interface{}{ + "namespace": "accounts", + "relation": "view", + "subject_id": role, + }) + + jsonQuery := bytes.NewBuffer(query) + + res, err := getResponse("GET", queryRelationEndpoint, jsonQuery) + + if err != nil { + log.ErrorLogger("Failed to query keto", err) + c.JSON(http.StatusInternalServerError, gin.H{ + "error": err.Error(), + "message": "Initialize Rbac failed.", + }) + return + } + c.JSON(http.StatusOK, gin.H{ "message": "RBAC passed", - "traits": traits, "role": role, + "res": res, }) } diff --git a/config/keto.go b/config/keto.go index e96031a..c86361a 100644 --- a/config/keto.go +++ b/config/keto.go @@ -4,7 +4,7 @@ import ( client "github.com/ory/client-go" ) -func getKetoClientConfig() (*client.Configuration, *client.Configuration){ +func getKetoClientConfig() (*client.Configuration, *client.Configuration) { readConfiguration := client.NewConfiguration() readConfiguration.Servers = []client.ServerConfiguration{ { @@ -24,4 +24,6 @@ func getKetoClientConfig() (*client.Configuration, *client.Configuration){ var ( KetoReadConfig, KetoWriteConfig = getKetoClientConfig() + KetoReadURL = NymeriaConfig.URL.KetoReadURL + KetoWriteURL = NymeriaConfig.URL.KetoWriteURL )