docs icon indicating copy to clipboard operation
docs copied to clipboard

Create document explaining how to migrate identity schemas

Open aeneasr opened this issue 1 year ago • 0 comments

Preflight checklist

Describe your problem

The following code snippet allows users to udpate the identity schema in case they make changes to the schema:

package main

import (
	"context"
	"fmt"
	"github.com/sirupsen/logrus"
)
import "github.com/ory/client-go"

var YOUR_ORY_PAT = "...."
var YOUR_ORY_SDK_URL = "https://YOUR_PROJECT.projects.oryapis.com"
var UPDATE_TO_NEW_SCHEMA_ID = "f086edf7eb1d4e78731d4409303cdd173fab4b1e6ca79c09871290103d7c22072c252773792b29621f9ac272ced5ffa9ee63420a81f6dff6850c07a7cb26c2e4"
var IDENTITY_ID_TO_UPDATE = "3974b38c-6622-417a-a1c2-532b06f67264"

func main() {
	if err := migrateSchema(UPDATE_TO_NEW_SCHEMA_ID, IDENTITY_ID_TO_UPDATE); err != nil {
		panic(err)
	}
}

func migrateSchema(toSchema, identityID string) error {
	conf := client.NewConfiguration()
	conf.Servers = client.ServerConfigurations{
		{
			URL: YOUR_ORY_SDK_URL,
		},
	}
	oc := client.NewAPIClient(conf)

	ctx := context.Background()
	ctx = context.WithValue(ctx, client.ContextAccessToken, YOUR_PAT)

	// check if schema exists
	_, _, err := oc.V0alpha2Api.GetIdentitySchema(ctx, toSchema).Execute()
	if err != nil {
		logrus.Debug("error getting schema")
		return err
	}

	// check if identity exists
	identity, _, err := oc.V0alpha2Api.AdminGetIdentity(ctx, identityID).Execute()
	if err != nil {
		logrus.Debug("error getting identity")
		return err
	}
	if identity.SchemaId == toSchema {
		fmt.Println("already migrated, no update required")
		return nil
	}

	traits := identity.GetTraits().(map[string]interface{})
	body := client.NewAdminUpdateIdentityBody(toSchema, *identity.State, traits)

	updatedId, _, err := oc.V0alpha2Api.AdminUpdateIdentity(ctx, identityID).AdminUpdateIdentityBody(*body).Execute()
	if err != nil {
		logrus.Debug("error running update")
		return err
	}

	if updatedId.SchemaId != toSchema {
		return fmt.Errorf("schema wasn't updated")
	}

	fmt.Println("done")

	return nil
}

Describe your ideal solution

Rewrite the code above for better readability and write a document on how to migrate identity schemas in ory cloud

Workarounds or alternatives

None so far

Version

master

Additional Context

Pinging @vinckr because you were involved in this effort

aeneasr avatar Aug 24 '22 09:08 aeneasr