Commit 25af95e0e6f2ea13de1b694c5e289c987d84a12d
1 parent
3a4364a4
Exists in
master
add json scim response structure
Showing
1 changed file
with
66 additions
and
1 deletions
Show diff stats
app/controllers/concerns/scim_rails/response.rb
1 | 1 | module ScimRails |
2 | 2 | module Response |
3 | + CONTENT_TYPE = "application/scim+json, application/json".freeze | |
4 | + | |
3 | 5 | def json_response(object, status = :ok) |
4 | - render(json: object, status: status) | |
6 | + render \ | |
7 | + json: object, | |
8 | + status: status | |
9 | + end | |
10 | + | |
11 | + def json_scim_response(object:, status: :ok, counts: nil) | |
12 | + case params[:action] | |
13 | + when "index" | |
14 | + render \ | |
15 | + json: list_response(object, counts), | |
16 | + status: status, | |
17 | + content_type: CONTENT_TYPE | |
18 | + when "show", "create", "update" | |
19 | + render \ | |
20 | + json: user_response(object), | |
21 | + status: status, | |
22 | + content_type: CONTENT_TYPE | |
23 | + end | |
24 | + end | |
25 | + | |
26 | + private | |
27 | + | |
28 | + def list_response(object, counts) | |
29 | + object = object | |
30 | + .order(:id) | |
31 | + .offset(counts.offset) | |
32 | + .limit(counts.limit) | |
33 | + { | |
34 | + "schemas": [ | |
35 | + "urn:ietf:params:scim:api:messages:2.0:ListResponse" | |
36 | + ], | |
37 | + "totalResults": counts.total, | |
38 | + "startIndex": counts.start_index, | |
39 | + "itemsPerPage": counts.limit, | |
40 | + "Resources": list_users(object) | |
41 | + } | |
42 | + end | |
43 | + | |
44 | + def list_users(users) | |
45 | + users.map do |user| | |
46 | + user_response(user) | |
47 | + end | |
48 | + end | |
49 | + | |
50 | + def user_response(user) | |
51 | + schema = ScimRails.config.user_schema | |
52 | + find_value(user, schema) | |
53 | + end | |
54 | + | |
55 | + def find_value(user, object) | |
56 | + case object | |
57 | + when Hash | |
58 | + object.each.with_object({}) do |(key, value), hash| | |
59 | + hash[key] = find_value(user, value) | |
60 | + end | |
61 | + when Array | |
62 | + object.map do |value| | |
63 | + find_value(user, value) | |
64 | + end | |
65 | + when Symbol | |
66 | + user.public_send(object) | |
67 | + else | |
68 | + object | |
69 | + end | |
5 | 70 | end |
6 | 71 | end |
7 | 72 | end | ... | ... |