forked from lessonly/scim_rails
-
Notifications
You must be signed in to change notification settings - Fork 7
/
response.rb
94 lines (85 loc) · 2.8 KB
/
response.rb
1
2
3
4
5
6
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# frozen_string_literal: true
module ScimRails
module Response
CONTENT_TYPE = 'application/scim+json'
def json_response(object, status = :ok)
render \
json: object,
status: status,
content_type: CONTENT_TYPE
end
def json_scim_response(object:, status: :ok, counts: nil)
case params[:action]
when 'index'
render \
json: list_response(object, counts),
status: status,
content_type: CONTENT_TYPE
when 'show', 'create', 'put_update', 'patch_update'
render \
json: object_response(object),
status: status,
content_type: CONTENT_TYPE
end
end
private
def list_response(object, counts)
object = object
.order(:id)
.offset(counts.offset)
.limit(counts.limit)
{
schemas: [
'urn:ietf:params:scim:api:messages:2.0:ListResponse'
],
totalResults: counts.total,
startIndex: counts.start_index,
itemsPerPage: counts.limit,
Resources: list_objects(object),
}
end
def list_objects(objects)
objects.map do |object|
object_response(object)
end
end
def object_response(object)
schema = case object
when ScimRails.config.scim_users_model
ScimRails.config.user_schema
when ScimRails.config.scim_groups_model
ScimRails.config.group_schema
else
raise ScimRails::ExceptionHandler::InvalidQuery,
"Unknown model: #{object}"
end
find_value(object, schema)
end
# `find_value` is a recursive method that takes a "user" and a
# "user schema" and replaces any symbols in the schema with the
# corresponding value from the user. Given a schema with symbols,
# `find_value` will search through the object for the symbols,
# send those symbols to the model, and replace the symbol with
# the return value.
def find_value(object, schema)
case schema
when Hash
schema.each.with_object({}) do |(key, value), hash|
hash[key] = find_value(object, value)
end
when Array, ActiveRecord::Associations::CollectionProxy
schema.map do |value|
find_value(object, value)
end
when ScimRails.config.scim_users_model
find_value(schema, ScimRails.config.user_abbreviated_schema)
when ScimRails.config.scim_groups_model
find_value(schema, ScimRails.config.group_abbreviated_schema)
when Symbol
find_value(object, object.public_send(schema))
else
schema
end
end
end
end