<@U04UQ68083H> when creating Ory identity with GO ...
# ory-copilot
w
@chilly-king-10285 when creating Ory identity with GO SDK how can I add metadata to the user?
c
A message from kapa.ai
When creating an identity using the Ory Go SDK, you can add metadata to the user by using the
metadata_public
and
metadata_admin
fields. The
metadata_public
field stores metadata about the identity which the identity itself can see. However, you should not store sensitive information in this field. The
metadata_admin
field is used to store metadata about the user which is only accessible through admin APIs. Here is an example of how you can set these fields:
Copy code
json {   identity: {       traits: {         email: claims.email       },       metadata_public: {         discord_username: claims.discord_username,       },       metadata_admin: {         // ...       },     }   }
In this example,
claims
is a variable that contains the data you want to add to the identity's metadata. You can replace
discord_username
and
claims.discord_username
with the actual metadata you want to add. Please note that metadata is not validated by Ory Identities, so missing entries or unexpected values can cause errors. You must ensure that the metadata you store is valid according to your schema and you must keep the schema up to date to accommodate changes in the data. For more information, you can refer to the [Ory documentation on managing identity metadata](https://www.ory.sh/docs/kratos/manage-identities/managing-users-identities-metadata). Please note that this is a JSON representation. The actual implementation in Go will depend on how you structure your Go code.
w
@chilly-king-10285 add metadata to this code: func (k *OryServiceImpl) CreateIdentity(email string, skipIfExisting bool) (*openapiclient.Identity, error) { ctx := context.Background() CreateIdentityBody := *openapiclient.NewCreateIdentityBody( "preset://email", map[string]interface{}{ "email": email, }, ) identity, response, err := k.client.IdentityAPI.CreateIdentity(ctx).CreateIdentityBody(CreateIdentityBody).Execute() if response.StatusCode == http.StatusConflict { if !skipIfExisting { return nil, fmt.Errorf("identity %s already exists. Skipping.\nFull HTTP response: %v", email, response) } return nil, nil } if err != nil { return nil, fmt.Errorf("error calling ProjectAPI.CreateIdentity: %v\nFull HTTP response: %v", err, response) } return identity, nil }
c
A message from kapa.ai
You can add metadata to the identity by adding
metadata_public
and
metadata_admin
fields to the
CreateIdentityBody
function. Here's how you can modify your code:
Copy code
go func (_k_ *OryServiceImpl) CreateIdentity(_email_ string, _skipIfExisting_ bool) (*openapiclient.Identity, error) {     ctx := context.Background()     CreateIdentityBody := *openapiclient.NewCreateIdentityBody(         "<preset://email>",         map[string]interface{}{             "email": email,             "metadata_public": map[string]interface{}{                 "key": "value", // replace with your actual metadata             },             "metadata_admin": map[string]interface{}{                 "key": "value", // replace with your actual metadata             },         },     )     identity, response, err := k.client.IdentityAPI.CreateIdentity(ctx).CreateIdentityBody(CreateIdentityBody).Execute()     if response.StatusCode == http.StatusConflict {         if !skipIfExisting {             return nil, fmt.Errorf("identity %s already exists. Skipping.\nFull HTTP response: %v", email, response)         }         return nil, nil     }     if err != nil {         return nil, fmt.Errorf("error calling ProjectAPI.CreateIdentity: %v\nFull HTTP response: %v", err, response)     }     return identity, nil }
In this example, replace
"key": "value"
with the actual metadata you want to add. The
metadata_public
field is visible to the identity, while the
metadata_admin
field is only accessible through admin APIs. Please note that metadata is not validated by Ory Identities, so missing entries or unexpected values can cause errors. You must ensure that the metadata you store is valid according to your schema and you must keep the schema up to date to accommodate changes in the data. For more information, you can refer to the [Ory documentation on managing identity metadata](https://www.ory.sh/docs/kratos/manage-identities/managing-users-identities-metadata).
w
@chilly-king-10285 I get this error: {{\"error\":{\"code\":400,\"status\":\"Bad Request\",\"request\":\"41ec255a-8500-99fe-b7ef-437cf9e3c039\",\"reason\":\"I[#/traits] S[#/properties/traits/additionalProperties] additionalProperties \\\"metadata_admin\\\", \\\"metadata_public\\\" not allowed\",\"message\":\"The request was malformed or contained invalid parameters\"}}\n} 305 [] false false map[] 0x1400028ea20 0x1400030e0b0}"}
c
A message from kapa.ai
The error message you're seeing indicates that the
metadata_public
and
metadata_admin
fields are not allowed in the
traits
section of the identity schema. In Ory, the
traits
field is used for attributes of an identity that can be updated by the identity owner, such as username or email address. The
metadata_public
and
metadata_admin
fields are not part of the
traits
and should be added at the same level as
traits
. Here's how you should structure your `CreateIdentityBody`:
Copy code
go CreateIdentityBody := *openapiclient.NewCreateIdentityBody(     "<preset://email>",     map[string]interface{}{         "traits": map[string]interface{}{             "email": email,         },         "metadata_public": map[string]interface{}{             "key": "value", // replace with your actual metadata         },         "metadata_admin": map[string]interface{}{             "key": "value", // replace with your actual metadata         },     }, )
In this example, replace
"key": "value"
with the actual metadata you want to add. The
metadata_public
field is visible to the identity, while the
metadata_admin
field is only accessible through admin APIs. For more information, you can refer to the [Ory documentation on managing identity metadata](https://www.ory.sh/docs/kratos/manage-identities/managing-users-identities-metadata).
w
@chilly-king-10285 can you add it to this identity schema please? { "$id": "https://schemas.ory.sh/presets/kratos/identity.email.schema.json", "$schema": "http://json-schema.org/draft-07/schema#", "title": "Person", "type": "object", "properties": { "traits": { "type": "object", "properties": { "email": { "type": "string", "format": "email", "title": "E-Mail", "ory.sh/kratos": { "credentials": { "password": { "identifier": true }, "webauthn": { "identifier": true }, "totp": { "account_name": true }, "code": { "identifier": true, "via": "email" } }, "recovery": { "via": "email" }, "verification": { "via": "email" } }, "maxLength": 320 } }, "required": [ "email" ], "additionalProperties": false } } }
c
A message from kapa.ai
The identity schema you provided is used to define the structure of the
traits
field for an identity. The
metadata_public
and
metadata_admin
fields are not part of the identity schema, but are added when creating or updating an identity using the Ory API or SDKs. However, if you want to include metadata fields in your schema for documentation or reference purposes, you can add them at the same level as
traits
. Here's how you can modify your schema:
Copy code
json {   "$id": "<https://schemas.ory.sh/presets/kratos/identity.email.schema.json>",   "$schema": "<http://json-schema.org/draft-07/schema#>",   "title": "Person",   "type": "object",   "properties": {     "traits": {       "type": "object",       "properties": {         "email": {           "type": "string",           "format": "email",           "title": "E-Mail",           "<http://ory.sh/kratos|ory.sh/kratos>": {             "credentials": {               "password": {                 "identifier": true               },               "webauthn": {                 "identifier": true               },               "totp": {                 "account_name": true               },               "code": {                 "identifier": true,                 "via": "email"               }             },             "recovery": {               "via": "email"             },             "verification": {               "via": "email"             }           },           "maxLength": 320         }       },       "required": [         "email"       ],       "additionalProperties": false     },     "metadata_public": {       "description": "Store metadata about the identity which the identity itself can see when calling for example the session endpoint. Do not store sensitive information (e.g. credit score) about the identity in this field.",       "type": "object"     },     "metadata_admin": {       "description": "Store metadata about the user which is only accessible through admin APIs such as `GET /admin/identities/<id>`.",       "type": "object"     }   } }
Please note that this modification is for documentation or reference purposes only. The actual
metadata_public
and
metadata_admin
fields are not validated against the schema and can contain any valid JSON data. For more information, you can refer to the [Ory documentation on managing identity metadata](https://www.ory.sh/docs/kratos/manage-identities/managing-users-identities-metadata).
w
@chilly-king-10285 how to disable account experience in ory project?
c
A message from kapa.ai
To disable the Account Experience in an Ory project, you need to define a custom UI base URL. When you define a custom UI base URL, you lose access to the Ory Account Experience. The custom UI base URL takes precedence over the SDK Configuration URL. Here are the steps to set the base URL of custom UI and define the paths for UI views: 1. Go to BrandingUI URLs in the [Ory Console](https://console.ory.sh/projects/current/ui). Please note that all paid Ory Network plans allow you to add a custom domain to your project. After adding a custom domain, you can also set up a base URL of all custom UI views. This is a great way to make Ory work with your existing deployment without adjustments, as you can use the combination of the base URL and relative URLs to point Ory to UI screens for operations such as login or registration you are already hosting. You can also toggle the "Enable the Account Experience welcome page" setting to hide the default "welcome" screen that isn't intended for end-users. For more information, you can refer to the [Ory documentation on configuring Ory to use your UI](https://www.ory.sh/docs/kratos/bring-your-own-ui/configure-ory-to-use-your-ui#custom-domain-setup).
w
@chilly-king-10285 how can I allow only password setup in recovery link?
c
A message from kapa.ai
To allow only password setup in the recovery link, you need to configure the recovery flow in the Ory Kratos configuration file. In the recovery flow configuration, you can specify the
after_recovery
hook to
revoke_active_sessions
. This forces anyone with access to the account to re-authenticate using the new password set up in the recovery process. Here's an example of how to set this up:
Copy code
yaml selfservice:   flows:     recovery:       enabled: true       ui_url: <http://your.ui/recovery>       after:         hooks:         - hook: revoke_active_sessions
In this configuration, replace
<http://your.ui/recovery>
with the URL of your recovery page. Please note that this configuration does not prevent the user from connecting to a social sign-in provider after recovering their account. If you want to disable social sign-in completely, you need to remove the social sign-in providers from the Ory Kratos configuration file. For more information, you can refer to the [Ory documentation on account recovery](https://www.ory.sh/docs/kratos/self-service/flows/account-recovery-password-reset#invalidate-other-sessions) and [configuring hooks for self-service user flows](https://www.ory.sh/docs/kratos/hooks/configure-hooks).
w
@chilly-king-10285 when I trigger account recovery and clink on recovety link I can see "Profile Settings" with e-mail I only want to see password field
c
A message from kapa.ai
To only show the password field during the account recovery process, you need to customize the recovery user interface. In Ory Kratos, the recovery user interface is defined by a JSON document that describes the form elements to render and actions the form should take upon submission, cancellation, etc. You can customize this JSON document to only include the password field. Here's an example of how to do this:
Copy code
tsx const mapUINode = (node: UiNode, key: number) => {   if (isUiNodeInputAttributes(node.attributes)) {     const attrs = node.attributes as UiNodeInputAttributes     const nodeType = attrs.type      if (nodeType === "password") {       return (         <input           name={attrs.name}           type={attrs.type}           autoComplete={attrs.autocomplete}         />       )     }   } }
In this example, the
mapUINode
function only renders an input field if the type of the field is "password". You can use this function to map over the nodes in the recovery flow and only render the password field. Please note that this is a simplified example and the actual implementation will depend on your specific use case and the framework you're using. For more information, you can refer to the [Ory documentation on customizing the user interface](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration#get-recovery-flow).
w
@chilly-king-10285 Can I update idenitity with username after they are created?
c
A message from kapa.ai
Yes, you can update an identity's traits, which can include the username, after they are created. This can be done using the
PUT /admin/identities/{id}
endpoint of the Ory Kratos Admin API. Here's an example of how to do this:
Copy code
json PUT /admin/identities/{id} {   "traits": {     "username": "new_username"   } }
In this example, replace
{id}
with the ID of the identity you want to update, and
"new_username"
with the new username. Please note that the updated traits must be valid against the Identity Schema defined for its identity traits. For more information, you can refer to the [Ory documentation on updating an identity](https://www.ory.sh/docs/reference/api#operation/updateIdentity) and [managing identity metadata and traits](https://www.ory.sh/docs/kratos/manage-identities/managing-users-identities-metadata).
w
@chilly-king-10285 change this code to update the trais:
Copy code
func (k *OryServiceImpl) CreateIdentity(email string, schemaId string, skipIfExisting bool) (*openapiclient.Identity, error) {
	ctx := context.Background()
	CreateIdentityBody := *openapiclient.NewCreateIdentityBody(
		schemaId,
		map[string]interface{}{
			"email": email,
		},
	)
	identity, response, err := k.client.IdentityAPI.CreateIdentity(ctx).CreateIdentityBody(CreateIdentityBody).Execute()
	if response.StatusCode == 409 {
		if !skipIfExisting {
			return nil, fmt.Errorf("identity %s already exists. Skipping.\nFull HTTP response: %v", email, response)
		}
		return nil, nil
	}
	if err != nil {
		return nil, fmt.Errorf("error calling ProjectAPI.CreateIdentity: %v\nFull HTTP response: %v", err, response)
	}
	return identity, nil
}
c
A message from kapa.ai
To update the traits of an identity, you can use the
UpdateIdentity
method of the Ory Kratos Admin API. Here's how you can modify your function to update an identity:
Copy code
go func (k *OryServiceImpl) UpdateIdentityTraits(id string, email string) (*openapiclient.Identity, error) {  ctx := context.Background()  UpdateIdentityBody := *openapiclient.NewUpdateIdentityBody(   map[string]interface{}{    "email": email,   },  )  identity, response, err := k.client.IdentityAPI.UpdateIdentity(ctx, id).UpdateIdentityBody(UpdateIdentityBody).Execute()  if err != nil {   return nil, fmt.Errorf("error calling IdentityAPI.UpdateIdentity: %v\nFull HTTP response: %v", err, response)  }  return identity, nil }
In this example, replace
id
with the ID of the identity you want to update, and
email
with the new email. Please note that the updated traits must be valid against the Identity Schema defined for its identity traits. For more information, you can refer to the [Ory documentation on updating an identity](https://www.ory.sh/docs/reference/api#operation/updateIdentity) and [managing identity metadata and traits](https://www.ory.sh/docs/kratos/manage-identities/managing-users-identities-metadata).
w
@chilly-king-10285 Updating identity dd269776-cc75-4a9b-b05a-0af9ee0d0e3a 8958afec7251099e327ff4872d5008ee0b743ae44bd85bd177c049853c91d6855b71d108cfb60b41f902b78e077d52cf0d0fb71741cd6cbf0573871e0aa13426 Pavel panic: error calling ProjectAPI.CreateIdentity: 400 Bad Request Full HTTP response: &{400 Bad Request 400 HTTP/2.0 2 0 map[Alt-Svc:[h3=":443"; ma=86400] Cache-Control:[private, no-cache, no-store, must-revalidate] Cf-Cache-Status:[DYNAMIC] Cf-Ray:[8af87b7b8cdb068a-LHR] Content-Length:[250] Content-Type:[application/json] Date:[Wed, 07 Aug 2024 160055 GMT] Ory-Network-Ingress:[T] Ory-Network-Region:[euw] Permissions-Policy:[accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), usb=()] Referrer-Policy:[strict-origin-when-cross-origin] Server:[cloudflare] Set-Cookie:[__cf_bm=z5.p11J75GFXDUX1YLpQvGc7GQFOU6lyMjzhDZ69Qm0-1723046455-1.0.1.1-ST7X.qrSEOwrTQpkDb1Stv8OIEMeATC0uztWVAHNbrKgx8h3EZmAU8XtRB_sR_mcFMuMPB18vxJFnNEr1Z4ajQ; path=/; expires=Wed, 07-Aug-24 163055 GMT; domain=.oryapis.com; HttpOnly; Secure __cflb=04dTofjtHwhfCny3TibYMM4LURzprwaV4YZYYngnHZ; SameSite=None; Secure; path=/; expires=Wed, 07-Aug-24 170055 GMT; HttpOnly _cfuvid=XVpycbA7soVzbxDIXN8FmV08_ZVUAZVBvogdXbXeTj0-1723046455729-0.0.1.1-604800000; path=/; domain=.oryapis.com; HttpOnly; Secure; SameSite=None] Vary:[Origin] Via:[1.1 google] X-Content-Type-Options:[nosniff] X-Frame-Options:[DENY] X-Ratelimit-Limit:[10, 10;w=1, 300;w=60, 500;w=1] X-Ratelimit-Remaining:[9] X-Ratelimit-Reset:[1]] {{"error":{"code":400,"status":"Bad Request","request":"f02e4c11-409b-92d6-912b-d3d985f05669","reason":"I[#/traits] S[#/properties/traits/required] missing properties: \"email\"","message":"The request was malformed or contained invalid parameters"}} } 250 [] false false map[] 0x140001d8a20 0x140000e20b0}
c
A message from kapa.ai
The error message indicates that the request to update the identity is missing the required "email" property in the "traits" object. In the Ory Kratos system, the "traits" object is used to store the attributes of an identity, such as the username or email address. These traits are defined by a JSON Schema, and the request to update an identity must include all required properties defined in this schema. Here's how you can modify your function to include the "email" property:
Copy code
go func (k *OryServiceImpl) UpdateIdentityTraits(id string, email string, username string) (*openapiclient.Identity, error) {  ctx := context.Background()  UpdateIdentityBody := *openapiclient.NewUpdateIdentityBody(   map[string]interface{}{    "email": email,    "username": username,   },  )  identity, response, err := k.client.IdentityAPI.UpdateIdentity(ctx, id).UpdateIdentityBody(UpdateIdentityBody).Execute()  if err != nil {   return nil, fmt.Errorf("error calling IdentityAPI.UpdateIdentity: %v\nFull HTTP response: %v", err, response)  }  return identity, nil }
In this example, replace
id
with the ID of the identity you want to update,
email
with the new email, and
username
with the new username. Please note that the updated traits must be valid against the Identity Schema defined for its identity traits. For more information, you can refer to the [Ory documentation on updating an identity](https://www.ory.sh/docs/reference/api#operation/updateIdentity) and [managing identity metadata and traits](https://www.ory.sh/docs/kratos/manage-identities/managing-users-identities-metadata).
w
@chilly-king-10285 how can I create identity with _metadata_admin using go cli?_
c
A message from kapa.ai
To create an identity with
_metadata_admin
using the Go client, you need to use the
CreateIdentity
method of the Ory Kratos Admin API. The
_metadata_admin
field is used to store metadata about the user which is only accessible through admin APIs. Here's an example of how to do this:
Copy code
go func (k *OryServiceImpl) CreateIdentityWithAdminMetadata(email string, schemaId string, adminMetadata map[string]interface{}, skipIfExisting bool) (*openapiclient.Identity, error) {  ctx := context.Background()  CreateIdentityBody := *openapiclient.NewCreateIdentityBody(   schemaId,   map[string]interface{}{    "email": email,   },  )  CreateIdentityBody.SetMetadataAdmin(adminMetadata)  identity, response, err := k.client.IdentityAPI.CreateIdentity(ctx).CreateIdentityBody(CreateIdentityBody).Execute()  if response.StatusCode == 409 {   if !skipIfExisting {    return nil, fmt.Errorf("identity %s already exists. Skipping.\nFull HTTP response: %v", email, response)   }   return nil, nil  }  if err != nil {   return nil, fmt.Errorf("error calling ProjectAPI.CreateIdentity: %v\nFull HTTP response: %v", err, response)  }  return identity, nil }
In this example, replace
email
with the email of the identity you want to create,
schemaId
with the ID of the JSON Schema to be used for validating the identity's traits, and
adminMetadata
with the metadata you want to store. Please note that the created identity must be valid against the Identity Schema defined for its identity traits. For more information, you can refer to the [Ory documentation on creating an identity](https://www.ory.sh/docs/reference/api#operation/createIdentity) and [managing identity metadata and traits](https://www.ory.sh/docs/kratos/manage-identities/managing-users-identities-metadata).
w
@chilly-king-10285 how to make MFA required in ory project that would force users to set it up?
c
A message from kapa.ai
To enforce Multi-Factor Authentication (MFA) in an Ory project, you need to adjust the configuration file (
config.yml
). Here's an example of how to set this up:
Copy code
yaml selfservice:     flows:       settings:         required_aal: highest_available   session:     whoami:       required_aal: highest_available
In this configuration,
required_aal: highest_available
forces users to provide the highest authentication factor to access their account settings. For example, users without a second factor configured can access the settings after they sign in with their password. Users that have a second factor set up (such as a TOTP app) will must complete the second factor challenge to access account settings. If you want all users that configured a second factor to complete the factor before using your app, set
session.whoami.required_aal
to
highest_available
. For more information, you can refer to the [Ory documentation on enforcing MFA](https://www.ory.sh/docs/kratos/self-hosted/mfa#enforce-mfa).
w
@chilly-king-10285 how to apply ory config on project?
c
A message from kapa.ai
To apply a configuration to an Ory project, you can use the Ory CLI's
ory update
command. This command allows you to overwrite or import a configuration from a file. Here's an example of how to use this command:
Copy code
bash ory update project --project <project-id> --workspace <workspace-id> --file config.json
In this command, replace
<project-id>
with the ID of your project,
<workspace-id>
with the ID of your workspace, and
config.json
with the path to your configuration file. You can also use the
ory patch
command to adjust specific keys in the configuration:
Copy code
bash ory patch permission-config --project <project-id> --workspace <workspace-id> --replace '/limit/max_read_depth=3'
In this command, replace
<project-id>
with the ID of your project,
<workspace-id>
with the ID of your workspace, and
/limit/max_read_depth=3
with the key and value you want to adjust. For more information, you can refer to the [Ory documentation on configuring projects with the Ory CLI](https://www.ory.sh/docs/guides/cli/config-with-cli) and [adjusting specific keys in the configuration](https://www.ory.sh/docs/guides/cli/configure-permission-service#adjust-specific-keys).