Problem with understanding the ORY Kratos golang SDK

Viewed 165

So I am writing an API for registering/logging in/logging out users

I use following package https://github.com/ory/client-go for this

The code below should register the user

var newIdentity models.NewIdentity
err := fctx.BodyParser(&newIdentity) // request body to struct
if err != nil {
    c.Log.Error("Error occurred during unmarshalling. Error: %s", err.Error())
    return err
}
adminCreateIdentityBody := *ory.NewAdminCreateIdentityBody(
    "default",
    map[string]interface{}{
        "email": newIdentity.Email,
        // I think that somewhere here I should insert a password, but it doesn't work
        "name": map[string]string{
            "first": newIdentity.Name.First,
            "last":  newIdentity.Name.Last,
        },
    })

createdIdentity, resp, err := c.OryAdminApiClient.V0alpha2Api.AdminCreateIdentity(context.Background()).AdminCreateIdentityBody(adminCreateIdentityBody).Execute()

The problem is that I don't quite understand how I can get the session to the client for the user I'm creating

I also could not find how to write down the password for the user being created in adminCreateIdentityBody

1 Answers

This won't answer all of your questions but I figured out how to create users on the backend. I'm using Gin for web routing so if you're not that are some parts that might be different. Also this code is a bit dirty but it does set the password sent from a simple HTML post form:

import (
    /* your other imports here */
    kratosclient "github.com/ory/kratos-client-go"
)

func Route(dsn string) {
    router := gin.Default()

    router.POST("/signup", func(c *gin.Context) {
        log.Println("Sign up!")

        var signupRequest SignupRequest
        error := c.Bind(&signupRequest)

        if error != nil {
            // Required parameter wasn't there; client error.
            // status = http.StatusBadRequest
            // response = ErrorResponse()
            log.Println("Parameter error - ", error)
            return
        }

        configuration := kratosclient.NewConfiguration()
        configuration.Servers = []kratosclient.ServerConfiguration{
            {
                URL: "http://host.docker.internal:4434", // Kratos Admin API - when running Kratos container on "same machine/host/localhost", as this app
                // URL: "http://127.0.0.1:4434", // Kratos Admin API
            },
        }
        apiClient := kratosclient.NewAPIClient(configuration)

        // Set password
        myPw := *kratosclient.NewAdminCreateIdentityImportCredentialsPassword()
        myConfig := kratosclient.AdminCreateIdentityImportCredentialsPasswordConfig{}
        myPw.SetConfig(myConfig)
        myPw.Config.SetPassword(signupRequest.Password)
        adminCreateIdentityBody := *kratosclient.NewAdminCreateIdentityBody(
            "default",
            map[string]interface{}{
                "email": signupRequest.Email,
                "name": map[string]string{
                    "first": "foo",
                    "last":  "bar",
                },
            },
        )
        myCredentials := kratosclient.AdminIdentityImportCredentials{}
        myCredentials.SetPassword(myPw)
        adminCreateIdentityBody.SetCredentials(myCredentials)

        createdIdentity, r, err := apiClient.V0alpha2Api.AdminCreateIdentity(context.Background()).AdminCreateIdentityBody(adminCreateIdentityBody).Execute()
        if err != nil {
            fmt.Fprintf(os.Stderr, "Error when calling `V0alpha2Api.AdminCreateIdentity``: %v\n", err)
            fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
        }
        // response from `AdminCreateIdentity`: Identity
        fmt.Fprintf(os.Stdout, "Created identity with ID: %v\n", createdIdentity.Id)
        getIdentity, r, err := apiClient.V0alpha2Api.AdminGetIdentity(context.Background(), createdIdentity.Id).Execute()
        if err != nil {
            fmt.Fprintf(os.Stderr, "Error when calling `V0alpha2Api.AdminGetIdentity``: %v\n", err)
            fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
        }
        fmt.Fprintf(os.Stdout, "Email for identity with id %v. Traits %v\n", createdIdentity.Id, getIdentity.Traits)

        c.HTML(http.StatusOK, "signupdone.tmpl", gin.H{
            "email": signupRequest.Email,
        })

        // We could delete the identity like below:
        // r, err = apiClient.V0alpha2Api.AdminDeleteIdentity(context.Background(), getIdentity.Id).Execute()
        // if err != nil {
        //  fmt.Fprintf(os.Stderr, "Error when calling `V0alpha2Api.AdminDeleteIdentity``: %v\n", err)
        //  fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
        // }
        // fmt.Println("Successfully Removed identity")
    })
}

type SignupRequest struct {
    Email    string `form:"email" binding:"required"`
    Password string `form:"pw" binding:"required"`
}

I've barely just touched Go yet so there might be some better ways of formulating things, but this does work, on my container ‍.

Related