-
Notifications
You must be signed in to change notification settings - Fork 180
/
hub.ex
724 lines (583 loc) · 24.9 KB
/
hub.ex
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
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
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
170
171
172
173
174
175
176
177
178
179
180
181
182
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
defmodule Ret.Hub.HubSlug do
use EctoAutoslugField.Slug, from: :name, to: :slug, always_change: true
def get_sources(_changeset, _opts) do
[:hub_sid, :name]
end
end
defmodule Ret.Hub do
use Ecto.Schema
use Bitwise
import Ecto.Changeset
import Ecto.Query
import Canada, only: [can?: 2]
alias Ret.{
Account,
Hub,
Repo,
Scene,
SceneListing,
WebPushSubscription,
RoomAssigner,
BitFieldUtils,
HubRoleMembership,
AppConfig
}
alias Ret.Hub.{HubSlug}
@schema_prefix "ret0"
@primary_key {:hub_id, :id, autogenerate: true}
@max_entry_code 999_999
@entry_code_expiration_hours 72
@max_entry_code_generate_attempts 25
@member_permissions %{
(1 <<< 0) => :spawn_and_move_media,
(1 <<< 1) => :spawn_camera,
(1 <<< 2) => :spawn_drawing,
(1 <<< 3) => :pin_objects,
(1 <<< 4) => :spawn_emoji,
(1 <<< 5) => :fly
}
@member_permissions_keys @member_permissions |> Map.values()
@default_member_permissions %{
spawn_and_move_media: true,
spawn_camera: true,
spawn_drawing: true,
pin_objects: true,
spawn_emoji: true,
fly: true
}
@default_restrictive_member_permissions %{
spawn_and_move_media: false,
spawn_camera: false,
spawn_drawing: false,
pin_objects: false,
spawn_emoji: false,
fly: false
}
def hub_preloads() do
[
scene: Scene.scene_preloads(),
scene_listing: [
:model_owned_file,
:screenshot_owned_file,
:scene_owned_file,
:project,
:account,
scene: Scene.scene_preloads()
],
web_push_subscriptions: [],
hub_bindings: [],
created_by_account: [],
hub_role_memberships: []
]
end
schema "hubs" do
field(:name, :string)
field(:description, :string)
field(:hub_sid, :string)
field(:host, :string)
field(:entry_code, :integer)
field(:entry_code_expires_at, :utc_datetime)
field(:last_active_at, :utc_datetime)
field(:creator_assignment_token, :string)
field(:embed_token, :string)
field(:embedded, :boolean)
field(:member_permissions, :integer)
field(:default_environment_gltf_bundle_url, :string)
field(:slug, HubSlug.Type)
field(:max_occupant_count, :integer, default: 0)
field(:spawned_object_types, :integer, default: 0)
field(:entry_mode, Ret.Hub.EntryMode)
field(:user_data, :map)
belongs_to(:scene, Ret.Scene, references: :scene_id)
belongs_to(:scene_listing, Ret.SceneListing, references: :scene_listing_id)
has_many(:web_push_subscriptions, Ret.WebPushSubscription, foreign_key: :hub_id)
belongs_to(:created_by_account, Ret.Account, references: :account_id)
has_many(:hub_invites, Ret.HubInvite, foreign_key: :hub_id)
has_many(:hub_bindings, Ret.HubBinding, foreign_key: :hub_id)
has_many(:hub_role_memberships, Ret.HubRoleMembership, foreign_key: :hub_id)
field(:allow_promotion, :boolean)
field(:room_size, :integer)
timestamps()
end
# Create new room, inserts into db
# returns newly created %Hub
def create_new_room(%{"name" => _name} = params, true = _add_to_db) do
scene_or_scene_listing = get_scene_or_scene_listing(params)
%Hub{}
|> changeset(scene_or_scene_listing, params)
|> Repo.insert()
end
# Create new room, does NOT insert into db
# returns newly created %Hub
def create_new_room(%{"name" => _name} = params, false = _add_to_db) do
scene_or_scene_listing = get_scene_or_scene_listing(params)
%Hub{}
|> changeset(scene_or_scene_listing, params)
end
defp get_scene_or_scene_listing(params) do
if is_nil(params["scene_id"]) do
SceneListing.get_random_default_scene_listing()
else
Scene.scene_or_scene_listing_by_sid(params["scene_id"])
end
end
def get_by_entry_code_string(entry_code_string) when is_binary(entry_code_string) do
case Integer.parse(entry_code_string) do
{entry_code, _} -> Hub |> Repo.get_by(entry_code: entry_code)
_ -> nil
end
end
def changeset(%Hub{} = hub, %Scene{} = scene, attrs) do
hub
|> changeset(nil, attrs)
|> put_assoc(:scene, scene)
end
def changeset(%Hub{} = hub, %SceneListing{} = scene_listing, attrs) do
hub
|> changeset(nil, attrs)
|> put_assoc(:scene_listing, scene_listing)
end
def changeset(%Hub{} = hub, nil, attrs) do
hub
|> cast(attrs, [:default_environment_gltf_bundle_url])
|> add_attrs_to_changeset(attrs)
|> add_hub_sid_to_changeset
|> add_generated_tokens_to_changeset
|> add_entry_code_to_changeset
|> add_default_member_permissions_to_changeset
|> unique_constraint(:hub_sid)
|> unique_constraint(:entry_code)
end
def add_attrs_to_changeset(changeset, attrs) do
changeset
|> cast(attrs, [:name, :description, :user_data, :room_size])
|> validate_required([:name])
|> validate_length(:name, max: 64)
|> validate_length(:description, max: 64_000)
|> validate_number(:room_size,
greater_than_or_equal_to: 0,
less_than_or_equal_to: AppConfig.get_cached_config_value("features|max_room_size")
)
|> HubSlug.maybe_generate_slug()
end
def member_permissions_from_attrs(%{} = attrs) do
attrs["member_permissions"] |> Map.new(fn {k, v} -> {String.to_atom(k), v} end) |> member_permissions_to_int
end
def add_member_permissions_update_to_changeset(changeset, hub, attrs) do
member_permissions =
Map.merge(member_permissions_for_hub(hub), attrs["member_permissions"])
|> Map.new(fn {k, v} -> {String.to_atom(k), v} end)
|> member_permissions_to_int
changeset
|> put_change(:member_permissions, member_permissions)
end
def add_member_permissions_to_changeset(changeset, attrs) do
member_permissions = attrs |> member_permissions_from_attrs
changeset
|> put_change(:member_permissions, member_permissions)
end
def maybe_add_promotion_to_changeset(changeset, account, hub, attrs) do
can_change_promotion = account |> can?(update_hub_promotion(hub))
if can_change_promotion, do: changeset |> add_promotion_to_changeset(attrs), else: changeset
end
def add_promotion_to_changeset(changeset, attrs) do
changeset |> put_change(:allow_promotion, !!attrs["allow_promotion"])
end
def add_entry_mode_to_changeset(changeset, attrs) do
changeset |> put_change(:entry_mode, attrs["entry_mode"])
end
def changeset_for_new_seen_occupant_count(%Hub{} = hub, occupant_count) do
new_max_occupant_count = max(hub.max_occupant_count, occupant_count)
hub
|> cast(%{max_occupant_count: new_max_occupant_count}, [:max_occupant_count])
|> maybe_add_last_active_at_to_changeset(occupant_count)
|> validate_required([:max_occupant_count])
end
def changeset_for_seen_embedded_hub(%Hub{} = hub), do: hub |> cast(%{embedded: true}, [:embedded])
# NOTE occupant_count is 1 when there is 1 *other* user in the room with you, so active is when >= 1.
defp maybe_add_last_active_at_to_changeset(changeset, occupant_count) when occupant_count >= 1,
do: changeset |> put_change(:last_active_at, Timex.now() |> DateTime.truncate(:second))
defp maybe_add_last_active_at_to_changeset(changeset, _), do: changeset
def changeset_for_new_scene(%Hub{} = hub, %Scene{} = scene) do
hub
|> change()
|> add_new_scene_to_changeset(scene)
end
def changeset_for_new_scene(%Hub{} = hub, %SceneListing{} = scene_listing) do
hub
|> change()
|> add_new_scene_to_changeset(scene_listing)
end
def add_new_scene_to_changeset(changeset, %Scene{} = scene) do
changeset
|> put_change(:scene_id, scene.scene_id)
|> put_change(:scene_listing_id, nil)
end
def add_new_scene_to_changeset(changeset, %SceneListing{} = scene_listing) do
changeset
|> put_change(:scene_listing_id, scene_listing.scene_listing_id)
|> put_change(:scene_id, nil)
end
def changeset_for_new_environment_url(%Hub{} = hub, url) do
hub
|> cast(%{default_environment_gltf_bundle_url: url}, [:default_environment_gltf_bundle_url])
|> validate_required([:default_environment_gltf_bundle_url])
|> put_change(:scene_id, nil)
|> put_change(:scene_listing_id, nil)
end
def changeset_for_new_spawned_object_type(%Hub{} = hub, object_type)
when object_type in 0..31 do
# spawned_object_types is a bitmask of the seen object types
new_spawned_object_types = hub.spawned_object_types ||| 1 <<< object_type
hub
|> cast(%{spawned_object_types: new_spawned_object_types}, [:spawned_object_types])
|> validate_required([:spawned_object_types])
end
def changeset_for_entry_mode(%Hub{} = hub, entry_mode),
do: hub |> cast(%{entry_mode: entry_mode}, [:entry_mode])
def changeset_for_new_host(%Hub{} = hub, host), do: hub |> cast(%{host: host}, [:host])
def changeset_for_creator_assignment(
%Ret.Hub{creator_assignment_token: expected_token} = hub,
account,
token
)
when expected_token != nil and expected_token == token do
hub |> change() |> add_account_to_changeset(account)
end
def changeset_for_creator_assignment(hub, _, _), do: hub |> change()
def add_account_to_changeset(changeset, nil), do: changeset
def add_account_to_changeset(changeset, %Account{} = account) do
changeset |> put_assoc(:created_by_account, account) |> put_change(:creator_assignment_token, nil)
end
def send_push_messages_for_join(%Hub{web_push_subscriptions: subscriptions} = hub, endpoint_to_skip \\ nil) do
body = hub |> push_message_for_join
for subscription <- subscriptions |> Enum.filter(&(&1.endpoint != endpoint_to_skip)) do
subscription |> WebPushSubscription.maybe_send(body)
end
end
defp push_message_for_join(%Hub{} = hub) do
%{type: "join", hub_name: hub.name, hub_id: hub.hub_sid, hub_url: hub |> url_for, image: hub |> image_url_for}
|> Poison.encode!()
end
def url_for(%Hub{} = hub) do
"#{RetWeb.Endpoint.url()}/#{hub.hub_sid}/#{hub.slug}"
end
def image_url_for(%Hub{scene: nil, scene_listing: nil}) do
"#{RetWeb.Endpoint.url()}/app-thumbnail.png"
end
def image_url_for(%Hub{scene: scene}) when scene != nil do
scene.screenshot_owned_file |> Ret.OwnedFile.uri_for() |> URI.to_string()
end
def image_url_for(%Hub{scene_listing: scene_listing}) when scene_listing != nil do
scene_listing.screenshot_owned_file |> Ret.OwnedFile.uri_for() |> URI.to_string()
end
def member_count_for(%Hub{hub_sid: hub_sid}), do: member_count_for(hub_sid)
def member_count_for(hub_sid) do
RetWeb.Presence.list("hub:#{hub_sid}")
|> Enum.filter(fn {_, %{metas: m}} ->
m |> Enum.any?(fn %{presence: p, context: c} -> p == :room and !(c != nil and Map.get(c, "discord", false)) end)
end)
|> Enum.count()
end
def lobby_count_for(%Hub{hub_sid: hub_sid}), do: lobby_count_for(hub_sid)
def lobby_count_for(hub_sid) do
RetWeb.Presence.list("hub:#{hub_sid}")
|> Enum.filter(fn {_, %{metas: m}} ->
m |> Enum.any?(fn %{presence: p, context: c} -> p == :lobby and !(c != nil and Map.get(c, "discord", false)) end)
end)
|> Enum.count()
end
def room_size_for(%Hub{} = hub) do
hub.room_size || AppConfig.get_cached_config_value("features|default_room_size")
end
defp changeset_for_new_entry_code(%Hub{} = hub) do
hub
|> Ecto.Changeset.change()
|> add_entry_code_to_changeset
end
def ensure_valid_entry_code!(hub) do
if hub |> entry_code_expired? do
hub |> changeset_for_new_entry_code |> Repo.update!()
else
hub
end
end
def ensure_host(hub) do
if RoomAssigner.is_alive?(hub.host) do
hub
else
# TODO the database mutation should be centralized into the GenServer
# to ensure a partition doesn't cause a rogue node to re-assign the server
host = RoomAssigner.get_available_host(hub.host)
if host && host != hub.host do
hub |> changeset_for_new_host(host) |> Repo.update!()
else
hub
end
end
end
def entry_code_expired?(%Hub{entry_code: entry_code, entry_code_expires_at: entry_code_expires_at})
when is_nil(entry_code) or is_nil(entry_code_expires_at),
do: true
def entry_code_expired?(%Hub{} = hub) do
Timex.now() |> Timex.after?(hub.entry_code_expires_at)
end
def vacuum_entry_codes do
Ret.Locking.exec_if_lockable(:hub_vacuum_entry_codes, fn ->
query = from(h in Hub, where: h.entry_code_expires_at() < ^Timex.now())
Repo.update_all(query, set: [entry_code: nil, entry_code_expires_at: nil])
end)
end
# Remove the host entry from any rooms that are older than a day old and have no presence
def vacuum_hosts do
Ret.Locking.exec_if_lockable(:hub_vacuum_hosts, fn ->
one_day_ago = Timex.now() |> Timex.shift(days: -1)
candidate_hub_sids =
from(h in Hub, where: not is_nil(h.host) and h.inserted_at < ^one_day_ago)
|> Repo.all()
|> Enum.map(& &1.hub_sid)
present_hub_sids = RetWeb.Presence.present_hub_sids()
clearable_hub_sids = candidate_hub_sids |> Enum.filter(&(!Enum.member?(present_hub_sids, &1)))
from(h in Hub, where: h.hub_sid in ^clearable_hub_sids) |> Repo.update_all(set: [host: nil])
end)
end
defp add_hub_sid_to_changeset(changeset) do
hub_sid = Ret.Sids.generate_sid()
changeset |> put_change(:hub_sid, hub_sid)
end
defp add_generated_tokens_to_changeset(changeset) do
creator_assignment_token = SecureRandom.hex()
embed_token = SecureRandom.hex()
changeset
|> put_change(:creator_assignment_token, creator_assignment_token)
|> put_change(:embed_token, embed_token)
end
defp add_entry_code_to_changeset(changeset) do
expires_at = Timex.now() |> Timex.shift(hours: @entry_code_expiration_hours) |> DateTime.truncate(:second)
changeset
|> put_change(:entry_code, generate_entry_code!())
|> put_change(:entry_code_expires_at, expires_at)
end
defp generate_entry_code!(attempt \\ 0)
defp generate_entry_code!(attempt) when attempt > @max_entry_code_generate_attempts do
raise "Unable to allocate entry code"
end
defp generate_entry_code!(attempt) do
candidate_entry_code = :rand.uniform(@max_entry_code)
case Hub |> Repo.get_by(entry_code: candidate_entry_code) do
nil -> candidate_entry_code
_ -> generate_entry_code!(attempt + 1)
end
end
def janus_room_id_for_hub(hub) do
# Cap to 53 bits of entropy because of Javascript :/
with <<room_id::size(53), _::size(11), _::binary>> <- :crypto.hash(:sha256, hub.hub_sid) do
room_id
end
end
def janus_port do
Application.get_env(:ret, Ret.JanusLoadStatus)[:janus_port]
end
def generate_turn_info do
if Ret.Coturn.enabled?() do
{username, credential} = Ret.Coturn.generate_credentials()
transports =
(Application.get_env(:ret, Ret.Coturn)[:public_tls_ports] || "5349")
|> String.split(",")
|> Enum.map(&%{port: &1 |> Integer.parse() |> elem(0)})
%{enabled: true, username: username, credential: credential, transports: transports}
else
%{enabled: false}
end
end
defp add_default_member_permissions_to_changeset(changeset) do
if Ret.AppConfig.get_config_bool("features|permissive_rooms") do
changeset |> put_change(:member_permissions, @default_member_permissions |> member_permissions_to_int)
else
changeset |> put_change(:member_permissions, @default_restrictive_member_permissions |> member_permissions_to_int)
end
end
def add_owner!(%Hub{created_by_account_id: created_by_account_id} = hub, %Account{account_id: account_id})
when created_by_account_id != nil and created_by_account_id === account_id,
do: hub
def add_owner!(%Hub{} = hub, %Account{} = account) do
Repo.get_by(HubRoleMembership, hub_id: hub.hub_id, account_id: account.account_id) ||
%HubRoleMembership{} |> HubRoleMembership.changeset(hub, account) |> Repo.insert!()
hub |> Repo.preload([hub_role_memberships: []], force: true)
end
def remove_owner!(%Hub{} = hub, %Account{} = account) do
case Repo.get_by(HubRoleMembership, hub_id: hub.hub_id, account_id: account.account_id) do
%HubRoleMembership{} = membership ->
membership |> Repo.delete!()
_ ->
nil
end
hub |> Repo.preload([hub_role_memberships: []], force: true)
end
def is_creator?(%Hub{created_by_account_id: created_by_account_id}, account_id)
when created_by_account_id != nil and created_by_account_id === account_id,
do: true
def is_creator?(_hub, _account), do: false
def is_owner?(%Hub{hub_role_memberships: hub_role_memberships} = hub, account_id) do
is_creator?(hub, account_id) || hub_role_memberships |> Enum.any?(&(&1.account_id === account_id))
end
def member_permissions_to_int(%{} = member_permissions) do
invalid_member_permissions = member_permissions |> Map.drop(@member_permissions_keys) |> Map.keys()
if invalid_member_permissions |> Enum.count() > 0 do
raise ArgumentError, "Invalid permissions #{invalid_member_permissions |> Enum.join(", ")}"
end
@member_permissions
|> Enum.reduce(0, fn {val, member_permission}, acc ->
if(member_permissions[member_permission], do: val, else: 0) + acc
end)
end
def has_member_permission?(%Hub{} = hub, member_permission) do
case @member_permissions
|> Enum.find(fn {_, member_permission_name} -> member_permission_name == member_permission end) do
nil -> raise ArgumentError, "Invalid permission #{member_permission}"
{val, _} -> (hub.member_permissions &&& val) > 0
end
end
def member_permissions_for_hub(%Hub{} = hub) do
hub.member_permissions
|> BitFieldUtils.permissions_to_map(@member_permissions)
|> Map.new(fn {k, v} -> {Atom.to_string(k), v} end)
end
# The account argument here can be a Ret.Account, a Ret.OAuthProvider or nil.
def perms_for_account(%Ret.Hub{} = hub, account) do
%{
join_hub: account |> can?(join_hub(hub)),
update_hub: account |> can?(update_hub(hub)),
update_hub_promotion: account |> can?(update_hub_promotion(hub)),
update_roles: account |> can?(update_roles(hub)),
close_hub: account |> can?(close_hub(hub)),
embed_hub: account |> can?(embed_hub(hub)),
kick_users: account |> can?(kick_users(hub)),
mute_users: account |> can?(mute_users(hub)),
spawn_camera: account |> can?(spawn_camera(hub)),
spawn_drawing: account |> can?(spawn_drawing(hub)),
spawn_and_move_media: account |> can?(spawn_and_move_media(hub)),
pin_objects: account |> can?(pin_objects(hub)),
spawn_emoji: account |> can?(spawn_emoji(hub)),
fly: account |> can?(fly(hub))
}
end
def roles_for_account(%Ret.Hub{}, nil),
do: %{owner: false, creator: false, signed_in: false}
def roles_for_account(%Ret.Hub{} = hub, account),
do: %{owner: hub |> is_owner?(account.account_id), creator: hub |> is_creator?(account.account_id), signed_in: true}
end
defimpl Canada.Can, for: Ret.Account do
alias Ret.{Hub, AppConfig}
@owner_actions [:update_hub, :close_hub, :embed_hub, :kick_users, :mute_users]
@object_actions [:spawn_and_move_media, :spawn_camera, :spawn_drawing, :pin_objects, :spawn_emoji, :fly]
@creator_actions [:update_roles]
# Always deny all actions to disabled accounts
def can?(%Ret.Account{state: :disabled}, _, _), do: false
# Always deny access to non-enterable hubs
def can?(%Ret.Account{}, :join_hub, %Ret.Hub{entry_mode: :deny}), do: false
def can?(%Ret.Account{} = account, :update_hub_promotion, %Ret.Hub{} = hub) do
owners_can_change_promotion = Ret.AppConfig.get_config_bool("features|public_rooms")
!!account.is_admin or (owners_can_change_promotion and can?(account, :update_hub, hub))
end
# Bound hubs - Join perm
def can?(%Ret.Account{} = account, :join_hub, %Ret.Hub{hub_bindings: hub_bindings})
when hub_bindings |> length > 0 do
hub_bindings |> Enum.any?(&(account |> Ret.HubBinding.member_of_channel?(&1)))
end
# Bound hubs - Manage actions
def can?(%Ret.Account{} = account, action, %Ret.Hub{hub_bindings: hub_bindings})
when action in [:update_hub, :close_hub] and hub_bindings |> length > 0 do
hub_bindings |> Enum.any?(&(account |> Ret.HubBinding.can_manage_channel?(&1)))
end
# Bound hubs - Moderator actions
def can?(%Ret.Account{} = account, action, %Ret.Hub{hub_bindings: hub_bindings})
when hub_bindings |> length > 0 and action in [:kick_users, :mute_users] do
hub_bindings |> Enum.any?(&(account |> Ret.HubBinding.can_moderate_users?(&1)))
end
# Bound hubs - Object permissions
def can?(%Ret.Account{} = account, action, %Ret.Hub{hub_bindings: hub_bindings} = hub)
when hub_bindings |> length > 0 and action in @object_actions do
is_moderator = hub_bindings |> Enum.any?(&(account |> Ret.HubBinding.can_moderate_users?(&1)))
if is_moderator do
true
else
is_member = hub_bindings |> Enum.any?(&(account |> Ret.HubBinding.member_of_channel?(&1)))
is_member and hub |> Hub.has_member_permission?(action)
end
end
# Bound hubs - Always prevent embedding and role assignment (since it's dictated by binding)
def can?(%Ret.Account{}, action, %Ret.Hub{hub_bindings: hub_bindings})
when hub_bindings |> length > 0 and action in [:embed_hub, :update_roles],
do: false
# Unbound hubs - Anyone can join an unbound hub
def can?(_account, :join_hub, %Ret.Hub{hub_bindings: []}), do: true
# Unbound hubs - Creator can perform creator actions
def can?(%Ret.Account{account_id: account_id}, action, %Ret.Hub{
created_by_account_id: created_by_account_id,
hub_bindings: []
})
when action in @creator_actions and created_by_account_id != nil and created_by_account_id == account_id,
do: true
# Unbound hubs - Owners can perform special actions
def can?(%Ret.Account{account_id: account_id}, action, %Ret.Hub{hub_bindings: []} = hub)
when action in @owner_actions,
do: hub |> Ret.Hub.is_owner?(account_id)
# Unbound hubs - Object actions can be performed if granted in member permissions or if account is an owner
def can?(%Ret.Account{account_id: account_id}, action, %Hub{hub_bindings: []} = hub) when action in @object_actions do
hub |> Hub.has_member_permission?(action) or hub |> Ret.Hub.is_owner?(account_id)
end
# Create hubs
def can?(%Ret.Account{is_admin: true}, :create_hub, _), do: true
def can?(_account, :create_hub, _),
do: !AppConfig.get_cached_config_value("features|disable_room_creation")
# Create accounts
def can?(%Ret.Account{is_admin: true}, :create_account, _), do: true
def can?(_account, :create_account, _), do: !AppConfig.get_cached_config_value("features|disable_sign_up")
# Deny permissions for any other case that falls through
def can?(_, _, _), do: false
end
# Perms for oauth users that do not have a hubs account
defimpl Canada.Can, for: Ret.OAuthProvider do
alias Ret.{AppConfig, Hub}
@object_actions [:spawn_and_move_media, :spawn_camera, :spawn_drawing, :pin_objects, :spawn_emoji, :fly]
@special_actions [:update_hub, :update_roles, :close_hub, :embed_hub, :kick_users, :mute_users]
# Always deny access to non-enterable hubs
def can?(%Ret.OAuthProvider{}, :join_hub, %Ret.Hub{entry_mode: :deny}), do: false
# OAuthProvider users cannot perform special actions
def can?(%Ret.OAuthProvider{}, action, %Ret.Hub{}) when action in @special_actions,
do: false
def can?(%Ret.OAuthProvider{} = oauth_provider, :join_hub, %Ret.Hub{hub_bindings: hub_bindings})
when hub_bindings |> length > 0 do
hub_bindings |> Enum.any?(&(oauth_provider |> Ret.HubBinding.member_of_channel?(&1)))
end
# Object permissions for OAuthProvider users are based on member permission settings
def can?(%Ret.OAuthProvider{} = oauth_provider, action, %Ret.Hub{hub_bindings: hub_bindings} = hub)
when action in @object_actions do
is_member = hub_bindings |> Enum.any?(&(oauth_provider |> Ret.HubBinding.member_of_channel?(&1)))
is_member and hub |> Hub.has_member_permission?(action)
end
def can?(_, :create_hub, _),
do: !AppConfig.get_cached_config_value("features|disable_room_creation")
def can?(_, _, _), do: false
end
# Permissions for un-authenticated clients
defimpl Canada.Can, for: Atom do
alias Ret.{AppConfig, Hub}
@object_actions [:spawn_and_move_media, :spawn_camera, :spawn_drawing, :pin_objects, :spawn_emoji, :fly]
# Always deny access to non-enterable hubs
def can?(_, :join_hub, %Ret.Hub{entry_mode: :deny}), do: false
# Anyone can join an unbound hub as long as accounts aren't required
def can?(_, :join_hub, %Ret.Hub{hub_bindings: []}),
do: !AppConfig.get_cached_config_value("features|require_account_for_join")
# Object permissions for anonymous users are based on member permission settings
def can?(_account, action, hub) when action in @object_actions do
hub |> Hub.has_member_permission?(action)
end
# Create hubs
def can?(_, :create_hub, _),
do: !AppConfig.get_cached_config_value("features|disable_room_creation")
# Create accounts
def can?(_, :create_account, _), do: !AppConfig.get_cached_config_value("features|disable_sign_up")
def can?(_, _, _), do: false
end