-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathstudy.rb
More file actions
2328 lines (2089 loc) · 85.5 KB
/
study.rb
File metadata and controls
2328 lines (2089 loc) · 85.5 KB
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
class Study
###
#
# Study: main object class for portal; stores information regarding study objects and references to FireCloud workspaces,
# access controls to viewing study objects, and also used as main parsing class for uploaded study files.
#
###
include Mongoid::Document
include Mongoid::Timestamps
extend ValidationTools
include Swagger::Blocks
include Mongoid::History::Trackable
# feature flag integration
include FeatureFlaggable
###
#
# FIRECLOUD METHODS
#
###
# prefix for FireCloud workspaces, defaults to blank in production
REQUIRED_ATTRIBUTES = %w(name)
MAX_EMBARGO = 2.years.freeze
###
#
# SETTINGS, ASSOCIATIONS AND SCOPES
#
###
# pagination
def self.per_page
10
end
# associations and scopes
belongs_to :user
has_and_belongs_to_many :branding_groups
has_many :authors, dependent: :delete_all do
def corresponding
where(corresponding: true)
end
end
accepts_nested_attributes_for :authors, allow_destroy: :true
has_many :publications, dependent: :delete_all do
def published
where(preprint: false)
end
end
accepts_nested_attributes_for :publications, allow_destroy: :true
has_many :study_files, dependent: :delete_all do
# all study files not queued for deletion
def available
where(queued_for_deletion: false)
end
def by_type(file_type)
if file_type.is_a?(Array)
available.where(:file_type.in => file_type).to_a
else
available.where(file_type: file_type).to_a
end
end
def non_primary_data
available.not_in(file_type: StudyFile::PRIMARY_DATA_TYPES).to_a
end
def primary_data
available.in(file_type: StudyFile::PRIMARY_DATA_TYPES).to_a
end
# all files that have been pushed to the bucket (will have the generation tag)
def valid
available.where(:generation.ne => nil).to_a
end
# includes links to external data which do not reside in the workspace bucket
def downloadable
available.where.any_of({ :generation.ne => nil }, { :human_fastq_url.ne => nil })
end
# all files not queued for deletion, ignoring newly built files
def persisted
available.reject(&:new_record?)
end
end
accepts_nested_attributes_for :study_files, allow_destroy: true
has_many :study_file_bundles, dependent: :destroy do
def by_type(file_type)
if file_type.is_a?(Array)
where(:bundle_type.in => file_type)
else
where(bundle_type: file_type)
end
end
end
has_many :genes do
def by_name_or_id(term, study_file_ids)
all_matches = any_of({name: term, :study_file_id.in => study_file_ids},
{searchable_name: term.downcase, :study_file_id.in => study_file_ids},
{gene_id: term, :study_file_id.in => study_file_ids})
if all_matches.empty?
[]
else
# since we can have duplicate genes but not cells, merge into one object for rendering
# allow for case-sensitive matching over case-insensitive
exact_matches = all_matches.select {|g| g.name == term}
if exact_matches.any?
data = exact_matches
else
# group by searchable name to find any possible case sensitivity issues, then uniquify by study_file_id
# this will drop any fuzzy matches caused by case insensitivity that would lead to merging genes
# that were intended to be unique
data = all_matches.group_by(&:searchable_name).values.map {|group| group.uniq(&:study_file_id)}.flatten
end
merged_scores = {'searchable_name' => data.first.searchable_name, 'name' => data.first.name, 'scores' => {}}
data.each do |score|
merged_scores['scores'].merge!(score.scores)
end
merged_scores
end
end
end
has_many :precomputed_scores do
def by_name(name)
where(name: name).first
end
end
has_many :dot_plot_genes, dependent: :delete_all
has_many :study_shares, dependent: :destroy do
def can_edit
where(permission: 'Edit').map(&:email)
end
def can_view
all.to_a.map(&:email)
end
def non_reviewers
where(:permission.nin => %w(Reviewer)).map(&:email)
end
def reviewers
where(permission: 'Reviewer').map(&:email)
end
def visible
if ApplicationController.read_only_firecloud_client.present?
readonly_issuer = ApplicationController.read_only_firecloud_client.issuer
where(:email.not => /#{readonly_issuer}/).map(&:email)
else
all.to_a.map(&:email)
end
end
end
accepts_nested_attributes_for :study_shares, allow_destroy: true, reject_if: proc { |attributes| attributes['email'].blank? }
has_many :cluster_groups do
def by_name(name)
find_by(name: name)
end
end
has_many :data_arrays, as: :linear_data do
def by_name_and_type(name, type)
where(name: name, array_type: type).order_by(&:array_index)
end
end
has_many :cell_metadata do
def by_name_and_type(name, type)
find_by(name: name, annotation_type: type)
end
end
has_many :directory_listings do
def unsynced
where(sync_status: false).to_a
end
# all synced directories, regardless of type
def are_synced
where(sync_status: true).to_a
end
# synced directories of a specific type
def synced_by_type(file_type)
where(sync_status: true, file_type: file_type).to_a
end
# primary data directories
def primary_data
where(sync_status: true, :file_type.in => DirectoryListing::PRIMARY_DATA_TYPES).to_a
end
# non-primary data directories
def non_primary_data
where(sync_status: true, :file_type.nin => DirectoryListing::PRIMARY_DATA_TYPES).to_a
end
end
# User annotations are per study
has_many :user_annotations
has_many :user_data_arrays
# Study Accession
has_one :study_accession
# External Resource links
has_many :external_resources, as: :resource_links, dependent: :destroy
accepts_nested_attributes_for :external_resources, allow_destroy: true
# DownloadAgreement (extra user terms for downloading data)
has_one :download_agreement, dependent: :delete_all
accepts_nested_attributes_for :download_agreement, allow_destroy: true
# Study Detail (full html description)
has_one :study_detail, dependent: :delete_all
accepts_nested_attributes_for :study_detail, allow_destroy: true
# Anonymous Reviewer Access
has_one :reviewer_access, dependent: :delete_all
accepts_nested_attributes_for :reviewer_access, allow_destroy: true
has_many :differential_expression_results, dependent: :delete_all do
def automated
where(:is_author_de.in => [nil, false])
end
def author
where(is_author_de: true)
end
end
# field definitions
field :name, type: String
field :embargo, type: Date
field :url_safe_name, type: String
field :accession, type: String
field :description, type: String
field :firecloud_workspace, type: String
field :firecloud_project, type: String, default: FireCloudClient::PORTAL_NAMESPACE
field :bucket_id, type: String
field :data_dir, type: String
field :public, type: Boolean, default: true
field :queued_for_deletion, type: Boolean, default: false
field :detached, type: Boolean, default: false # indicates whether workspace/bucket is missing
field :initialized, type: Boolean, default: false
field :view_count, type: Integer, default: 0
field :cell_count, type: Integer, default: 0
field :gene_count, type: Integer, default: 0
field :view_order, type: Float, default: 100.0
field :use_existing_workspace, type: Boolean, default: false
field :default_options, type: Hash, default: {} # extensible hash where we can put arbitrary values as 'defaults'
field :external_identifier, type: String # ID from external service, used for tracking via ImportService
field :imported_from, type: String # Human-readable tag for external service that study was imported from, e.g. HCA
field :duos_dataset_id, type: Integer
field :duos_study_id, type: Integer
##
#
# SWAGGER DEFINITIONS
#
##
swagger_schema :Study do
key :required, [:name]
key :name, 'Study'
property :id do
key :type, :string
end
property :name do
key :type, :string
key :description, 'Name of Study'
end
property :embargo do
key :type, :string
key :format, :date
key :description, 'Date used for restricting download access to StudyFiles in Study'
end
property :description do
key :type, :string
key :description, 'Plain text description blob for Study'
end
property :full_description do
key :type, :string
key :description, 'HTML description blob for Study (optional)'
end
property :url_safe_name do
key :type, :string
key :description, 'URL-encoded version of Study name'
end
property :accession do
key :type, :string
key :description, 'Accession (used in permalinks, not editable)'
end
property :firecloud_project do
key :type, :string
key :default, FireCloudClient::PORTAL_NAMESPACE
key :description, 'FireCloud billing project to which Study firecloud_workspace belongs'
end
property :firecloud_workspace do
key :type, :string
key :description, 'FireCloud workspace that corresponds to this Study'
end
property :use_existing_workspace do
key :type, :boolean
key :default, false
key :description, 'Boolean indication whether this Study used an existing FireCloud workspace when created'
end
property :bucket_id do
key :type, :string
key :description, 'GCS Bucket name where uploaded files are stored'
end
property :data_dir do
key :type, :string
key :description, 'Local directory where uploaded files are localized to (for parsing)'
end
property :public do
key :type, :boolean
key :default, true
key :description, 'Boolean indication of whether Study is publicly readable'
end
property :queued_for_deletion do
key :type, :boolean
key :default, false
key :description, 'Boolean indication whether Study is queued for garbage collection'
end
property :branding_group_id do
key :type, :string
key :description, 'ID of BrandingGroup to which Study belongs, if present'
end
property :initialized do
key :type, :boolean
key :default, false
key :description, 'Boolean indication of whether Study has at least one of all required StudyFile types parsed to enable visualizations (Expression Matrix, Metadata, Cluster)'
end
property :detached do
key :type, :boolean
key :default, false
key :description, 'Boolean indication of whether Study has been \'detached\' from its FireCloud workspace, usually when the workspace is deleted directly in FireCloud'
end
property :view_count do
key :type, :number
key :format, :integer
key :default, 0
key :description, 'Number of times Study has been viewed in the portal'
end
property :cell_count do
key :type, :number
key :format, :integer
key :default, 0
key :description, 'Number of unique cell names in Study (set from Metadata StudyFile)'
end
property :gene_count do
key :type, :number
key :format, :integer
key :default, 0
key :description, 'Number of unique gene names in Study (set from Expression Matrix or 10X Genes File)'
end
property :view_order do
key :type, :number
key :format, :float
key :default, 100.0
key :description, 'Number used to control sort order in which Studies are returned when searching/browsing'
end
property :default_options do
key :type, :object
key :default, {}
key :description, 'Key/Value storage of additional options'
end
property :created_at do
key :type, :string
key :format, :date_time
key :description, 'Creation timestamp'
end
property :updated_at do
key :type, :string
key :format, :date_time
key :description, 'Last update timestamp'
end
end
swagger_schema :StudyInput do
allOf do
schema do
property :study do
key :type, :object
property :name do
key :type, :string
key :description, 'Name of Study'
end
property :embargo do
key :type, :string
key :format, :date
key :description, 'Date used for restricting download access to StudyFiles in Study'
end
property :description do
key :type, :string
key :description, 'Plain text description blob for Study'
end
property :study_detail_attributes do
key :type, :object
property :full_description do
key :type, :string
key :description, 'HTML description blob for Study (optional)'
end
end
property :firecloud_project do
key :type, :string
key :default, FireCloudClient::PORTAL_NAMESPACE
key :description, 'FireCloud billing project to which Study firecloud_workspace belongs'
end
property :firecloud_workspace do
key :type, :string
key :description, 'FireCloud workspace that corresponds to this Study'
end
property :use_existing_workspace do
key :type, :boolean
key :default, false
key :description, 'Boolean indication whether this Study used an existing FireCloud workspace when created'
end
key :required, [:name]
end
end
end
end
swagger_schema :StudyUpdateInput do
allOf do
schema do
property :study do
key :type, :object
property :name do
key :type, :string
end
property :description do
key :type, :string
end
property :embargo do
key :type, :string
key :format, :date
key :description, 'Date used for restricting download access to StudyFiles in Study'
end
property :cell_count do
key :type, :number
key :format, :integer
key :default, 0
key :description, 'Number of unique cell names in Study (set from Metadata StudyFile)'
end
property :gene_count do
key :type, :number
key :format, :integer
key :default, 0
key :description, 'Number of unique gene names in Study (set from Expression Matrix or 10X Genes File)'
end
property :view_order do
key :type, :number
key :format, :float
key :default, 100.0
key :description, 'Number used to control sort order in which Studies are returned when searching/browsing'
end
property :study_detail_attributes do
key :type, :object
property :full_description do
key :type, :string
key :description, 'HTML description blob for Study (optional)'
end
end
property :default_options do
key :type, :object
key :default, {}
key :description, 'Key/Value storage of additional options'
end
property :branding_group_id do
key :type, :string
key :description, 'ID of branding group object to assign Study to (if present)'
end
key :required, [:name]
end
end
end
end
swagger_schema :SiteStudy do
property :name do
key :type, :string
key :description, 'Name of Study'
end
property :description do
key :type, :string
key :description, 'HTML description blob for Study'
end
property :accession do
key :type, :string
key :description, 'Accession (used in permalinks, not editable)'
end
property :public do
key :type, :boolean
key :default, true
key :description, 'Boolean indication of whether Study is publicly readable'
end
property :detached do
key :type, :boolean
key :default, false
key :description, 'Boolean indication of whether Study has been \'detached\' from its FireCloud workspace, usually when the workspace is deleted directly in FireCloud'
end
property :cell_count do
key :type, :number
key :format, :integer
key :default, 0
key :description, 'Number of unique cell names in Study (set from Metadata StudyFile)'
end
property :gene_count do
key :type, :number
key :format, :integer
key :default, 0
key :description, 'Number of unique gene names in Study (set from Expression Matrix or 10X Genes File)'
end
end
swagger_schema :SiteStudyWithFiles do
property :name do
key :type, :string
key :description, 'Name of Study'
end
property :description do
key :type, :string
key :description, 'Plain text description blob for Study'
end
property :full_description do
key :type, :string
key :description, 'HTML description blob for Study'
end
property :accession do
key :type, :string
key :description, 'Accession (used in permalinks, not editable)'
end
property :public do
key :type, :boolean
key :default, true
key :description, 'Boolean indication of whether Study is publicly readable'
end
property :detached do
key :type, :boolean
key :default, false
key :description, 'Boolean indication of whether Study has been \'detached\' from its FireCloud workspace, usually when the workspace is deleted directly in FireCloud'
end
property :cell_count do
key :type, :number
key :format, :integer
key :default, 0
key :description, 'Number of unique cell names in Study (set from Metadata StudyFile)'
end
property :gene_count do
key :type, :number
key :format, :integer
key :default, 0
key :description, 'Number of unique gene names in Study (set from Expression Matrix or 10X Genes File)'
end
property :study_files do
key :type, :array
key :description, 'Available StudyFiles for download/streaming'
items do
key :title, 'StudyFile'
key '$ref', 'SiteStudyFile'
end
end
property :directory_listings do
key :type, :array
key :description, 'Available Directories of files for bulk download'
items do
key :title, 'DirectoryListing'
key '$ref', 'DirectoryListingDownload'
end
end
property :publications do
key :type, :array
key :description, 'Available publications'
items do
key :title, 'Publication'
key '$ref', :PublicationInput
end
end
property :external_resources do
key :type, :array
key :description, 'Available external resource links'
items do
key :title, 'ExternalResource'
key '$ref', :ExternalResourceInput
end
end
end
swagger_schema :SearchStudyWithFiles do
property :name do
key :type, :string
key :description, 'Name of Study'
end
property :description do
key :type, :string
key :description, 'HTML description blob for Study'
end
property :accession do
key :type, :string
key :description, 'Accession (used in permalinks, not editable)'
end
property :public do
key :type, :boolean
key :default, true
key :description, 'Boolean indication of whether Study is publicly readable'
end
property :detached do
key :type, :boolean
key :default, false
key :description, 'Boolean indication of whether Study has been \'detached\' from its FireCloud workspace, usually when the workspace is deleted directly in FireCloud'
end
property :cell_count do
key :type, :number
key :format, :integer
key :default, 0
key :description, 'Number of unique cell names in Study (set from Metadata StudyFile)'
end
property :study_url do
key :type, :string
key :description, 'Relative URL path to view study'
end
property :facet_matches do
key :type, :object
key :description, 'SearchFacet filter matches'
end
property :term_matches do
key :type, :array
key :description, 'Keyword term matches'
items do
key :title, 'TermMatch'
key :type, :string
end
end
property :term_search_weight do
key :type, :integer
key :description, 'Relevance of term match'
end
property :inferred_match do
key :type, :boolean
key :description, 'Indication if match is inferred (e.g. converting facet filter value to keyword search)'
end
property :preset_match do
key :type, :boolean
key :description, 'Indication this study was included by a preset search'
end
property :gene_matches do
key :type, :array
key :description, 'Array of ids of the genes that were matched for this study'
items do
key :title, 'gene match'
key :type, :string
end
end
property :can_visualize_clusters do
key :type, :boolean
key :description, 'Whether this study has cluster visualization data available'
end
property :study_files do
key :type, :object
key :title, 'StudyFiles'
key :description, 'Available StudyFiles for download, by type'
StudyFile::BULK_DOWNLOAD_TYPES.each do |file_type|
property file_type do
key :description, "#{file_type} Files"
key :type, :array
items do
key :title, 'StudyFile'
key '$ref', 'SiteStudyFile'
end
end
end
end
end
###
#
# VALIDATIONS & CALLBACKS
#
###
# custom validator since we need everything to pass in a specific order (otherwise we get orphaned FireCloud workspaces)
validate :initialize_with_new_workspace, on: :create, if: Proc.new {|study| !study.use_existing_workspace && !study.detached}
validate :initialize_with_existing_workspace, on: :create, if: Proc.new {|study| study.use_existing_workspace}
# populate specific errors for associations since they share the same form
validate do |study|
%i[study_shares authors publications].each do |association_name|
study.send(association_name).each_with_index do |model, index|
next if model.valid?
model.errors.full_messages.each do |msg|
indicator = "#{index + 1}#{(index + 1).ordinal}"
errors.add(:base, "#{indicator} #{model.class} Error - #{msg}")
end
errors.delete(association_name) if errors[association_name].present?
end
end
# get errors for reviewer_access, if any
if study.reviewer_access.present? && !study.reviewer_access.valid?
study.reviewer_access.errors.full_messages.each do |msg|
errors.add(:base, msg)
end
end
end
# XSS protection
validate :strip_unsafe_characters_from_description
validates_format_of :name, with: ValidationTools::OBJECT_LABELS,
message: ValidationTools::OBJECT_LABELS_ERROR
validates_format_of :firecloud_workspace, :firecloud_project,
with: ValidationTools::ALPHANUMERIC_SPACE_DASH, message: ValidationTools::ALPHANUMERIC_SPACE_DASH_ERROR
validates_format_of :data_dir, :bucket_id, :url_safe_name,
with: ValidationTools::ALPHANUMERIC_DASH, message: ValidationTools::ALPHANUMERIC_DASH_ERROR
# update validators
validates_uniqueness_of :name, on: :update, message: ": %{value} has already been taken. Please choose another name."
validates_presence_of :name, on: :update
validates_uniqueness_of :url_safe_name, on: :update, message: ": The name you provided tried to create a public URL (%{value}) that is already assigned. Please rename your study to a different value."
validate :prevent_firecloud_attribute_changes, on: :update
validates_presence_of :firecloud_project, :firecloud_workspace
validates_uniqueness_of :external_identifier, allow_blank: true
validates :cell_count, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
validate :enforce_embargo_max_length
validate :check_user_org_on_private
###
# callbacks
before_validation :set_url_safe_name
before_validation :set_data_dir, :set_firecloud_workspace_name, on: :create
after_validation :assign_accession, on: :create
# before_save :verify_default_options
after_create :make_data_dir, :set_default_participant, :check_bucket_read_access, :log_study_creation
before_destroy :ensure_cascade_on_associations
after_destroy :remove_data_dir
before_save :set_readonly_access
after_update :log_study_state
# search definitions
index({"name" => "text", "description" => "text"}, {background: true})
index({accession: 1}, {unique: true})
###
#
# ACCESS CONTROL METHODS
#
###
# return all studies that are editable by a given user
def self.editable(user)
if user.admin?
self.where(queued_for_deletion: false)
else
studies = self.where(queued_for_deletion: false, user_id: user._id)
shares = StudyShare.where(email: /#{user.email}/i, permission: 'Edit').map(&:study).select {|s| !s.queued_for_deletion }
[studies + shares].flatten.uniq
end
end
# return all studies that are viewable by a given user as a Mongoid criterion
def self.viewable(user)
if user.nil?
self.where(queued_for_deletion: false, public: true)
elsif user.admin?
self.where(queued_for_deletion: false)
else
public = self.where(public: true, queued_for_deletion: false).map(&:id)
owned = self.where(user_id: user._id, public: false, queued_for_deletion: false).map(&:id)
shares = StudyShare.where(email: /#{user.email}/i).map(&:study).select {|s| !s.queued_for_deletion }.map(&:id)
group_shares = user.user_groups
intersection = public + owned + shares + group_shares
# return Mongoid criterion object to use with pagination
Study.in(:_id => intersection)
end
end
# return all studies either owned by or shared with a given user as a Mongoid criterion
def self.accessible(user, check_groups: true)
if user.admin?
self.where(queued_for_deletion: false)
else
owned = self.where(user_id: user._id, queued_for_deletion: false).map(&:_id)
shares = StudyShare.where(email: /#{user.email}/i).map(&:study).select {|s| !s.queued_for_deletion }.map(&:_id)
group_shares = check_groups ? user.user_groups : []
intersection = owned + shares + group_shares
Study.in(:_id => intersection)
end
end
# check if a give use can edit study
# check_groups can be set to false to skip checking group shares (for performance)
def can_edit?(user, check_groups: true)
if user.nil?
false
else
if admins.map(&:downcase).include?(user.email.downcase)
true
elsif check_groups
user_in_group_share?(user, 'Edit')
else
false
end
end
end
# google allows arbitrary periods in email addresses so if the email is a gmail account remove any excess periods
def remove_gmail_periods(email_address)
email_address = email_address.downcase
return email_address unless email_address.end_with?('gmail.com')
# sub out any periods with blanks, then replace the period for the '.com' at the end of the address
email_address = email_address.gsub('.', '').gsub(/com\z/, '.com')
end
# check if a given user can view study by share (does not take public into account - use Study.viewable(user) instead)
# check_groups can be set to false to skip checking group shares (for performance)
def can_view?(user, check_groups: true)
if user.nil?
false
else
# use if/elsif with explicit returns to ensure skipping downstream calls
if study_shares.can_view.map do |email_address|
remove_gmail_periods(email_address)
end.include?(remove_gmail_periods(user.email))
return true
elsif can_edit?(user, check_groups:)
return true
elsif check_groups
return user_in_group_share?(user, 'View', 'Reviewer')
end
end
false
end
# check if a user has access to a study's GCS bucket. will require View or Edit permission at the user or group level
def has_bucket_access?(user)
if user.nil?
false
else
if self.user == user
return true
elsif self.study_shares.non_reviewers.map(&:downcase).include?(user.email.downcase)
return true
else
self.user_in_group_share?(user, 'View', 'Edit')
end
end
end
# call Rawls to check bucket access for a given user (defaults to main service account)
# if a user should have access, but doesn't (403 response) then a FastPass request is issued to speed up the process
# this is mainly used as a proxy for synchronizing service account bucket access faster in non-default projects
def check_bucket_read_access(user: nil)
return nil if detached # exit for studies with no workspace
client = user ? FireCloudClient.new(user:) : FireCloudClient.new
client.check_bucket_read_access(firecloud_project, firecloud_workspace)
end
# always run :check_bucket_read_access in the background at lower priority
# can be invoked in the foreground with :check_bucket_read_access_without_delay
handle_asynchronously :check_bucket_read_access, priority: 10
# check if a user has permission do download data from this study (either is public and user is signed in, user is an admin, or user has a direct share)
def can_download?(user)
if self.public? && user.present?
return true
elsif user.present? && user.admin?
return true
else
self.has_bucket_access?(user)
end
end
# check if user can delete a study - only owners can
def can_delete?(user)
self.user_id == user.id || user.admin?
end
# check if a user can run workflows on the given study
def can_compute?(user)
if user.nil? || !user.registered_for_firecloud?
false
else
# don't check permissions if API is not 'ok'
if ApplicationController.firecloud_client.services_available?(FireCloudClient::SAM_SERVICE, FireCloudClient::RAWLS_SERVICE, FireCloudClient::AGORA_SERVICE)
begin
workspace_acl = ApplicationController.firecloud_client.get_workspace_acl(self.firecloud_project, self.firecloud_workspace)
if workspace_acl['acl'][user.email].nil?
# check if user has project-level permissions
user.is_billing_project_owner?(self.firecloud_project)
else
workspace_acl['acl'][user.email]['canCompute']
end
rescue => e
ErrorTracker.report_exception(e, user, { study: self.attributes.to_h})
Rails.logger.error "Unable to retrieve compute permissions for #{user.email}: #{e.message}"
false
end
else
false
end
end
end
# check if a user has access to a study via a user group
def user_in_group_share?(user, *permissions)
# check if api status is ok, otherwise exit without checking to prevent UI hanging on repeated calls
if user.registered_for_firecloud && ApplicationController.firecloud_client.services_available?(FireCloudClient::SAM_SERVICE, FireCloudClient::RAWLS_SERVICE, FireCloudClient::THURLOE_SERVICE)
group_shares = self.study_shares.keep_if {|share| share.is_group_share?}.select {|share| permissions.include?(share.permission)}.map(&:email)
# get user's groups via user.user_groups which includes token setting & error handling
user_groups = user.user_groups
# use native array intersection to determine if any of the user's groups have been shared with this study at the correct permission
(user_groups & group_shares).any?
else
false # if user is not registered for firecloud, default to false
end
end
# list of emails for accounts that can edit this study
def admins
[self.user.email, self.study_shares.can_edit, User.where(admin: true).pluck(:email)].flatten.uniq
end
# array of user accounts associated with this study (study owner + shares); can scope by permission, if provided
# differs from study.admins as it does not include portal admins
def associated_users(permission: nil)
owner = self.user
shares = permission.present? ? self.study_shares.where(permission: permission) : self.study_shares
share_users = shares.map { |share| User.find_by(email: /#{share.email}/i) }.compact
[owner] + share_users
end
# check if study is still under embargo or whether given user can bypass embargo
def embargoed?(user)
if user.nil?
embargo_active?
else
# must not be viewable by current user & embargoed to be true
!can_view?(user) && embargo_active?
end
end
# helper method to check embargo status
def embargo_active?
embargo.blank? ? false : Time.zone.today < embargo
end
def has_download_agreement?
self.download_agreement.present? ? !self.download_agreement.expired? : false
end
# label for study visibility
def visibility
self.public? ? "<span class='sc-badge bg-success text-success'>Public</span>".html_safe : "<span class='sc-badge bg-danger text-danger'>Private</span>".html_safe
end
# helper method to return key-value pairs of sharing permissions local to portal (not what is persisted in FireCloud)
# primarily used when syncing study with FireCloud workspace
def local_acl
acl = {
"#{self.user.email}" => (Rails.env.production? && FireCloudClient::COMPUTE_DENYLIST.include?(self.firecloud_project)) ? 'Edit' : 'Owner'
}
self.study_shares.each do |share|
acl["#{share.email}"] = share.permission
end
acl
end
# compute a simplistic relevance score by counting instances of terms in names/descriptions
def search_weight(terms)
weights = {
total: 0,
terms: {}
}
terms.each do |term|
author_names = authors.pluck(:first_name, :last_name, :institution).flatten.join(' ')
text_blob = "#{self.name} #{self.description} #{author_names}"
score = text_blob.scan(/#{::Regexp.escape(term)}/i).size
if score > 0
weights[:total] += score