Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Restructures Admin Backend #40

Merged
merged 6 commits into from
Dec 14, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
162 changes: 162 additions & 0 deletions api/admin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
package api

import (
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"strings"

"github.com/gin-gonic/gin"
client "github.com/ory/client-go"

"github.com/sdslabs/nymeria/log"
"github.com/sdslabs/nymeria/pkg/wrapper/kratos/admin"
)

func HandleCreateIdentityFlow(c *gin.Context) {

var t admin.Identity

err := c.BindJSON(&t)

if err != nil {
log.ErrorLogger("Unable to process json body", err)

errCode, _ := strconv.Atoi(strings.Split(err.Error(), " ")[0])
c.JSON(errCode, gin.H{
"error": err.Error(),
"message": "Unable to process json body",
})
return
}

var mappedJsonIdentity map[string]interface{}

data, _ := json.Marshal(t)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

error handling

json.Unmarshal(data, &mappedJsonIdentity)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

error handling please


adminCreateIdentityBody := *client.NewAdminCreateIdentityBody(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move this to wrapper

"default",
mappedJsonIdentity,
) // AdminCreateIdentityBody | (optional)

createdIdentity, r, err := admin.CreateIdentityFlowWrapper(adminCreateIdentityBody)

if err != nil {
log.ErrorLogger("Error while calling `AdminCreateIdentity`", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "INternal server error",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'N' shouldn't be capital

})
return
}
c.JSON(http.StatusOK, gin.H{
"identity": createdIdentity.Id,
})
}

func HandleGetIdentityFlow(c *gin.Context) {
createdIdentity := c.Query("identity")
getIdentity, r, err := admin.GetIdentityFlowWrapper(createdIdentity)

if err != nil {
log.ErrorLogger("Error while calling `AdminGetIdentity`", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Internal server error",
})
return
}

jsonString, _ := json.Marshal(getIdentity.Traits)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

error handling


var identity admin.Identity

if err := json.Unmarshal(jsonString, &identity); err != nil {
fmt.Println(err)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use logger

}
fmt.Fprintf(os.Stdout, "Identity details for id %v. Traits: %v\n", createdIdentity, identity)
itsdarshankumar marked this conversation as resolved.
Show resolved Hide resolved
c.JSON(http.StatusOK, gin.H{
"Identity": createdIdentity,
"Traits": identity,
})
}

func HandleDeleteIdentityFlow(c *gin.Context) {

var t IdentityBody
err := c.BindJSON(&t)

if err != nil {
log.ErrorLogger("Unable to process json body", err)

errCode, _ := strconv.Atoi(strings.Split(err.Error(), " ")[0])
c.JSON(errCode, gin.H{
"error": err.Error(),
"message": "Unable to process json body",
})
return
}

r, err := admin.DeleteIdentityFlowWrapper(t.Identity)

if err != nil {
log.ErrorLogger("Error while calling `AdminDeleteIdentity`", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "INternal server error",
})
return
}
c.JSON(http.StatusOK, gin.H{
"message": "removed identity",
})
}

func HandleListIdentity(c *gin.Context) {
identities, r, err := admin.ListIdentityFlowWrapper()
if err != nil {
log.ErrorLogger("Error while calling `AdminListIdentities`", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Internal server error",
})

return
}
c.JSON(http.StatusOK, gin.H{
"identities": identities,
})
}

