-
Notifications
You must be signed in to change notification settings - Fork 73
/
user.rb
532 lines (402 loc) · 13.7 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
require 'digest/sha1'
class User < ApplicationRecord
def self.columns
super.reject { |c| c.name == "janrain_identifier" }
end
include Fields::Fields
required_fields_are :username, :email
optional_fields_are :title, :first_name, :last_name, :job_role
set_fields_account_source :account
include Authentication
include Authentication::ByPassword
include Authentication::ByCookieToken
include CrossDomainSessions
include Roles
include States
include Invitations
include Permissions
include ProvidedAccessTokens
audited sensitive_attributes: %i[crypted_password salt activation_code lost_password_token password_digest]
before_validation :trim_white_space_from_username
before_destroy :can_be_destroyed?
include WebHooksHelpers #TODO: make this inclusion more dsl-ish
fires_human_web_hooks_on_events
def can_be_destroyed?
errors.add :base, :last_admin unless destroyable?
errors.empty?
end
belongs_to :account, :autosave => false, :inverse_of => :users
# TODO: enable this in rails 3.1 or greater :)
# has_one :provider_account, :through => :account, :source => :provider_account
delegate :provider_account, :to => :account, :allow_nil => true
has_many :posts, -> { latest_first }
has_many :topics, -> { latest_first }
has_many :sso_authorizations, dependent: :delete_all
has_many :moderatorships, :dependent => :delete_all
has_many :forums, :through => :moderatorships, :source => :forum do
def moderatable
select("#{Forum.table_name}.*, #{Moderatorship.table_name}.id as moderatorship_id")
end
end
# TODO: this should be called topic_subscriptions
has_many :user_topics
has_many :subscribed_topics, :through => :user_topics, :source => :topic
has_many :user_sessions, dependent: :destroy
has_many :notifications, dependent: :delete_all, inverse_of: :user
has_one :notification_preferences, dependent: :delete, inverse_of: :user
has_many :access_tokens, foreign_key: :owner_id, dependent: :destroy, inverse_of: :owner
symbolize :role
symbolize :signup_type
validates :username, length: { :within => 3..40, :allow_blank => false }
validates :username, format: { :with => RE_LOGIN_OK, :allow_blank => true,
:message => MSG_LOGIN_BAD }
#OPTIMIZE: use the same format validations in user, account and invitation, add TESTS!
validates :email, length: { :within => 6..255, :allow_blank => true } #r@a.wk
validates :email, format: { :with => RE_EMAIL_OK, :allow_blank => false,
:message => MSG_EMAIL_BAD, :unless => :minimal_signup? }
#TODO: this needs tests
validates :password, length: { :minimum => 6, :allow_blank => true,
:if => lambda{ |u| u.validate_password? and not u.send(:provider_requires_strong_passwords?) } }
validates :extra_fields, length: { maximum: 65535 }
validates :crypted_password, :salt, :remember_token, :activation_code,
length: { maximum: 40 }
validates :state, :role, :lost_password_token, :first_name, :last_name, :signup_type,
:job_role, :last_login_ip, :email_verification_code, :title, :cas_identifier,
:authentication_id, :open_id, :password_digest,
length: { maximum: 255 }
# strong passwords
special_characters = '-+=><_$#.:;!?@&*()~][}{|'
RE_STRONG_PASSWORD = %r{
\A
(?=.*\d) # number
(?=.*[a-z]) # lowercase
(?=.*[A-Z]) # uppercase
(?=.*[#{Regexp.escape(special_characters)}]) # special char
(?!.*\s) # does not end with space
.{8,} # at least 8 characters
\z
}x
STRONG_PASSWORD_FAIL_MSG = "Password must be at least 8 characters long, and contain both upper and lowercase letters, a digit and one special character of #{special_characters}."
validates :password, format: { :with => RE_STRONG_PASSWORD, :message => STRONG_PASSWORD_FAIL_MSG,
:if => :provider_requires_strong_passwords? }
validates :conditions, acceptance: { :on => :create }
validates :service_conditions, acceptance: { :on => :create }
validate :email_is_unique
validate :username_is_unique
validates :open_id, uniqueness: true, allow_nil: true
attr_accessible :title, :username, :email, :first_name, :last_name, :password,
:password_confirmation, :conditions, :cas_identifier, :open_id,
:service_conditions, :job_role, :extra_fields, as: %i[default member admin]
attr_accessible :member_permission_service_ids, :member_permission_ids, as: %i[admin]
# after_validation :reset_lost_password_token
after_save :nullify_authentication_id, if: :any_sso_authorizations?
after_commit :notify_deletion, on: :destroy
def self.search_states
%w(pending active)
end
scope :without_ids, lambda { |id| id ? where(['users.id <> ?', id]) : where({}) }
scope :by_email, lambda { |email| where(:email => email) }
scope :latest, -> {limit(5).order(created_at: :desc)}
scope :but_impersonation_admin, -> { where(['username <> ?', ThreeScale.config.impersonation_admin['username']]) }
scope :impersonation_admins, -> { where(username: ThreeScale.config.impersonation_admin['username']) }
scope :admins, -> { where(role: 'admin') }
scope :active, -> { where(state: 'active') }
scope :with_valid_password_token, -> { where { lost_password_token_generated_at >= 24.hours.ago } }
def self.find_by_username_or_email(value)
find_by(['users.username = ? OR users.email = ?', value, value])
end
def self.find_with_valid_password_token(token)
with_valid_password_token.find_by(lost_password_token: token)
end
def self.impersonation_admin!
where(username: ThreeScale.config.impersonation_admin['username']).first!
end
def self.impersonation_admin
where(username: ThreeScale.config.impersonation_admin['username']).first
end
def impersonation_admin?
username == ThreeScale.config.impersonation_admin['username']
end
def any_sso_authorizations?
persisted? ? sso_authorizations.exists? : sso_authorizations.any?
end
def notification_preferences
migration = Notifications::NewNotificationSystemMigration.new(account)
super || build_notification_preferences(preferences: migration.notification_preferences)
end
def accessible_services
account.accessible_services.permitted_for_user(self)
end
def multiple_accessible_services?
account.multiple_accessible_services?(Service.permitted_for_user(self))
end
def accessible_services?
accessible_services.exists?
end
def allowed_access_token_scopes
AccessToken.scopes.allowed_for(self)
end
def accessible_service_tokens
if has_permission?(:plans)
accessible_services.joins(:service_tokens)
.includes(:service_tokens).map(&:active_service_token)
else
[]
end
end
def accessible_cinstances
cinstances = account.provided_cinstances
# TODO: this has no clear migration path
# once we would enable the :service_permissions feature for everyone
# members that have no access to service would stop seeing applications
case
when has_access_to_all_services?
cinstances
when account.provider_can_use?(:service_permissions)
cinstances.where(service_id: member_permission_service_ids)
else
cinstances
end
end
def can_login?
# Only buyers need to be approved for now.
(active? || email_unverified?) && account && (account.provider? || account.approved?)
end
def expire_password_token
update_columns(lost_password_token_generated_at: nil)
end
def generate_lost_password_token
attributes = {
lost_password_token: token = SecureRandom.hex(32),
lost_password_token_generated_at: Time.current
}
assign_attributes(attributes, without_protection: true)
token if save(validate: true)
end
def generate_lost_password_token!
if generate_lost_password_token
if account.provider?
ProviderUserMailer.lost_password(self).deliver_now
else
UserMailer.lost_password(self).deliver_now
end
end
end
def update_password(new_password, new_password_confirmation)
self.password = new_password
self.password_confirmation = new_password_confirmation
reset_lost_password_token if valid?
save
end
def using_password?
password_digest.present? || crypted_password.present?
end
def can_set_password?
account.password_login_allowed? && !using_password?
end
def kill_user_sessions( but = UserSession.new)
sessions_to_destroy = user_sessions
sessions_to_destroy = sessions_to_destroy.where.not(id: but.id) if but.persisted?
sessions_to_destroy.destroy_all
end
def signup
@_signup ||= SignupType.new(self)
end
def new_signup?
signup.new?
end
def minimal_signup?
signup.minimal?
end
def api_signup?
signup.api?
end
def cas_signup?
signup.cas?
end
def open_id_signup?
signup.open_id?
end
def created_by_provider_signup?
signup.created_by_provider?
end
def password_required?
signup.by_user? && super
end
def recently_activated?
!minimal_signup? && super
end
def informal_name
first_name.present? ? first_name : display_name
end
def display_name
name = full_name
name.present? ? name : username
end
def full_name
[first_name, last_name].select(&:present?).join(' ')
end
# CMS Methods patched below - to be moved to module, or gem to be adjusted directly
def self.current
Thread.current[:cms_user]
end
def self.tenant_id
current.try!(:tenant_id)
end
def self.current=(user)
Thread.current[:cms_user] = user
end
def self.attributes_for_destroy_list
%w( id account_id username email first_name last_name role job_role extra_fields state activated_at created_at)
end
def make_activation_code
self.activation_code = self.class.make_token
end
#NEW CMS END
def toggle_suspend
if self.suspended?
self.unsuspend!
else
self.suspend!
end
end
def account_approved?
account && account.approved? || false
end
def update_last_login!(options)
options.assert_valid_keys(:time, :ip)
self.last_login_at = options[:time]
self.last_login_ip = options[:ip]
# do not call callbacks
self.class.where(id: id).update_all(last_login_at: options[:time], last_login_ip: options[:ip])
end
def subscribed?(topic)
self.subscribed_topics.include? topic
end
def to_xml(options = {})
xml = options[:builder] || ThreeScale::XML::Builder.new
xml.user do |xml|
unless new_record?
xml.id_ id
xml.created_at created_at.xmlschema
xml.updated_at updated_at.xmlschema
end
xml.account_id self.account_id
xml.state state
xml.role role.to_s
xml.cas_identifier(cas_identifier) if cas_signup?
xml.open_id open_id if open_id_signup?
unless destroyed?
fields_to_xml(xml)
extra_fields_to_xml(xml)
end
end
xml.to_xml
end
def special_fields
[:password, :password_confirmation]
end
#TODO: do this with an association
def sections
account.accessible_sections if account
end
def validate_password?
password_required? && password_changed?
end
def unique?(attribute)
unique_in?(uniqueness_scope, attribute)
end
def unique_in?(scope, attribute)
scope ||= self.class
condition = uniqueness_condition_for(attribute)
not scope.without_ids(self.id).exists?(condition)
end
private
def notify_deletion
Users::UserDeletedEvent.create_and_publish!(self)
end
def destroyable?
return true if destroyed_by_association
!(account && !account.destroyed? && account.admins == [self])
end
def nullify_authentication_id
update_column(:authentication_id, nil)
end
def provider_requires_strong_passwords?
# use fields definitons source (instance variable) as backup when creating new record
# and there is no provider account (its still new record and not set through association.build)
if validate_password? && (source = fields_definitions_source_root)
source.settings.strong_passwords_enabled?
end
end
def trim_white_space_from_username
self.username= self.username.strip if self.username
end
def reset_lost_password_token
self.lost_password_token = nil
end
def uniqueness_condition_for(attribute)
{ attribute => self[attribute] }
end
def uniqueness_scope
case
when account.try!(:provider?)
account.users
when provider = account.try!(:provider_account) # buyers
provider.buyer_users
end
end
def email_is_unique
errors.add(:email, :taken) if email.present? && (not unique?(:email))
end
def username_is_unique
errors.add(:username, :taken) if username.present? && (not unique?(:username))
end
class << self
def find_ids(options)
sql = construct_finder_sql(options)
self.connection.select_values(sql)
end
end
protected
def provider_id_for_audits
account.try!(:provider_id_for_audits) || provider_account.try!(:provider_id_for_audits)
end
class SignupType
def initialize(user)
@user = user
end
def partner?
signup_type.to_s.match(/^partner(:|$)/)
end
def new?
signup_type == :new_signup
end
def minimal?
signup_type == :minimal
end
def api?
signup_type == :api
end
def open_id?
@user.open_id.present?
end
def oauth2?
@user.any_sso_authorizations? || @user.authentication_id.present?
end
def created_by_provider?
signup_type == :created_by_provider
end
def cas?
@user.cas_identifier.present?
end
def machine?
minimal? || api? || created_by_provider? || open_id? || cas? || oauth2?
end
def by_user?
not machine?
end
private
delegate :signup_type, to: :@user
end
end