Module: BetterAuth::Plugins
- Defined in:
- lib/better_auth/scim/utils.rb,
lib/better_auth/scim/client.rb,
lib/better_auth/scim/routes.rb,
lib/better_auth/plugins/scim.rb,
lib/better_auth/scim/mappings.rb,
lib/better_auth/scim/scim_error.rb,
lib/better_auth/scim/validation.rb,
lib/better_auth/scim/middlewares.rb,
lib/better_auth/scim/scim_tokens.rb,
lib/better_auth/scim/scim_filters.rb,
lib/better_auth/scim/user_schemas.rb,
lib/better_auth/scim/scim_metadata.rb,
lib/better_auth/scim/scim_resources.rb,
lib/better_auth/scim/patch_operations.rb,
lib/better_auth/scim/provider_management.rb
Constant Summary collapse
- SCIM_MAX_PATCH_OPERATIONS =
100- SCIM_MAX_PATCH_VALUE_DEPTH =
5- SCIM_ERROR_SCHEMA =
"urn:ietf:params:scim:api:messages:2.0:Error"- SCIM_LIST_RESPONSE_SCHEMA =
"urn:ietf:params:scim:api:messages:2.0:ListResponse"- SCIM_USER_SCHEMA_ID =
"urn:ietf:params:scim:schemas:core:2.0:User"- SCIM_SUPPORTED_MEDIA_TYPES =
["application/json", "application/scim+json"].freeze
Class Method Summary collapse
- .scim(options = {}) ⇒ Object
- .scim_account_id(body) ⇒ Object
- .scim_apply_patch_path!(user, update, account_update, path, value, operation_name) ⇒ Object
- .scim_apply_patch_value!(user, update, account_update, value, operation_name, path = nil) ⇒ Object
- .scim_assert_provider_access!(ctx, user_id, provider, required_roles, config = {}) ⇒ Object
- .scim_auth_middleware(config) ⇒ Object
- .scim_call_token_hook(callback, payload) ⇒ Object
- .scim_client ⇒ Object
- .scim_create_org_membership(ctx, user_id, organization_id) ⇒ Object
- .scim_create_user_endpoint(config) ⇒ Object
- .scim_decode_token(encoded) ⇒ Object
- .scim_default_provider(config, provider_id, organization_id) ⇒ Object
- .scim_delete_provider_connection_endpoint(config) ⇒ Object
- .scim_delete_provider_openapi_metadata ⇒ Object
- .scim_delete_user_endpoint(config) ⇒ Object
- .scim_display_name(body, fallback = nil) ⇒ Object
- .scim_error(status, detail, scim_type: nil) ⇒ Object
- .scim_family_name(name) ⇒ Object
- .scim_find_organization_member(ctx, user_id, organization_id) ⇒ Object
- .scim_find_user_with_account!(ctx) ⇒ Object
- .scim_full_name(fallback, given_name:, family_name:) ⇒ Object
- .scim_generate_token_endpoint(config) ⇒ Object
- .scim_generate_token_openapi_metadata ⇒ Object
- .scim_get_provider_connection_endpoint(config) ⇒ Object
- .scim_get_user_endpoint(config) ⇒ Object
- .scim_given_name(name) ⇒ Object
- .scim_has_organization_plugin?(ctx) ⇒ Boolean
- .scim_has_required_role?(role, required_roles) ⇒ Boolean
- .scim_hidden_metadata(summary, allowed_media_types) ⇒ Object
- .scim_list_pagination(query) ⇒ Object
- .scim_list_provider_connections_endpoint(config) ⇒ Object
- .scim_list_users_endpoint(config) ⇒ Object
- .scim_non_negative_integer(value, fallback) ⇒ Object
- .scim_normalized_provider(provider) ⇒ Object
- .scim_openapi_metadata(summary) ⇒ Object
- .scim_openapi_responses ⇒ Object
- .scim_organization_plugin(ctx) ⇒ Object
- .scim_param(ctx, key) ⇒ Object
- .scim_parse_filter(filter) ⇒ Object
- .scim_parse_roles(role) ⇒ Object
- .scim_patch_should_apply?(current_value, new_value, operation_name) ⇒ Boolean
- .scim_patch_user_endpoint(config) ⇒ Object
- .scim_patch_validation_error(message) ⇒ Object
- .scim_positive_integer(value, fallback) ⇒ Object
- .scim_primary_email(body) ⇒ Object
- .scim_provider_by_provider_id!(ctx, provider_id) ⇒ Object
- .scim_provider_id_query(ctx) ⇒ Object
- .scim_provider_ownership_enabled?(config) ⇒ Boolean
- .scim_required_roles(ctx, config) ⇒ Object
- .scim_resource_type_endpoint ⇒ Object
- .scim_resource_types_endpoint ⇒ Object
- .scim_resource_url(base_url, path) ⇒ Object
- .scim_schema(config = {}) ⇒ Object
- .scim_schema_endpoint ⇒ Object
- .scim_schemas_endpoint ⇒ Object
- .scim_service_provider_config_endpoint ⇒ Object
- .scim_store_token(ctx, config, token) ⇒ Object
- .scim_token_matches?(ctx, config, token, stored) ⇒ Boolean
- .scim_token_string_matches?(expected, provided) ⇒ Boolean
- .scim_update_user_endpoint(config) ⇒ Object
- .scim_user_org_memberships(ctx, user_id) ⇒ Object
- .scim_user_resource(user, account = nil, base_url = nil) ⇒ Object
- .scim_user_resource_type(base_url = nil) ⇒ Object
- .scim_user_schema(base_url = nil) ⇒ Object
- .scim_user_update(body) ⇒ Object
- .scim_validate_patch_body!(body) ⇒ Object
- .scim_validate_patch_value_depth!(value, depth = 0) ⇒ Object
- .scim_validate_user_body!(body) ⇒ Object
Class Method Details
.scim(options = {}) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/better_auth/plugins/scim.rb', line 26 def scim( = {}) config = {store_scim_token: "hashed", provider_ownership: {enabled: true}}.merge(normalize_hash()) Plugin.new( id: "scim", version: BetterAuth::SCIM::VERSION, client: scim_client, schema: scim_schema(config), endpoints: { generate_scim_token: scim_generate_token_endpoint(config), list_scim_provider_connections: scim_list_provider_connections_endpoint(config), get_scim_provider_connection: scim_get_provider_connection_endpoint(config), delete_scim_provider_connection: scim_delete_provider_connection_endpoint(config), create_scim_user: scim_create_user_endpoint(config), update_scim_user: scim_update_user_endpoint(config), patch_scim_user: scim_patch_user_endpoint(config), delete_scim_user: scim_delete_user_endpoint(config), list_scim_users: scim_list_users_endpoint(config), get_scim_user: scim_get_user_endpoint(config), get_scim_service_provider_config: scim_service_provider_config_endpoint, get_scim_schemas: scim_schemas_endpoint, get_scim_schema: scim_schema_endpoint, get_scim_resource_types: scim_resource_types_endpoint, get_scim_resource_type: scim_resource_type_endpoint }, options: config ) end |
.scim_account_id(body) ⇒ Object
23 24 25 |
# File 'lib/better_auth/scim/mappings.rb', line 23 def scim_account_id(body) body[:external_id] || body[:user_name].to_s.downcase end |
.scim_apply_patch_path!(user, update, account_update, path, value, operation_name) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/better_auth/scim/patch_operations.rb', line 19 def scim_apply_patch_path!(user, update, account_update, path, value, operation_name) remove = operation_name == "remove" normalized = "/" + path.to_s.sub(%r{\A/+}, "").tr(".", "/") case normalized when "/userName" new_value = value.to_s.downcase update[:email] = new_value if scim_patch_should_apply?(user["email"], new_value, operation_name) when "/externalId" account_update[:accountId] = value unless remove when "/name/formatted" update[:name] = value if scim_patch_should_apply?(user["name"], value, operation_name) when "/name/givenName" new_value = scim_full_name(user.fetch("email"), given_name: value, family_name: scim_family_name(update[:name] || user["name"])) update[:name] = new_value if scim_patch_should_apply?(user["name"], new_value, operation_name) when "/name/familyName" new_value = scim_full_name(user.fetch("email"), given_name: scim_given_name(update[:name] || user["name"]), family_name: value) update[:name] = new_value if scim_patch_should_apply?(user["name"], new_value, operation_name) end end |
.scim_apply_patch_value!(user, update, account_update, value, operation_name, path = nil) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 |
# File 'lib/better_auth/scim/patch_operations.rb', line 7 def scim_apply_patch_value!(user, update, account_update, value, operation_name, path = nil) value.each do |key, nested_value| nested_key = Schema.storage_key(key) nested_path = path ? "#{path}.#{nested_key}" : nested_key if nested_value.is_a?(Hash) scim_apply_patch_value!(user, update, account_update, normalize_hash(nested_value), operation_name, nested_path) else scim_apply_patch_path!(user, update, account_update, nested_path, nested_value, operation_name) end end end |
.scim_assert_provider_access!(ctx, user_id, provider, required_roles, config = {}) ⇒ Object
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/better_auth/scim/provider_management.rb', line 52 def scim_assert_provider_access!(ctx, user_id, provider, required_roles, config = {}) return unless provider organization_id = provider["organizationId"] if organization_id raise APIError.new("FORBIDDEN", message: "Organization plugin is required to access this SCIM provider") unless scim_has_organization_plugin?(ctx) member = scim_find_organization_member(ctx, user_id, organization_id) raise APIError.new("FORBIDDEN", message: "You must be a member of the organization to access this provider") unless member raise APIError.new("FORBIDDEN", message: "Insufficient role for this operation") unless scim_has_required_role?(member.fetch("role", ""), required_roles) elsif scim_provider_ownership_enabled?(config) raise APIError.new("FORBIDDEN", message: "You must be the owner to access this provider") unless provider["userId"] == user_id elsif provider.key?("userId") && provider["userId"] && provider["userId"] != user_id raise APIError.new("FORBIDDEN", message: "You must be the owner to access this provider") end end |
.scim_auth_middleware(config) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/better_auth/scim/middlewares.rb', line 7 def scim_auth_middleware(config) lambda do |ctx| encoded = ctx.headers["authorization"].to_s.sub(/\ABearer\s+/i, "") raise scim_error("UNAUTHORIZED", "SCIM token is required") if encoded.empty? token, provider_id, organization_id = scim_decode_token(encoded) provider = scim_default_provider(config, provider_id, organization_id) if provider stored = provider.fetch("scimToken").to_s provided = token.to_s unless scim_token_string_matches?(stored, provided) raise scim_error("UNAUTHORIZED", "Invalid SCIM token") end else provider = ctx.context.adapter.find_one( model: "scimProvider", where: [{field: "providerId", value: provider_id}].tap { |where| where << {field: "organizationId", value: organization_id} if organization_id } ) raise scim_error("UNAUTHORIZED", "Invalid SCIM token") unless provider raise scim_error("UNAUTHORIZED", "Invalid SCIM token") unless provider["organizationId"].to_s == organization_id.to_s raise scim_error("UNAUTHORIZED", "Invalid SCIM token") unless scim_token_matches?(ctx, config, token, provider.fetch("scimToken")) end ctx.context.apply_plugin_context!(scim_provider: provider) nil end end |
.scim_call_token_hook(callback, payload) ⇒ Object
90 91 92 |
# File 'lib/better_auth/scim/provider_management.rb', line 90 def scim_call_token_hook(callback, payload) callback.call(payload) if callback.respond_to?(:call) end |
.scim_client ⇒ Object
7 8 9 10 11 12 13 |
# File 'lib/better_auth/scim/client.rb', line 7 def scim_client { "id" => "scim-client", "version" => BetterAuth::SCIM::VERSION, "serverPluginId" => "scim" } end |
.scim_create_org_membership(ctx, user_id, organization_id) ⇒ Object
94 95 96 97 98 99 |
# File 'lib/better_auth/scim/provider_management.rb', line 94 def scim_create_org_membership(ctx, user_id, organization_id) return unless organization_id return if ctx.context.adapter.find_one(model: "member", where: [{field: "organizationId", value: organization_id}, {field: "userId", value: user_id}]) ctx.context.adapter.create(model: "member", data: {userId: user_id, organizationId: organization_id, role: "member", createdAt: Time.now}) end |
.scim_create_user_endpoint(config) ⇒ Object
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
# File 'lib/better_auth/scim/routes.rb', line 94 def scim_create_user_endpoint(config) Endpoint.new(path: "/scim/v2/Users", method: "POST", metadata: ("Create SCIM user.", SCIM_SUPPORTED_MEDIA_TYPES), use: [scim_auth_middleware(config)]) do |ctx| body = normalize_hash(ctx.body) scim_validate_user_body!(body) provider = ctx.context.scim_provider provider_id = provider.fetch("providerId") email = scim_primary_email(body).downcase account_id = scim_account_id(body) existing_account = ctx.context.adapter.find_one(model: "account", where: [{field: "accountId", value: account_id}, {field: "providerId", value: provider_id}]) raise scim_error("CONFLICT", "User already exists", scim_type: "uniqueness") if existing_account user, account = ctx.context.adapter.transaction do user = ctx.context.internal_adapter.find_user_by_email(email)&.fetch(:user) user ||= ctx.context.internal_adapter.create_user( email: email, name: scim_display_name(body, email) ) account = ctx.context.internal_adapter.create_account( userId: user.fetch("id"), providerId: provider_id, accountId: account_id, accessToken: "", refreshToken: "" ) scim_create_org_membership(ctx, user.fetch("id"), provider["organizationId"]) [user, account] end resource = scim_user_resource(user, account, ctx.context.base_url) ctx.json(resource, status: 201, headers: {location: resource.fetch(:meta).fetch(:location)}) end end |
.scim_decode_token(encoded) ⇒ Object
38 39 40 41 42 43 44 45 46 |
# File 'lib/better_auth/scim/scim_tokens.rb', line 38 def scim_decode_token(encoded) decoded = Base64.urlsafe_decode64(encoded.to_s) token, provider_id, *organization_parts = decoded.split(":") raise scim_error("UNAUTHORIZED", "Invalid SCIM token") if token.to_s.empty? || provider_id.to_s.empty? [token, provider_id, organization_parts.join(":").then { |value| value.empty? ? nil : value }] rescue ArgumentError raise scim_error("UNAUTHORIZED", "Invalid SCIM token") end |
.scim_default_provider(config, provider_id, organization_id) ⇒ Object
48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/better_auth/scim/scim_tokens.rb', line 48 def scim_default_provider(config, provider_id, organization_id) Array(config[:default_scim]).find do |provider| candidate = normalize_hash(provider) next true if candidate[:provider_id].to_s == provider_id.to_s && organization_id.to_s.empty? && candidate[:organization_id].to_s.empty? candidate[:provider_id].to_s == provider_id.to_s && !organization_id.to_s.empty? && candidate[:organization_id].to_s == organization_id.to_s end&.then do |provider| data = normalize_hash(provider) {"providerId" => data[:provider_id], "scimToken" => data[:scim_token], "organizationId" => data[:organization_id]} end end |
.scim_delete_provider_connection_endpoint(config) ⇒ Object
83 84 85 86 87 88 89 90 91 92 |
# File 'lib/better_auth/scim/routes.rb', line 83 def scim_delete_provider_connection_endpoint(config) Endpoint.new(path: "/scim/delete-provider-connection", method: "POST", metadata: ) do |ctx| session = Routes.current_session(ctx) body = normalize_hash(ctx.body) provider = scim_provider_by_provider_id!(ctx, body[:provider_id]) scim_assert_provider_access!(ctx, session.fetch(:user).fetch("id"), provider, scim_required_roles(ctx, config), config) ctx.context.adapter.delete(model: "scimProvider", where: [{field: "providerId", value: provider.fetch("providerId")}]) ctx.json({success: true}) end end |
.scim_delete_provider_openapi_metadata ⇒ Object
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/better_auth/scim/scim_metadata.rb', line 55 def { openapi: { summary: "Delete SCIM provider connection.", requestBody: OpenAPI.json_request_body( OpenAPI.object_schema( { provider_id: {type: "string", description: "SCIM provider identifier"} }, required: ["provider_id"] ) ), responses: scim_openapi_responses.merge( "200" => OpenAPI.json_response("SCIM provider connection deleted", OpenAPI.success_response_schema) ) } } end |
.scim_delete_user_endpoint(config) ⇒ Object
171 172 173 174 175 176 177 178 179 180 181 |
# File 'lib/better_auth/scim/routes.rb', line 171 def scim_delete_user_endpoint(config) Endpoint.new(path: "/scim/v2/Users/:userId", method: "DELETE", metadata: ("Delete SCIM user.", [*SCIM_SUPPORTED_MEDIA_TYPES, ""]), use: [scim_auth_middleware(config)]) do |ctx| user, account = scim_find_user_with_account!(ctx) ctx.context.adapter.transaction do ctx.context.internal_adapter.delete_account(account.fetch("id")) remaining_accounts = ctx.context.internal_adapter.find_accounts(user.fetch("id")) ctx.context.internal_adapter.delete_user(user.fetch("id")) if remaining_accounts.empty? end ctx.json(nil, status: 204) end end |
.scim_display_name(body, fallback = nil) ⇒ Object
16 17 18 19 20 21 |
# File 'lib/better_auth/scim/mappings.rb', line 16 def scim_display_name(body, fallback = nil) name = normalize_hash(body[:name] || {}) return name[:formatted].to_s.strip unless name[:formatted].to_s.strip.empty? scim_full_name(fallback, given_name: name[:given_name], family_name: name[:family_name]) end |
.scim_error(status, detail, scim_type: nil) ⇒ Object
7 8 9 10 11 12 13 14 15 |
# File 'lib/better_auth/scim/scim_error.rb', line 7 def scim_error(status, detail, scim_type: nil) body = { schemas: [SCIM_ERROR_SCHEMA], status: APIError::STATUS_CODES.fetch(status.to_s.upcase, 500).to_s, detail: detail } body[:scimType] = scim_type if scim_type APIError.new(status, message: detail, body: body) end |
.scim_family_name(name) ⇒ Object
43 44 45 46 |
# File 'lib/better_auth/scim/mappings.rb', line 43 def scim_family_name(name) parts = name.to_s.split (parts.length > 1) ? parts[1..].join(" ") : "" end |
.scim_find_organization_member(ctx, user_id, organization_id) ⇒ Object
27 28 29 30 31 32 33 34 35 |
# File 'lib/better_auth/scim/provider_management.rb', line 27 def scim_find_organization_member(ctx, user_id, organization_id) ctx.context.adapter.find_one( model: "member", where: [ {field: "userId", value: user_id}, {field: "organizationId", value: organization_id} ] ) end |
.scim_find_user_with_account!(ctx) ⇒ Object
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 |
# File 'lib/better_auth/scim/routes.rb', line 292 def scim_find_user_with_account!(ctx) provider = ctx.context.scim_provider user_id = scim_param(ctx, :user_id) account = ctx.context.adapter.find_one( model: "account", where: [ {field: "userId", value: user_id}, {field: "providerId", value: provider.fetch("providerId")} ] ) user = account && ctx.context.internal_adapter.find_user_by_id(user_id) if user && provider["organizationId"] member = ctx.context.adapter.find_one( model: "member", where: [{field: "organizationId", value: provider.fetch("organizationId")}, {field: "userId", value: user_id}] ) user = nil unless member end raise scim_error("NOT_FOUND", "User not found") unless user && account [user, account] end |
.scim_full_name(fallback, given_name:, family_name:) ⇒ Object
33 34 35 36 |
# File 'lib/better_auth/scim/mappings.rb', line 33 def scim_full_name(fallback, given_name:, family_name:) name = [given_name, family_name].compact.join(" ").strip name.empty? ? fallback.to_s : name end |
.scim_generate_token_endpoint(config) ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/better_auth/scim/routes.rb', line 9 def scim_generate_token_endpoint(config) Endpoint.new(path: "/scim/generate-token", method: "POST", metadata: ) do |ctx| session = Routes.current_session(ctx) body = normalize_hash(ctx.body) raw_provider_id = body[:provider_id] raise APIError.new("BAD_REQUEST", message: BASE_ERROR_CODES["VALIDATION_ERROR"]) unless raw_provider_id.is_a?(String) provider_id = raw_provider_id organization_id = body[:organization_id] if body.key?(:organization_id) && !organization_id.nil? && !organization_id.is_a?(String) raise APIError.new("BAD_REQUEST", message: BASE_ERROR_CODES["VALIDATION_ERROR"]) end raise APIError.new("BAD_REQUEST", message: BASE_ERROR_CODES["MISSING_FIELD"]) if provider_id.empty? raise APIError.new("BAD_REQUEST", message: "Provider id contains forbidden characters") if provider_id.include?(":") required_roles = scim_required_roles(ctx, config) if organization_id && !scim_has_organization_plugin?(ctx) raise APIError.new("BAD_REQUEST", message: "Restricting a token to an organization requires the organization plugin") end member = nil if organization_id member = scim_find_organization_member(ctx, session.fetch(:user).fetch("id"), organization_id) raise APIError.new("FORBIDDEN", message: "You are not a member of the organization") unless member raise APIError.new("FORBIDDEN", message: "Insufficient role for this operation") unless scim_has_required_role?(member.fetch("role", ""), required_roles) end existing = ctx.context.adapter.find_one(model: "scimProvider", where: [{field: "providerId", value: provider_id}]) if existing scim_assert_provider_access!(ctx, session.fetch(:user).fetch("id"), existing, required_roles, config) ctx.context.adapter.delete(model: "scimProvider", where: [{field: "id", value: existing.fetch("id")}]) end base_token = Crypto.random_string(24) token = Base64.urlsafe_encode64([base_token, provider_id, organization_id].compact.join(":"), padding: false) scim_call_token_hook(config[:before_scim_token_generated], user: session.fetch(:user), member: member, scim_token: token) stored = scim_store_token(ctx, config, base_token) data = {providerId: provider_id, scimToken: stored, organizationId: organization_id} data[:userId] = session.fetch(:user).fetch("id") if scim_provider_ownership_enabled?(config) provider = ctx.context.adapter.create(model: "scimProvider", data: data) scim_call_token_hook(config[:after_scim_token_generated], user: session.fetch(:user), member: member, scim_token: token, scim_provider: provider) ctx.json({scimToken: token}, status: 201) end end |
.scim_generate_token_openapi_metadata ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/better_auth/scim/scim_metadata.rb', line 32 def { openapi: { summary: "Generates a new SCIM token for the given provider", requestBody: OpenAPI.json_request_body( OpenAPI.object_schema( { provider_id: {type: "string", description: "SCIM provider identifier"}, organization_id: {type: "string", description: "Organization ID to restrict the SCIM token to"} }, required: ["provider_id"] ) ), responses: scim_openapi_responses.merge( "201" => OpenAPI.json_response( "SCIM token generated", OpenAPI.object_schema({scimToken: {type: "string"}}, required: ["scimToken"]) ) ) } } end |
.scim_get_provider_connection_endpoint(config) ⇒ Object
74 75 76 77 78 79 80 81 |
# File 'lib/better_auth/scim/routes.rb', line 74 def scim_get_provider_connection_endpoint(config) Endpoint.new(path: "/scim/get-provider-connection", method: "GET", metadata: ("Get SCIM provider connection.")) do |ctx| session = Routes.current_session(ctx) provider = scim_provider_by_provider_id!(ctx, scim_provider_id_query(ctx)) scim_assert_provider_access!(ctx, session.fetch(:user).fetch("id"), provider, scim_required_roles(ctx, config), config) ctx.json(scim_normalized_provider(provider)) end end |
.scim_get_user_endpoint(config) ⇒ Object
233 234 235 236 237 238 |
# File 'lib/better_auth/scim/routes.rb', line 233 def scim_get_user_endpoint(config) Endpoint.new(path: "/scim/v2/Users/:userId", method: "GET", metadata: ("Get SCIM user.", SCIM_SUPPORTED_MEDIA_TYPES), use: [scim_auth_middleware(config)]) do |ctx| user, account = scim_find_user_with_account!(ctx) ctx.json(scim_user_resource(user, account, ctx.context.base_url)) end end |
.scim_given_name(name) ⇒ Object
38 39 40 41 |
# File 'lib/better_auth/scim/mappings.rb', line 38 def scim_given_name(name) parts = name.to_s.split (parts.length > 1) ? parts[0...-1].join(" ") : name.to_s end |
.scim_has_organization_plugin?(ctx) ⇒ Boolean
7 8 9 |
# File 'lib/better_auth/scim/provider_management.rb', line 7 def scim_has_organization_plugin?(ctx) Array(ctx.context..plugins).any? { |plugin| plugin.id == "organization" } end |
.scim_has_required_role?(role, required_roles) ⇒ Boolean
41 42 43 44 |
# File 'lib/better_auth/scim/provider_management.rb', line 41 def scim_has_required_role?(role, required_roles) required = Array(required_roles).map(&:to_s) required.empty? || scim_parse_roles(role).any? { |candidate| required.include?(candidate) } end |
.scim_hidden_metadata(summary, allowed_media_types) ⇒ Object
12 13 14 15 16 17 18 19 20 21 |
# File 'lib/better_auth/scim/scim_metadata.rb', line 12 def (summary, allowed_media_types) { hide: true, allowed_media_types: allowed_media_types, openapi: { summary: summary, responses: scim_openapi_responses } } end |
.scim_list_pagination(query) ⇒ Object
315 316 317 318 319 320 321 |
# File 'lib/better_auth/scim/routes.rb', line 315 def scim_list_pagination(query) start_index = scim_positive_integer(query[:startIndex] || query[:start_index] || query["startIndex"] || query["start_index"], 1) count = if query.key?(:count) || query.key?("count") scim_non_negative_integer(query[:count] || query["count"], 0) end [start_index, count] end |
.scim_list_provider_connections_endpoint(config) ⇒ Object
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/better_auth/scim/routes.rb', line 53 def scim_list_provider_connections_endpoint(config) Endpoint.new(path: "/scim/list-provider-connections", method: "GET", metadata: ("List SCIM provider connections.")) do |ctx| session = Routes.current_session(ctx) user_id = session.fetch(:user).fetch("id") required_roles = scim_required_roles(ctx, config) org_memberships = scim_has_organization_plugin?(ctx) ? scim_user_org_memberships(ctx, user_id) : {} providers = ctx.context.adapter.find_many(model: "scimProvider").select do |provider| organization_id = provider["organizationId"] if organization_id member = org_memberships[organization_id] member && scim_has_required_role?(member.fetch("role", ""), required_roles) elsif scim_provider_ownership_enabled?(config) provider["userId"] == user_id else !provider.key?("userId") || provider["userId"].nil? || provider["userId"] == user_id end end ctx.json({providers: providers.map { |provider| scim_normalized_provider(provider) }}) end end |
.scim_list_users_endpoint(config) ⇒ Object
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
# File 'lib/better_auth/scim/routes.rb', line 183 def scim_list_users_endpoint(config) Endpoint.new(path: "/scim/v2/Users", method: "GET", metadata: ("List SCIM users.", SCIM_SUPPORTED_MEDIA_TYPES), use: [scim_auth_middleware(config)]) do |ctx| provider = ctx.context.scim_provider filter_value = nil if ctx.query[:filter] || ctx.query["filter"] _filter_field, filter_value = scim_parse_filter(ctx.query[:filter] || ctx.query["filter"]) end start_index, count = scim_list_pagination(ctx.query) empty_list = {schemas: [SCIM_LIST_RESPONSE_SCHEMA], totalResults: 0, itemsPerPage: 0, startIndex: start_index, Resources: []} accounts = ctx.context.adapter.find_many(model: "account", where: [{field: "providerId", value: provider.fetch("providerId")}]) account_user_ids = accounts.map { |account| account.fetch("userId") }.uniq if account_user_ids.empty? ctx.json(empty_list) else user_ids = account_user_ids if provider["organizationId"] user_ids = ctx.context.adapter.find_many( model: "member", where: [ {field: "organizationId", value: provider.fetch("organizationId")}, {field: "userId", value: account_user_ids, operator: "in"} ] ).map { |member| member.fetch("userId") }.uniq end if user_ids.empty? ctx.json(empty_list) else where = [{field: "id", value: user_ids, operator: "in"}] if filter_value where << {field: "email", value: filter_value.to_s.downcase, operator: "eq"} end total_results = ctx.context.internal_adapter.count_total_users(where: where) offset = start_index - 1 limit = count || ((offset > 0) ? [total_results - offset, 0].max : nil) users = ctx.context.internal_adapter.list_users( where: where, sort_by: {field: "email", direction: "asc"}, limit: limit, offset: offset.positive? ? offset : nil ) accounts_by_user = accounts.each_with_object({}) { |account, result| result[account.fetch("userId")] ||= account } resources = users.map { |user| scim_user_resource(user, accounts_by_user[user.fetch("id")], ctx.context.base_url) } ctx.json({schemas: [SCIM_LIST_RESPONSE_SCHEMA], totalResults: total_results, itemsPerPage: resources.length, startIndex: start_index, Resources: resources}) end end end end |
.scim_non_negative_integer(value, fallback) ⇒ Object
330 331 332 333 334 335 |
# File 'lib/better_auth/scim/routes.rb', line 330 def scim_non_negative_integer(value, fallback) parsed = Integer(value) parsed.negative? ? fallback : parsed rescue ArgumentError, TypeError fallback end |
.scim_normalized_provider(provider) ⇒ Object
82 83 84 85 86 87 88 |
# File 'lib/better_auth/scim/provider_management.rb', line 82 def scim_normalized_provider(provider) { id: provider.fetch("id"), providerId: provider.fetch("providerId"), organizationId: provider["organizationId"] } end |
.scim_openapi_metadata(summary) ⇒ Object
23 24 25 26 27 28 29 30 |
# File 'lib/better_auth/scim/scim_metadata.rb', line 23 def (summary) { openapi: { summary: summary, responses: scim_openapi_responses } } end |
.scim_openapi_responses ⇒ Object
74 75 76 77 78 79 80 81 82 |
# File 'lib/better_auth/scim/scim_metadata.rb', line 74 def scim_openapi_responses { "200" => {description: "Success"}, "400" => {description: "Bad Request"}, "401" => {description: "Unauthorized"}, "403" => {description: "Forbidden"}, "404" => {description: "Not Found"} } end |
.scim_organization_plugin(ctx) ⇒ Object
11 12 13 |
# File 'lib/better_auth/scim/provider_management.rb', line 11 def scim_organization_plugin(ctx) Array(ctx.context..plugins).find { |plugin| plugin.id == "organization" } end |
.scim_param(ctx, key) ⇒ Object
7 8 9 |
# File 'lib/better_auth/scim/utils.rb', line 7 def scim_param(ctx, key) ctx.params[key] || ctx.params[key.to_s] || ctx.params[Schema.storage_key(key)] || ctx.params[Schema.storage_key(key).to_sym] end |
.scim_parse_filter(filter) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/better_auth/scim/scim_filters.rb', line 7 def scim_parse_filter(filter) match = filter.to_s.match(/\A\s*([^\s]+)\s+(eq|ne|co|sw|ew|pr)\s*(?:"([^"]*)"|([^\s]+))?\s*\z/i) raise scim_error("BAD_REQUEST", "Invalid filter expression", scim_type: "invalidFilter") unless match field = match[1] operator = match[2].downcase value = match[3] || match[4] raise scim_error("BAD_REQUEST", "Invalid filter expression", scim_type: "invalidFilter") if value.nil? raise scim_error("BAD_REQUEST", "The operator \"#{operator}\" is not supported", scim_type: "invalidFilter") unless operator == "eq" raise scim_error("BAD_REQUEST", "The attribute \"#{field}\" is not supported", scim_type: "invalidFilter") unless field == "userName" [field, value] end |
.scim_parse_roles(role) ⇒ Object
37 38 39 |
# File 'lib/better_auth/scim/provider_management.rb', line 37 def scim_parse_roles(role) Array(role).flat_map { |entry| entry.to_s.split(",") }.map(&:strip).reject(&:empty?) end |
.scim_patch_should_apply?(current_value, new_value, operation_name) ⇒ Boolean
39 40 41 42 43 44 |
# File 'lib/better_auth/scim/patch_operations.rb', line 39 def scim_patch_should_apply?(current_value, new_value, operation_name) return false if operation_name == "remove" return false if operation_name == "add" && current_value == new_value true end |
.scim_patch_user_endpoint(config) ⇒ Object
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
# File 'lib/better_auth/scim/routes.rb', line 141 def scim_patch_user_endpoint(config) Endpoint.new(path: "/scim/v2/Users/:userId", method: "PATCH", metadata: ("Patch SCIM user.", SCIM_SUPPORTED_MEDIA_TYPES), use: [scim_auth_middleware(config)]) do |ctx| user, account = scim_find_user_with_account!(ctx) body = normalize_hash(ctx.body) scim_validate_patch_body!(body) update = {} account_update = {} Array(body[:operations] || ctx.body["Operations"]).each do |operation| op = normalize_hash(operation) operation_name = op[:op].to_s.empty? ? "replace" : op[:op].to_s.downcase raise scim_error("BAD_REQUEST", "Invalid SCIM patch operation") unless %w[replace add remove].include?(operation_name) if op[:value].is_a?(Hash) patch_path = op[:path].to_s.empty? ? nil : op[:path] scim_apply_patch_value!(user, update, account_update, normalize_hash(op[:value]), operation_name, patch_path) next end scim_apply_patch_path!(user, update, account_update, op[:path], op[:value], operation_name) end raise scim_error("BAD_REQUEST", "No valid fields to update") if update.empty? && account_update.empty? ctx.context.adapter.transaction do ctx.context.internal_adapter.update_user(user.fetch("id"), update.merge(updatedAt: Time.now)) unless update.empty? ctx.context.internal_adapter.update_account(account.fetch("id"), account_update.merge(updatedAt: Time.now)) unless account_update.empty? end ctx.json(nil, status: 204) end end |
.scim_patch_validation_error(message) ⇒ Object
60 61 62 |
# File 'lib/better_auth/scim/validation.rb', line 60 def scim_patch_validation_error() scim_error("BAD_REQUEST", ) end |
.scim_positive_integer(value, fallback) ⇒ Object
323 324 325 326 327 328 |
# File 'lib/better_auth/scim/routes.rb', line 323 def scim_positive_integer(value, fallback) parsed = Integer(value) parsed.positive? ? parsed : fallback rescue ArgumentError, TypeError fallback end |
.scim_primary_email(body) ⇒ Object
27 28 29 30 31 |
# File 'lib/better_auth/scim/mappings.rb', line 27 def scim_primary_email(body) primary = Array(body[:emails]).find { |email| normalize_hash(email)[:primary] } first = Array(body[:emails]).first normalize_hash(primary || first)[:value] || body[:user_name] end |
.scim_provider_by_provider_id!(ctx, provider_id) ⇒ Object
69 70 71 72 73 74 75 76 |
# File 'lib/better_auth/scim/provider_management.rb', line 69 def scim_provider_by_provider_id!(ctx, provider_id) raise APIError.new("BAD_REQUEST", message: BASE_ERROR_CODES["VALIDATION_ERROR"]) unless provider_id.is_a?(String) provider = ctx.context.adapter.find_one(model: "scimProvider", where: [{field: "providerId", value: provider_id.to_s}]) raise APIError.new("NOT_FOUND", message: "SCIM provider not found") unless provider provider end |
.scim_provider_id_query(ctx) ⇒ Object
78 79 80 |
# File 'lib/better_auth/scim/provider_management.rb', line 78 def scim_provider_id_query(ctx) ctx.query[:providerId] || ctx.query[:provider_id] || ctx.query["providerId"] || ctx.query["provider_id"] end |
.scim_provider_ownership_enabled?(config) ⇒ Boolean
23 24 25 |
# File 'lib/better_auth/scim/provider_management.rb', line 23 def scim_provider_ownership_enabled?(config) normalize_hash(config[:provider_ownership] || {})[:enabled] == true end |
.scim_required_roles(ctx, config) ⇒ Object
15 16 17 18 19 20 21 |
# File 'lib/better_auth/scim/provider_management.rb', line 15 def scim_required_roles(ctx, config) configured = config[:required_role] || config[:required_roles] return Array(configured).map(&:to_s) if configured creator_role = scim_organization_plugin(ctx)&.&.fetch(:creator_role, nil) ["admin", creator_role || "owner"].uniq end |
.scim_resource_type_endpoint ⇒ Object
284 285 286 287 288 289 290 |
# File 'lib/better_auth/scim/routes.rb', line 284 def scim_resource_type_endpoint Endpoint.new(path: "/scim/v2/ResourceTypes/:resourceTypeId", method: "GET", metadata: ("Get SCIM resource type.", SCIM_SUPPORTED_MEDIA_TYPES)) do |ctx| raise scim_error("NOT_FOUND", "Resource type not found") unless scim_param(ctx, :resource_type_id) == "User" ctx.json(scim_user_resource_type(ctx.context.base_url)) end end |
.scim_resource_types_endpoint ⇒ Object
277 278 279 280 281 282 |
# File 'lib/better_auth/scim/routes.rb', line 277 def scim_resource_types_endpoint Endpoint.new(path: "/scim/v2/ResourceTypes", method: "GET", metadata: ("List SCIM resource types.", SCIM_SUPPORTED_MEDIA_TYPES)) do |ctx| resource = scim_user_resource_type(ctx.context.base_url) ctx.json({schemas: [SCIM_LIST_RESPONSE_SCHEMA], Resources: [resource], totalResults: 1, itemsPerPage: 1, startIndex: 1}) end end |
.scim_resource_url(base_url, path) ⇒ Object
11 12 13 14 15 |
# File 'lib/better_auth/scim/utils.rb', line 11 def scim_resource_url(base_url, path) return path unless base_url "#{base_url}#{path}" end |
.scim_schema(config = {}) ⇒ Object
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/better_auth/plugins/scim.rb', line 54 def scim_schema(config = {}) scim_provider_fields = { providerId: {type: "string", required: true, unique: true}, scimToken: {type: "string", required: true, unique: true}, organizationId: {type: "string", required: false} } scim_provider_fields[:userId] = {type: "string", required: false} if scim_provider_ownership_enabled?(config) { scimProvider: { model_name: "scim_providers", fields: scim_provider_fields } } end |
.scim_schema_endpoint ⇒ Object
269 270 271 272 273 274 275 |
# File 'lib/better_auth/scim/routes.rb', line 269 def scim_schema_endpoint Endpoint.new(path: "/scim/v2/Schemas/:schemaId", method: "GET", metadata: ("Get SCIM schema.", SCIM_SUPPORTED_MEDIA_TYPES)) do |ctx| raise scim_error("NOT_FOUND", "Schema not found") unless scim_param(ctx, :schema_id).to_s == SCIM_USER_SCHEMA_ID ctx.json(scim_user_schema(ctx.context.base_url)) end end |
.scim_schemas_endpoint ⇒ Object
262 263 264 265 266 267 |
# File 'lib/better_auth/scim/routes.rb', line 262 def scim_schemas_endpoint Endpoint.new(path: "/scim/v2/Schemas", method: "GET", metadata: ("List SCIM schemas.", SCIM_SUPPORTED_MEDIA_TYPES)) do |ctx| resource = scim_user_schema(ctx.context.base_url) ctx.json({schemas: [SCIM_LIST_RESPONSE_SCHEMA], Resources: [resource], totalResults: 1, itemsPerPage: 1, startIndex: 1}) end end |
.scim_service_provider_config_endpoint ⇒ Object
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 |
# File 'lib/better_auth/scim/routes.rb', line 240 def scim_service_provider_config_endpoint Endpoint.new(path: "/scim/v2/ServiceProviderConfig", method: "GET", metadata: ("SCIM Service Provider Configuration", SCIM_SUPPORTED_MEDIA_TYPES)) do |ctx| ctx.json({ schemas: ["urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig"], patch: {supported: true}, bulk: {supported: false}, filter: {supported: true}, changePassword: {supported: false}, sort: {supported: false}, etag: {supported: false}, authenticationSchemes: [{ type: "oauthbearertoken", name: "OAuth Bearer Token", description: "Authentication scheme using the Authorization header with a bearer token tied to an organization.", specUri: "http://www.rfc-editor.org/info/rfc6750", primary: true }], meta: {resourceType: "ServiceProviderConfig"} }) end end |
.scim_store_token(ctx, config, token) ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/better_auth/scim/scim_tokens.rb', line 9 def scim_store_token(ctx, config, token) storage = config[:store_scim_token] if storage == "hashed" Crypto.sha256(token, encoding: :base64url) elsif storage == "encrypted" Crypto.symmetric_encrypt(key: ctx.context.secret, data: token) elsif storage.is_a?(Hash) && storage[:hash].respond_to?(:call) storage[:hash].call(token) elsif storage.is_a?(Hash) && storage[:encrypt].respond_to?(:call) storage[:encrypt].call(token) else token end end |
.scim_token_matches?(ctx, config, token, stored) ⇒ Boolean
24 25 26 27 28 29 30 |
# File 'lib/better_auth/scim/scim_tokens.rb', line 24 def scim_token_matches?(ctx, config, token, stored) storage = config[:store_scim_token] return scim_token_string_matches?(Crypto.symmetric_decrypt(key: ctx.context.secret, data: stored), token) if storage == "encrypted" return scim_token_string_matches?(storage[:decrypt].call(stored), token) if storage.is_a?(Hash) && storage[:decrypt].respond_to?(:call) scim_token_string_matches?(scim_store_token(ctx, config, token), stored) end |
.scim_token_string_matches?(expected, provided) ⇒ Boolean
32 33 34 35 36 |
# File 'lib/better_auth/scim/scim_tokens.rb', line 32 def scim_token_string_matches?(expected, provided) expected = expected.to_s provided = provided.to_s !provided.empty? && expected.bytesize == provided.bytesize && Crypto.constant_time_compare(expected, provided) end |
.scim_update_user_endpoint(config) ⇒ Object
126 127 128 129 130 131 132 133 134 135 136 137 138 139 |
# File 'lib/better_auth/scim/routes.rb', line 126 def scim_update_user_endpoint(config) Endpoint.new(path: "/scim/v2/Users/:userId", method: "PUT", metadata: ("Update SCIM user.", SCIM_SUPPORTED_MEDIA_TYPES), use: [scim_auth_middleware(config)]) do |ctx| user, account = scim_find_user_with_account!(ctx) body = normalize_hash(ctx.body) scim_validate_user_body!(body) updated, updated_account = ctx.context.adapter.transaction do [ ctx.context.internal_adapter.update_user(user.fetch("id"), scim_user_update(body)), ctx.context.internal_adapter.update_account(account.fetch("id"), accountId: scim_account_id(body), updatedAt: Time.now) ] end ctx.json(scim_user_resource(updated, updated_account, ctx.context.base_url)) end end |
.scim_user_org_memberships(ctx, user_id) ⇒ Object
46 47 48 49 50 |
# File 'lib/better_auth/scim/provider_management.rb', line 46 def scim_user_org_memberships(ctx, user_id) ctx.context.adapter.find_many(model: "member", where: [{field: "userId", value: user_id}]).each_with_object({}) do |member, result| result[member.fetch("organizationId")] = member end end |
.scim_user_resource(user, account = nil, base_url = nil) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/better_auth/scim/scim_resources.rb', line 7 def scim_user_resource(user, account = nil, base_url = nil) { schemas: [SCIM_USER_SCHEMA_ID], id: user.fetch("id"), userName: user.fetch("email"), externalId: account&.fetch("accountId", nil), displayName: user["name"], active: true, name: {formatted: user["name"]}, emails: [{primary: true, value: user.fetch("email")}], meta: { resourceType: "User", created: user["createdAt"], lastModified: user["updatedAt"], location: base_url ? "#{base_url}/scim/v2/Users/#{user.fetch("id")}" : nil }.compact }.compact end |
.scim_user_resource_type(base_url = nil) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/better_auth/scim/user_schemas.rb', line 49 def scim_user_resource_type(base_url = nil) { schemas: ["urn:ietf:params:scim:schemas:core:2.0:ResourceType"], id: "User", name: "User", endpoint: "/Users", description: "User Account", schema: SCIM_USER_SCHEMA_ID, meta: {resourceType: "ResourceType", location: scim_resource_url(base_url, "/scim/v2/ResourceTypes/User")} } end |
.scim_user_schema(base_url = nil) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/better_auth/scim/user_schemas.rb', line 7 def scim_user_schema(base_url = nil) { id: SCIM_USER_SCHEMA_ID, schemas: ["urn:ietf:params:scim:schemas:core:2.0:Schema"], name: "User", description: "User Account", attributes: [ {name: "id", type: "string", multiValued: false, description: "Unique opaque identifier for the User", required: false, caseExact: true, mutability: "readOnly", returned: "default", uniqueness: "server"}, {name: "userName", type: "string", multiValued: false, description: "Unique identifier for the User, typically used by the user to directly authenticate to the service provider", required: true, caseExact: false, mutability: "readWrite", returned: "default", uniqueness: "server"}, {name: "displayName", type: "string", multiValued: false, description: "The name of the User, suitable for display to end-users. The name SHOULD be the full name of the User being described, if known.", required: false, caseExact: true, mutability: "readOnly", returned: "default", uniqueness: "none"}, {name: "active", type: "boolean", multiValued: false, description: "A Boolean value indicating the User's administrative status.", required: false, mutability: "readOnly", returned: "default"}, { name: "name", type: "complex", multiValued: false, description: "The components of the user's real name.", required: false, subAttributes: [ {name: "formatted", type: "string", multiValued: false, description: "The full name, including all middlenames, titles, and suffixes as appropriate, formatted for display(e.g., 'Ms. Barbara J Jensen, III').", required: false, caseExact: false, mutability: "readWrite", returned: "default", uniqueness: "none"}, {name: "familyName", type: "string", multiValued: false, description: "The family name of the User, or last name in most Western languages (e.g., 'Jensen' given the fullname 'Ms. Barbara J Jensen, III').", required: false, caseExact: false, mutability: "readWrite", returned: "default", uniqueness: "none"}, {name: "givenName", type: "string", multiValued: false, description: "The given name of the User, or first name in most Western languages (e.g., 'Barbara' given the full name 'Ms. Barbara J Jensen, III').", required: false, caseExact: false, mutability: "readWrite", returned: "default", uniqueness: "none"} ] }, { name: "emails", type: "complex", multiValued: true, description: "Email addresses for the user. The value SHOULD be canonicalized by the service provider, e.g., 'bjensen@example.com' instead of 'bjensen@EXAMPLE.COM'. Canonical type values of 'work', 'home', and 'other'.", required: false, mutability: "readWrite", returned: "default", uniqueness: "none", subAttributes: [ {name: "value", type: "string", multiValued: false, description: "Email addresses for the user. The value SHOULD be canonicalized by the service provider, e.g., 'bjensen@example.com' instead of 'bjensen@EXAMPLE.COM'. Canonical type values of 'work', 'home', and 'other'.", required: false, caseExact: false, mutability: "readWrite", returned: "default", uniqueness: "server"}, {name: "primary", type: "boolean", multiValued: false, description: "A Boolean value indicating the 'primary' or preferred attribute value for this attribute, e.g., the preferred mailing address or primary email address. The primary attribute value 'true' MUST appear no more than once.", required: false, mutability: "readWrite", returned: "default"} ] } ], meta: {resourceType: "Schema", location: scim_resource_url(base_url, "/scim/v2/Schemas/#{SCIM_USER_SCHEMA_ID}")} } end |
.scim_user_update(body) ⇒ Object
7 8 9 10 11 12 13 14 |
# File 'lib/better_auth/scim/mappings.rb', line 7 def scim_user_update(body) email = scim_primary_email(body)&.downcase { email: email, name: scim_display_name(body, email), updatedAt: Time.now }.compact end |
.scim_validate_patch_body!(body) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/better_auth/scim/validation.rb', line 28 def scim_validate_patch_body!(body) schemas = Array(body[:schemas]) raise scim_error("BAD_REQUEST", "Invalid schemas for PatchOp") unless schemas.include?("urn:ietf:params:scim:api:messages:2.0:PatchOp") operations = body[:operations] raise scim_error("BAD_REQUEST", BASE_ERROR_CODES["VALIDATION_ERROR"]) unless operations.is_a?(Array) raise scim_error("BAD_REQUEST", "Too many SCIM patch operations") if operations.length > SCIM_MAX_PATCH_OPERATIONS operations.each_with_index do |operation, index| normalized = normalize_hash(operation) op = normalized[:op] next if op.nil? || op.to_s.empty? unless op.is_a?(String) raise scim_patch_validation_error("[body.Operations.#{index}.op] Invalid input: expected string") end next if %w[replace add remove].include?(op.downcase) raise scim_patch_validation_error("[body.Operations.#{index}.op] Invalid option: expected one of \"replace\"|\"add\"|\"remove\"") end operations.each { |operation| scim_validate_patch_value_depth!(normalize_hash(operation)[:value]) } end |
.scim_validate_patch_value_depth!(value, depth = 0) ⇒ Object
53 54 55 56 57 58 |
# File 'lib/better_auth/scim/validation.rb', line 53 def scim_validate_patch_value_depth!(value, depth = 0) return unless value.is_a?(Hash) raise scim_error("BAD_REQUEST", "SCIM patch value is too deeply nested") if depth > SCIM_MAX_PATCH_VALUE_DEPTH value.each_value { |nested| scim_validate_patch_value_depth!(nested, depth + 1) } end |
.scim_validate_user_body!(body) ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/better_auth/scim/validation.rb', line 10 def scim_validate_user_body!(body) raise scim_error("BAD_REQUEST", BASE_ERROR_CODES["VALIDATION_ERROR"]) unless body[:user_name].is_a?(String) raise scim_error("BAD_REQUEST", BASE_ERROR_CODES["VALIDATION_ERROR"]) if body[:user_name].empty? raise scim_error("BAD_REQUEST", BASE_ERROR_CODES["VALIDATION_ERROR"]) if body.key?(:external_id) && !body[:external_id].is_a?(String) raise scim_error("BAD_REQUEST", BASE_ERROR_CODES["VALIDATION_ERROR"]) if body.key?(:name) && !body[:name].is_a?(Hash) raise scim_error("BAD_REQUEST", BASE_ERROR_CODES["VALIDATION_ERROR"]) if body.key?(:emails) && !body[:emails].is_a?(Array) normalize_hash(body[:name] || {}).each_value do |value| raise scim_error("BAD_REQUEST", BASE_ERROR_CODES["VALIDATION_ERROR"]) unless value.is_a?(String) end Array(body[:emails]).each do |email| email = normalize_hash(email) value = email[:value] raise scim_error("BAD_REQUEST", BASE_ERROR_CODES["VALIDATION_ERROR"]) if email.key?(:primary) && ![true, false].include?(email[:primary]) raise scim_error("BAD_REQUEST", BASE_ERROR_CODES["VALIDATION_ERROR"]) unless value.to_s.match?(/\A[^@\s]+@[^@\s]+\.[^@\s]+\z/) end end |