func HandleBanIdentity(c *gin.Context) {
var t IdentityBody
err := c.BindJSON(&t)

if err != nil {
log.ErrorLogger("Unable to process json body", err)

errCode, _ := strconv.Atoi(strings.Split(err.Error(), " ")[0])
c.JSON(errCode, gin.H{
"error": err.Error(),
"message": "Unable to process json body",
})
return
}

id, r, err := admin.BanIdentityFlowWrapper(t.Identity)

if err != nil {
log.ErrorLogger("Error while calling `AdminPatchIdentities`", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"identities": id,
})
}
2 changes: 1 addition & 1 deletion api/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (

func HandleGetLoginFlow(c *gin.Context) {
log.Logger.Debug("Get Login")
cookie, flowID, csrf_token, err := login.InitializeLoginFlowWrapper("aal1")
cookie, flowID, csrf_token, err := login.InitializeLoginFlowWrapper("aal1", "")

if err != nil {
log.ErrorLogger("Initialize Login Failed", err)
Expand Down
11 changes: 5 additions & 6 deletions api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"

c "github.com/sdslabs/nymeria/pkg/controller/admin"
"github.com/sdslabs/nymeria/pkg/middleware"
)

Expand Down Expand Up @@ -37,11 +36,11 @@ func Start() {
r.GET("/mfa", HandleGetMFAFlow)
r.POST("/mfa", HandlePostMFAFlow)

r.POST("/create-identity", c.CreateIdentity)
r.GET("/get-identity", c.GetIdentity)
r.POST("/delete-identity", c.DeleteIdentity)
r.GET("/list-identity", c.ListIdentity)
r.PUT("/update-identity/ban", c.UpdateBanIdentity)
r.POST("/create-identity", HandleCreateIdentityFlow)
r.GET("/get-identity", HandleGetIdentityFlow)
r.POST("/delete-identity", HandleDeleteIdentityFlow)
r.GET("/list-identity", HandleListIdentity)
r.PUT("/update-identity/ban", HandleBanIdentity)

r.GET("/register", HandleGetRegistrationFlow)
r.POST("/register", HandlePostRegistrationFlow)
Expand Down
9 changes: 7 additions & 2 deletions api/mfa.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package api

import (
"net/http"
"strings"

"github.com/gin-gonic/gin"

Expand All @@ -12,7 +13,8 @@ import (

func HandleGetMFAFlow(c *gin.Context) {
log.Logger.Debug("Get MFA")
flow_cookie, flowID, csrf_token, err := login.InitializeLoginFlowWrapper("aal2")
cookie, _ := c.Cookie("sdslabs_session")
flow_cookie, flowID, csrf_token, err := login.InitializeLoginFlowWrapper("aal2", cookie)

if err != nil {
log.ErrorLogger("Initialize MFA Failed", err)
Expand Down Expand Up @@ -51,8 +53,11 @@ func HandlePostMFAFlow(c *gin.Context) {
})
return
}
session_cookie, _ := c.Cookie("sdslabs_session")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

error handling

csrfToken := req_body.CsrfToken
cookie := strings.Split(flow_cookie, ";")[0] + "; " + strings.Split(session_cookie, ";")[0] + "; x-csrf-token=" + csrfToken

identity, session, err := login.SubmitLoginWithMFAWrapper(flow_cookie, req_body.FlowID, req_body.CsrfToken, req_body.TOTP)
identity, session, err := login.SubmitLoginWithMFAWrapper(cookie, req_body.FlowID, req_body.CsrfToken, req_body.TOTP)

if err != nil {
log.ErrorLogger("Kratos post MFA flow failed", err)
Expand Down
4 changes: 4 additions & 0 deletions api/types.go
Aryan51203 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,7 @@ type ApplicationPutBody struct {
type ApplicationBody struct {
ID int `json:"id"`
}

type IdentityBody struct {
Identity string `json:"identity"`
}
20 changes: 11 additions & 9 deletions config.sample.yaml
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
env: dev # dev|prod

url:
frontend_url: "http://localhost:4455"
kratos_url: "http://localhost:4433"
domain: "https://someaddress.com"
frontend_url: "http://localhost:4455"
kratos_url: "http://localhost:4433"
admin_kratos_url: "http://localhost:4434"

domain: "https://someaddress.com"

db:
dsn: ""
host: "localhost"
port: 5432
user: "postgres"
password: "pass"
db_name: "kratos_db"
dsn: ""
host: "localhost"
port: 5432
user: "postgres"
password: "pass"
db_name: "kratos_db"
14 changes: 13 additions & 1 deletion config/kratos.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,18 @@ func getKratosClientConfig() *client.Configuration {
return configuration
}

func getKratosClientConfigAdmin() *client.Configuration {
configuration := client.NewConfiguration()
configuration.Servers = []client.ServerConfiguration{
{
URL: NymeriaConfig.URL.AdminKratosURL,
},
}

return configuration
}

var (
KratosClientConfig = getKratosClientConfig()
KratosClientConfig = getKratosClientConfig()
KratosClientConfigAdmin = getKratosClientConfigAdmin()
)
7 changes: 4 additions & 3 deletions config/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ type NymeriaCfg struct {
DB DB `yaml:"db"`
}
type URL struct {
FrontendURL string `yaml:"frontend_url"`
KratosURL string `yaml:"kratos_url"`
Domain string `yaml:"domain"`
FrontendURL string `yaml:"frontend_url"`
KratosURL string `yaml:"kratos_url"`
AdminKratosURL string `yaml:"admin_kratos_url"`
Domain string `yaml:"domain"`
}

type DB struct {
Expand Down
58 changes: 58 additions & 0 deletions pkg/wrapper/kratos/admin/admin.go
Aryan51203 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package admin

import (
"context"
"net/http"

"github.com/ory/client-go"

"github.com/sdslabs/nymeria/config"
)

func CreateIdentityFlowWrapper(adminCreateIdentityBody client.AdminCreateIdentityBody) (*client.Identity, *http.Response, error) {
apiClient := client.NewAPIClient(config.KratosClientConfigAdmin)
createdIdentity, r, err := apiClient.V0alpha2Api.AdminCreateIdentity(context.Background()).AdminCreateIdentityBody(adminCreateIdentityBody).Execute()

return createdIdentity, r, err
}

func GetIdentityFlowWrapper(createdIdentity string) (*client.Identity, *http.Response, error) {
apiClient := client.NewAPIClient(config.KratosClientConfigAdmin)

getIdentity, r, err := apiClient.V0alpha2Api.AdminGetIdentity(context.Background(), createdIdentity).Execute()

return getIdentity, r, err
}

func DeleteIdentityFlowWrapper(identity string) (*http.Response, error) {
apiClient := client.NewAPIClient(config.KratosClientConfigAdmin)

r, err := apiClient.V0alpha2Api.AdminDeleteIdentity(context.Background(), identity).Execute()

return r, err
}

func ListIdentityFlowWrapper() ([]client.Identity, *http.Response, error) {
apiClient := client.NewAPIClient(config.KratosClientConfigAdmin)

identities, r, err := apiClient.V0alpha2Api.AdminListIdentities(context.Background()).Execute()

return identities, r, err

}

func BanIdentityFlowWrapper(identity string) (*client.Identity, *http.Response, error) {
apiClient := client.NewAPIClient(config.KratosClientConfigAdmin)

jsonPatch := []client.JsonPatch{
{
From: nil,
Op: "replace",
Path: "/active",
Value: false,
},
}
id, r, err := apiClient.V0alpha2Api.AdminPatchIdentity(context.Background(), identity).JsonPatch(jsonPatch).Execute()

return id, r, err
}
14 changes: 14 additions & 0 deletions pkg/wrapper/kratos/admin/types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package admin

type Identity struct {
Name string `json:"name"`
Email string `json:"email"`
Phone_number string `json:"phone_number"`
Password string `json:"password"`
Image_url string `json:"img_url"`
Active bool `json:"active"`
Verified bool `json:"verified"`
Role string `json:"role"`
Created_at string `json:"created_at"`
Totp_enabled bool `json:"totp_enabled"`
}
Loading