-
Notifications
You must be signed in to change notification settings - Fork 444
/
Copy pathuser.rb
980 lines (779 loc) · 31.5 KB
/
user.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
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
require 'kconv'
require 'api_error'
class User < ApplicationRecord
include CanRenderModel
include Flipper::Identifier
# Keep in sync with states defined in db/schema.rb
STATES = ['unconfirmed', 'confirmed', 'locked', 'deleted', 'subaccount'].freeze
NOBODY_LOGIN = '_nobody_'.freeze
MAX_BIOGRAPHY_LENGTH_ALLOWED = 250
# disable validations because there can be users which don't have a bcrypt
# password yet. this is for backwards compatibility
has_secure_password validations: false
has_many :watched_items, dependent: :destroy
has_many :groups_users, inverse_of: :user
has_many :roles_users, inverse_of: :user
has_many :relationships, inverse_of: :user, dependent: :destroy
has_many :comments, dependent: :destroy, inverse_of: :user
has_many :status_messages
has_many :tokens, class_name: 'Token', dependent: :destroy, inverse_of: :executor, foreign_key: :executor_id
has_and_belongs_to_many :shared_workflow_tokens,
class_name: 'Token::Workflow',
join_table: :workflow_token_users,
association_foreign_key: :token_id,
dependent: :destroy,
inverse_of: :token_workflow
has_many :reviews, dependent: :nullify
has_many :event_subscriptions, inverse_of: :user
belongs_to :owner, class_name: 'User', optional: true
has_many :subaccounts, class_name: 'User', foreign_key: 'owner_id'
has_many :requests_created, foreign_key: 'creator', primary_key: :login, class_name: 'BsRequest'
# users have a n:m relation to group
has_and_belongs_to_many :groups, -> { distinct }
# users have a n:m relation to roles
has_and_belongs_to_many :roles, -> { distinct }
has_many :bs_request_actions_seen_by_users, dependent: :nullify
has_many :bs_request_actions_seen, through: :bs_request_actions_seen_by_users, source: :bs_request_action
has_one :ec2_configuration, class_name: 'Cloud::Ec2::Configuration', dependent: :destroy
has_one :azure_configuration, class_name: 'Cloud::Azure::Configuration', dependent: :destroy
has_many :upload_jobs, class_name: 'Cloud::User::UploadJob', dependent: :destroy
has_many :notifications, -> { order(created_at: :desc) }, as: :subscriber, dependent: :destroy
has_many :commit_activities
has_many :status_message_acknowledgements, dependent: :destroy
has_many :acknowledged_status_messages, through: :status_message_acknowledgements, class_name: 'StatusMessage', source: 'status_message'
has_many :disabled_beta_features, dependent: :destroy
has_many :reports, as: :reportable, dependent: :nullify
has_many :submitted_reports, class_name: 'Report'
has_many :moderated_comments, class_name: 'Comment', foreign_key: 'moderator_id'
has_many :decisions, foreign_key: 'moderator_id'
has_many :canned_responses, dependent: :destroy
scope :confirmed, -> { where(state: 'confirmed') }
scope :all_without_nobody, -> { where.not(login: NOBODY_LOGIN) }
scope :not_deleted, -> { where.not(state: 'deleted') }
scope :not_locked, -> { where.not(state: 'locked') }
scope :with_login_prefix, ->(prefix) { where('login LIKE ?', "#{prefix}%") }
scope :active, -> { confirmed.or(User.unscoped.where(state: :subaccount, owner: User.unscoped.confirmed)) }
scope :staff, -> { joins(:roles).where('roles.title' => 'Staff') }
scope :not_staff, -> { where.not(id: User.unscoped.staff.pluck(:id)) }
scope :admins, -> { joins(:roles).where('roles.title' => 'Admin') }
scope :moderators, -> { joins(:roles).where('roles.title' => 'Moderator') }
scope :in_beta, -> { where(in_beta: true) }
scope :in_rollout, -> { where(in_rollout: true) }
scope :list, lambda {
all_without_nobody.includes(:owner).select(:id, :login, :email, :state, :realname, :owner_id, :updated_at, :ignore_auth_services)
}
scope :with_email, -> { where.not(email: [nil, '']) }
scope :seen_since, ->(since) { where('last_logged_in_at > ?', since) }
validates :login, :state, presence: { message: 'must be given' }
validates :login,
uniqueness: { case_sensitive: true, message: 'is the name of an already existing user' }
validates :login,
format: { with: /\A[\w $\^\-.#*+&'"]*\z/,
message: 'must not contain invalid characters' }
validates :login,
length: { in: 2..100, allow_nil: true,
too_long: 'must have less than 100 characters',
too_short: 'must have more than two characters' }
validates :state, inclusion: { in: STATES }
validate :validate_state
# We want a valid email address. Note that the checking done here is very
# rough. Email adresses are hard to validate now domain names may include
# language specific characters and user names can be about anything anyway.
# However, this is not *so* bad since users have to answer on their email
# to confirm their registration.
validates :email,
format: { with: /\A([\w\-.\#$%&!?*'+=(){}|~]+)@([0-9a-zA-Z\-.\#$%&!?*'=(){}|~]+)+\z/,
message: 'must be a valid email address',
allow_blank: true }
# we disabled has_secure_password's validations. therefore we need to do manual validations
validate :password_validation
validates :password, length: { minimum: 6, maximum: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED }, allow_nil: true
validates :password, confirmation: true, allow_blank: true
validates :biography, length: { maximum: MAX_BIOGRAPHY_LENGTH_ALLOWED }
validates :rss_secret, uniqueness: true, length: { maximum: 200 }, allow_blank: true
after_create :create_home_project, :measure_create
after_update :measure_delete
def create_home_project
# avoid errors during seeding
return if login.in?([NOBODY_LOGIN, 'Admin'])
# may be disabled via Configuration setting
return unless can_create_project?(home_project_name)
# find or create the project
project = Project.find_by(name: home_project_name)
return if project
project = Project.create!(name: home_project_name)
project.commit_user = self
# make the user maintainer
project.relationships.create!(user: self, role: Role.find_by_title('maintainer'))
project.store
@home_project = project
end
# Inform ActiveModel::Dirty that changes are persistent now
after_save :changes_applied
# When a record object is initialized, we set the state and the login failure
# count to unconfirmed/0 when it has not been set yet.
before_validation(on: :create) do
self.state ||= 'unconfirmed'
# Set the last login time etc. when the record is created at first.
self.last_logged_in_at = Time.zone.today
self.login_failure_count = 0 if login_failure_count.nil?
end
def self.autocomplete_token(prefix = '')
autocomplete_login(prefix).collect { |user| { name: user } }
end
def self.autocomplete_login(prefix = '')
AutocompleteFinder::User.new(User.not_deleted.not_locked, prefix).call.pluck(:login)
end
# the default state of a user based on the api configuration
def self.default_user_state
::Configuration.registration == 'confirmation' ? 'unconfirmed' : 'confirmed'
end
def self.create_user_with_fake_pw!(attributes = {})
create!(attributes.merge(password: SecureRandom.base64(48)))
end
def self.create_ldap_user(attributes = {})
user = create_user_with_fake_pw!(attributes.merge(state: default_user_state, adminnote: 'User created via LDAP'))
return user if user.errors.empty?
logger.info("Cannot create ldap userid: '#{login}' on OBS. Full log: #{user.errors.full_messages.to_sentence}")
nil
end
# This static method tries to find a user with the given login and password
# in the database. Returns the user or nil if they could not be found
def self.find_with_credentials(login, password)
return find_with_credentials_via_ldap(login, password) if CONFIG['ldap_mode'] == :on
user = find_by_login(login)
user.try(:authenticate_via_password, password)
end
def self.find_with_credentials_via_ldap(login, password)
user = find_by_login(login)
ldap_info = nil
return user.authenticate_via_password(password) if user.try(:ignore_auth_services?)
if CONFIG['ldap_mode'] == :on
begin
require 'ldap'
logger.debug("Using LDAP to find #{login}")
ldap_info = UserLdapStrategy.find_with_ldap(login, password)
rescue LoadError
logger.warn "ldap_mode selected but 'ruby-ldap' module not installed."
rescue StandardError
logger.debug "#{login} not found in LDAP."
end
end
return unless ldap_info
# We've found an ldap authenticated user - find or create an OBS userDB entry.
if user
# Check for ldap updates
user.assign_attributes(email: ldap_info[0], realname: ldap_info[1])
user.save if user.changed?
else
logger.debug('No user found in database, creating')
logger.debug("Email: #{ldap_info[0]}")
logger.debug("Name : #{ldap_info[1]}")
user = create_ldap_user(login: login, email: ldap_info[0], realname: ldap_info[1])
end
user.mark_login!
user
end
# Currently logged in user or nobody user if there is no user logged in.
# Use this to check permissions, but don't treat it as logged in user. Check
# is_nobody? on the returned object
def self.possibly_nobody
current || nobody
end
# Currently logged in user. Will throw an exception if no user is logged in.
# So the controller needs to require login if using this (or models using it)
def self.session!
raise ArgumentError, 'Requiring user, but found nobody' unless session
current
end
# Currently logged in user or nil
def self.session
current if current && !current.is_nobody?
end
def self.admin_session?
current && current.is_admin?
end
# set the user as current session user (should be real user)
def self.session=(user)
Thread.current[:user] = user
end
def self.get_default_admin
admin = CONFIG['default_admin'] || 'Admin'
user = User.find_by!(login: admin)
raise NotFoundError, "Admin not found, user #{admin} has not admin permissions" unless user.is_admin?
user
end
def self.find_nobody!
User.create_with(email: 'nobody@localhost',
realname: 'Anonymous User',
state: 'locked',
password: '123456').find_or_create_by(login: NOBODY_LOGIN)
end
def self.find_by_login!(login)
user = not_deleted.find_by(login: login)
return user if user
raise NotFoundError, "Couldn't find User with login = #{login}"
end
# some users have last_logged_in_at empty
def last_logged_in_at
self[:last_logged_in_at] || created_at
end
def away?
last_logged_in_at < 3.months.ago
end
def authenticate_via_password(password)
if authenticate(password)
mark_login!
self
else
count_login_failure
nil
end
end
def validate_state
# check that the state transition is valid
errors.add(:state, 'must be a valid new state from the current state') unless state_transition_allowed?(state_was, state)
end
# This method returns true if the user is assigned the role with one of the
# role titles given as parameters. False otherwise.
def has_role?(*role_titles)
obj = all_roles.detect do |role|
role_titles.include?(role.title)
end
!obj.nil?
end
# This method checks whether the given value equals the password when
# hashed with this user's password hash type. Returns a boolean.
def deprecated_password_equals?(value)
hash_string(value) == deprecated_password
end
def authenticate(unencrypted_password)
# for users without a bcrypt password we need an extra check and convert
# the password to a bcrypt one
if deprecated_password
if deprecated_password_equals?(unencrypted_password)
update(password: unencrypted_password, deprecated_password: nil, deprecated_password_salt: nil, deprecated_password_hash_type: nil)
return self
end
return false
end
# it seems that the user is not using a deprecated password so we use bcrypt's
# #authenticate method
super
end
# Returns true if the the state transition from "from" state to "to" state
# is valid. Returns false otherwise.
#
# Note that currently no permission checking is included here; It does not
# matter what permissions the currently logged in user has, only that the
# state transition is legal in principle.
def state_transition_allowed?(from, to)
from = from.to_i
to = to.to_i
return true if from == to # allow keeping state
case from
when 'unconfirmed'
true
when 'confirmed'
to.in?(['locked', 'deleted'])
when 'locked'
to.in?(['confirmed', 'deleted'])
when 'deleted'
to == 'confirmed'
else
false
end
end
def cloud_configurations?
ec2_configuration.present? || azure_configuration.present?
end
def to_axml(_opts = {})
render_axml
end
def render_axml(watchlist = false, render_watchlist_only: false)
# CanRenderModel
render_xml(watchlist: watchlist, render_watchlist_only: render_watchlist_only)
end
def home_project_name
"home:#{login}"
end
def home_project
@home_project ||= Project.find_by(name: home_project_name)
end
def branch_project_name(branch)
"#{home_project_name}:branches:#{branch}"
end
#####################
# permission checks #
#####################
def is_admin?
return @is_admin unless @is_admin.nil?
@is_admin = roles.exists?(title: 'Admin')
end
def is_staff?
return @is_staff unless @is_staff.nil?
@is_staff = roles.exists?(title: 'Staff')
end
def is_nobody?
login == NOBODY_LOGIN
end
def is_moderator?
roles.exists?(title: 'Moderator')
end
def is_active?
return owner.is_active? if owner
self.state == 'confirmed'
end
def is_in_group?(group)
case group
when String
group = Group.find_by_title(group)
when Integer
group = Group.find(group)
when Group, nil
nil
else
raise ArgumentError, "illegal parameter type to User#is_in_group?: #{group.class}"
end
group && lookup_strategy.is_in_group?(self, group)
end
# This method returns true if the user is granted the permission with one
# of the given permission titles.
def has_global_permission?(perm_string)
logger.debug "has_global_permission? #{perm_string}"
roles.detect do |role|
return true if role.static_permissions.find_by(title: perm_string)
end
end
# FIXME: This should be a policy
def can_modify?(object, ignore_lock = nil)
case object
when Project
can_modify_project?(object, ignore_lock)
when Package
can_modify_package?(object, ignore_lock)
when nil
false
else
raise ArgumentError, "Wrong type of object: '#{object.class}' instead of Project or Package."
end
end
# FIXME: This should be a policy
# project is instance of Project
def can_modify_project?(project, ignore_lock = nil)
raise ArgumentError, "illegal parameter type to User#can_modify_project?: #{project.class.name}" unless project.is_a?(Project)
if project.new_record?
# Project.check_write_access(!) should have been used?
raise NotFoundError, 'Project is not stored yet'
end
can_modify_project_internal(project, ignore_lock)
end
# FIXME: This should be a policy
# package is instance of Package
def can_modify_package?(package, ignore_lock = nil)
return false if package.nil? # happens with remote packages easily
raise ArgumentError, "illegal parameter type to User#can_modify_package?: #{package.class.name}" unless package.is_a?(Package)
return false if !ignore_lock && package.is_locked?
return true if is_admin?
return true if has_global_permission?('change_package')
return true if has_local_permission?('change_package', package)
false
end
# FIXME: This should be a policy
def can_modify_user?(user)
is_admin? || self == user
end
# FIXME: This should be a policy
# project_name is name of the project
def can_create_project?(project_name)
## special handling for home projects
return true if project_name == home_project_name && Configuration.allow_user_to_create_home_project
return true if /^#{home_project_name}:/ =~ project_name && Configuration.allow_user_to_create_home_project
return true if has_global_permission?('create_project')
parent_project = Project.new(name: project_name).parent
return false if parent_project.nil?
return true if is_admin?
has_local_permission?('create_project', parent_project)
end
# FIXME: This should be a policy
def can_modify_attribute_definition?(object)
can_create_attribute_definition?(object)
end
def attribute_modifier_rule_matches?(rule)
return false if rule.user && rule.user != self
return false if rule.group && !is_in_group?(rule.group)
true
end
# FIXME: This should be a policy
def can_create_attribute_definition?(object)
object = object.attrib_namespace if object.is_a?(AttribType)
raise ArgumentError, "illegal parameter type to User#can_change?: #{object.class.name}" unless object.is_a?(AttribNamespace)
return true if is_admin?
abies = object.attrib_namespace_modifiable_bies.includes([:user, :group])
abies.any? { |rule| attribute_modifier_rule_matches?(rule) }
end
def attribute_modification_rule_matches?(rule, object)
return false unless attribute_modifier_rule_matches?(rule)
return false if rule.role && !has_local_role?(rule.role, object)
true
end
# FIXME: This should be a policy
def can_create_attribute_in?(object, atype)
raise ArgumentError, "illegal parameter type to User#can_change?: #{object.class.name}" if !object.is_a?(Project) && !object.is_a?(Package)
return true if is_admin?
abies = atype.attrib_type_modifiable_bies.includes([:user, :group, :role])
# no rules -> maintainer
return can_modify?(object) if abies.empty?
abies.any? { |rule| attribute_modification_rule_matches?(rule, object) }
end
# FIXME: This should be a policy
def can_download_binaries?(package)
can?(:download_binaries, package)
end
# FIXME: This should be a policy
def can_source_access?(package)
can?(:source_access, package)
end
# FIXME: This should be a policy
def can?(key, package)
is_admin? ||
has_global_permission?(key.to_s) ||
has_local_permission?(key.to_s, package)
end
def has_local_role?(role, object)
if object.is_a?(Package) || object.is_a?(Project)
logger.debug "running local role package check: user #{login}, package #{object.name}, role '#{role.title}'"
rels = object.relationships.where(role_id: role.id, user_id: id)
return true if rels.exists?
rels = object.relationships.joins(:groups_users).where(groups_users: { user_id: id }).where(role_id: role.id)
return true if rels.exists?
return true if lookup_strategy.local_role_check(role, object)
end
return has_local_role?(role, object.project) if object.is_a?(Package)
false
end
# local permission check
# if context is a package, check permissions in package, then if needed continue with project check
# if context is a project, check it, then if needed go down through all namespaces until hitting the root
# return false if none of the checks succeed
# rubocop:disable Metrics/PerceivedComplexity
def has_local_permission?(perm_string, object)
roles = Role.ids_with_permission(perm_string)
return false unless roles
parent = nil
case object
when Package
logger.debug "running local permission check: user #{login}, package #{object.name}, permission '#{perm_string}'"
# check permission for given package
parent = object.project
# Users have permissions to manage packages in their own home project
# This is needed since users sometimes remove themselves from the maintainers of their own home project
return true if parent.name == home_project_name
when Project
logger.debug "running local permission check: user #{login}, project #{object.name}, permission '#{perm_string}'"
# Users have permissions to manage their own home project
# This is needed since users sometimes remove themselves from the maintainers of their own home project
return true if object.name == home_project_name
# check permission for given project
parent = object.parent
when nil
return has_global_permission?(perm_string)
else
return false
end
rel = object.relationships.where(user_id: id).where(role_id: roles)
return true if rel.exists?
rel = object.relationships.joins(:groups_users).where(groups_users: { user_id: id }).where(role_id: roles)
return true if rel.exists?
return true if lookup_strategy.local_permission_check(roles, object)
if parent
# check permission of parent project
logger.debug "permission not found, trying parent project '#{parent.name}'"
return has_local_permission?(perm_string, parent)
end
false
end
# rubocop:enable Metrics/PerceivedComplexity
def lock!
self.state = 'locked'
save!
# lock also all home projects to avoid unneccessary builds
Project.where('name like ?', "#{home_project_name}%").find_each do |prj|
next if prj.is_locked?
prj.lock('User account got locked')
end
end
def delete
delete!
rescue ActiveRecord::RecordInvalid
false
end
def delete!(adminnote: nil)
# remove user data as much as possible
# but we must NOT remove the information that the account did exist
# or another user could take over the identity which can open security
# issues (other infrastructur and systems using repositories)
self.adminnote = adminnote if adminnote.present?
self.email = ''
self.realname = ''
self.state = 'deleted'
comments.destroy_all
save!
# wipe also all home projects
destroy_home_projects(reason: 'User account got deleted')
true
end
def destroy_home_projects(reason:)
Project.where('name LIKE ?', "#{home_project_name}:%").or(Project.where(name: home_project_name)).find_each do |project|
project.commit_opts = { comment: "#{reason}" }
project.destroy
end
end
def involved_projects
Project.for_user(id).or(Project.for_group(group_ids))
end
# lists packages maintained by this user and are not in maintained projects
def involved_packages
Package.for_user(id).or(Package.for_group(group_ids)).where.not(project: involved_projects)
end
# list packages owned by this user.
def owned_packages
owned = []
begin
OwnerSearch::Owned.new.for(self).each do |owner|
owned << [owner.package, owner.project]
end
rescue APIError # no attribute set
end
owned
end
# lists reviews involving this user
def involved_reviews(search = nil)
result = BsRequest.by_user_reviews(id).or(
BsRequest.by_project_reviews(involved_projects).or(
BsRequest.by_package_reviews(involved_packages).or(
BsRequest.by_group_reviews(groups)
)
)
).with_actions_and_reviews.where(state: :review, reviews: { state: :new }).where.not(creator: login)
search.present? ? result.do_search(search) : result
end
# list requests involving this user
def declined_requests(search = nil)
result = requests_created.in_states(:declined).with_actions
search.present? ? result.do_search(search) : result
end
# list incoming requests involving this user
def incoming_requests(search = nil, all_states: false)
states = all_states ? BsRequest::VALID_REQUEST_STATES : [:new]
result = BsRequest.where(id: BsRequestAction.bs_request_ids_of_involved_projects(involved_projects)).or(
BsRequest.where(id: BsRequestAction.bs_request_ids_of_involved_packages(involved_packages))
).with_actions.in_states(states)
search.present? ? result.do_search(search) : result
end
# list outgoing requests involving this user
def outgoing_requests(search = nil, all_states: false)
states = all_states ? BsRequest::VALID_REQUEST_STATES : [:new, :review]
result = requests_created.in_states(states).with_actions
search.present? ? result.do_search(search) : result
end
# list of all requests
def requests(search = nil)
project_ids = involved_projects
package_ids = involved_packages
actions = BsRequestAction.bs_request_ids_of_involved_projects(project_ids).or(
BsRequestAction.bs_request_ids_of_involved_packages(package_ids)
)
reviews = Review.bs_request_ids_of_involved_users(id).or(
Review.bs_request_ids_of_involved_projects(project_ids).or(
Review.bs_request_ids_of_involved_packages(package_ids).or(
Review.bs_request_ids_of_involved_groups(groups)
)
)
).where(state: :new)
result = BsRequest.where(creator: login).or(
BsRequest.where(id: actions).or(
BsRequest.where(id: reviews)
)
).with_actions
search.present? ? result.do_search(search) : result
end
# TODO: This should be in a query object
def involved_patchinfos
@involved_patchinfos ||= Package.joins(:issues).includes({ issues: :issue_tracker }, :package_kinds, :project)
.where(issues: { state: 'OPEN', owner_id: id },
package_kinds: { kind: 'patchinfo' })
.distinct
end
def user_relevant_packages_for_status
MaintainedPackagesByUserFinder.new(self).call.pluck(:id)
end
def state
return owner.state if owner
self[:state]
end
def to_s
login
end
def to_param
to_s
end
def tasks
Rails.cache.fetch("requests_for_#{cache_key_with_version}") do
declined_requests.count +
incoming_requests.count +
involved_reviews.count
end
end
def unread_notifications
NotificationsFinder.new(notifications.for_web).unread.size
end
def update_globalroles(global_roles)
roles.replace(global_roles + roles.where(global: false))
end
def add_globalrole(global_role)
update_globalroles(global_role + roles.global)
end
def display_name
address = Mail::Address.new(email)
address.display_name = realname
address.format
end
def name
realname.presence || login
end
def combined_rss_feed_items
Notification.for_rss.where(subscriber: self).or(
Notification.for_rss.where(subscriber: groups)
).order(created_at: :desc, id: :desc).limit(Notification::MAX_RSS_ITEMS_PER_USER)
end
def mark_login!
update(last_logged_in_at: Time.zone.today, login_failure_count: 0)
end
def count_login_failure
update(login_failure_count: login_failure_count + 1)
end
def proxy_realname(env)
return unless env['HTTP_X_FIRSTNAME'].present? && env['HTTP_X_LASTNAME'].present?
env['HTTP_X_FIRSTNAME'].force_encoding('UTF-8') + ' ' + env['HTTP_X_LASTNAME'].force_encoding('UTF-8')
end
def update_login_values(env)
# updates user's email and real name using data transmitted by authentication proxy
self.email = env['HTTP_X_EMAIL'] if env['HTTP_X_EMAIL'].present?
self.realname = proxy_realname(env) if proxy_realname(env)
self.last_logged_in_at = Time.zone.today
self.login_failure_count = 0
if changes.any?
logger.info "updating email for user #{login} from proxy header: old:#{email}|new:#{env['HTTP_X_EMAIL']}" if changes.key?('email')
# At this point some login value changed, so a successful log in is tracked
RabbitmqBus.send_to_bus('metrics', 'login,access_point=webui value=1')
end
save
end
def run_as
before = User.session
begin
User.session = self
yield
ensure
User.session = before
end
end
def watched_requests
BsRequest.where(id: watched_items.where(watchable_type: 'BsRequest').pluck(:watchable_id)).order('number DESC')
end
def watched_packages
Package.where(id: watched_items.where(watchable_type: 'Package').pluck(:watchable_id)).order('LOWER(name), name')
end
def watched_projects
Project.where(id: watched_items.where(watchable_type: 'Project').pluck(:watchable_id)).order('LOWER(name), name')
end
# Can't use ActiveRecord::SecureToken because we don't want User to have
# a rss_secret by default. We want to skip creating Notification for the
# RSS channel if people don't use it.
def regenerate_rss_secret
update!(rss_secret: SecureRandom.base58(24))
end
private
def measure_create
RabbitmqBus.send_to_bus('metrics', 'user.create value=1')
end
def measure_delete
return unless saved_change_to_attribute?('state', to: 'deleted')
RabbitmqBus.send_to_bus('metrics', 'user.delete value=1')
end
# The currently logged in user (might be nil). It's reset after
# every request and normally set during authentification
def self.current
Thread.current[:user]
end
private_class_method :current
def self.nobody
Thread.current[:nobody] ||= find_nobody!
end
private_class_method :nobody
def password_validation
return if password_digest || deprecated_password
errors.add(:password, 'can\'t be blank')
end
# FIXME: This should be a policy
def can_modify_project_internal(project, ignore_lock)
# The ordering is important because of the lock status check
return false if !ignore_lock && project.is_locked?
return true if is_admin?
return true if has_global_permission?('change_project')
return true if has_local_permission?('change_project', project)
false
end
# Hashes the given parameter by the selected hashing method. It uses the
# "password_salt" property's value to make the hashing more secure.
def hash_string(value)
crypt2index = { 'md5crypt' => 1,
'sha256crypt' => 5 }
if deprecated_password_hash_type == 'md5'
Digest::MD5.hexdigest(value + deprecated_password_salt)
elsif crypt2index.key?(deprecated_password_hash_type)
value.crypt("$#{crypt2index[deprecated_password_hash_type]}$#{deprecated_password_salt}$").split('$')[3]
end
end
cattr_accessor :lookup_strategy do
@@lstrategy = if Configuration.ldapgroup_enabled?
UserLdapStrategy.new
else
UserBasicStrategy.new
end
end
end
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# adminnote :text(65535)
# biography :string(255) default("")
# deprecated_password :string(255) indexed
# deprecated_password_hash_type :string(255)
# deprecated_password_salt :string(255)
# email :string(200) default(""), not null
# ignore_auth_services :boolean default(FALSE)
# in_beta :boolean default(FALSE), indexed
# in_rollout :boolean default(TRUE), indexed
# last_logged_in_at :datetime
# login :text(65535) indexed
# login_failure_count :integer default(0), not null
# password_digest :string(255)
# realname :string(200) default(""), not null
# rss_secret :string(200) indexed
# state :string default("unconfirmed")
# created_at :datetime
# updated_at :datetime
# owner_id :integer
#
# Indexes
#
# index_users_on_in_beta (in_beta)
# index_users_on_in_rollout (in_rollout)
# index_users_on_rss_secret (rss_secret) UNIQUE
# users_login_index (login) UNIQUE
# users_password_index (deprecated_password)
#