Class: User

Inherits:
ApplicationRecord show all
Includes:
Housekeeping::AssociationHelpers, Housekeeping::Timestamps, Housekeeping::Users, Shared::DataAttributes, Shared::Identifiers, Shared::Notes, Shared::Tags
Defined in:
app/models/user.rb

Overview

A User is a TaxonWorks user, at present someone who can logon to the private workebench.

All Data Models contain created_by_id and updated_by_id that references a User.

A user may have a number of attributes that define roles/subclasses of a sort:

1) Administrators (User#is_administrator = true). An administrator can do absolutely everything, in any project, and across any project, except set User#is_administrator = false. It is intended that there be only 1-2 administrators per instance of TaxonWorks.

2) Project Administrators (ProjectMember#is_project_administrator). A project administrator can set Project settings and preferences, including the views that a Worker can see.

3) Superuser. A super_user (code only) is a User that is a profromct administrator OR administrator.

4) Worker. A worker is a User that can only see parts of the workbench allowed by a ProjectAdministrator.

Data models in TaxonWorks reference People, who may have roles as Sources (or others), i.e. Users are not “data” and not linked directly to People records.

Users must never be shared by real-life humans.

Constant Summary

VALID_EMAIL_REGEX =
/\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

Instance Attribute Summary (collapse)

Attributes included from Housekeeping::Users

#by

Class Method Summary (collapse)

Instance Method Summary (collapse)

Methods included from Housekeeping::AssociationHelpers

#has_many_relationship_classes, #has_many_relationships

Methods included from Housekeeping::Timestamps

#data_breakdown_for_chartkick_recent

Methods included from Housekeeping::Users

#set_created_by_id, #set_updated_by_id

Methods included from ActiverecordUtilities

#trim_attributes

Instance Attribute Details

- (String) api_access_token

Returns authentication token used to authenticate against /api endpoints

Returns:

  • (String)

    authentication token used to authenticate against /api endpoints



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
# File 'app/models/user.rb', line 98

class User < ApplicationRecord
  include Housekeeping::Users
  include Housekeeping::Timestamps
  include Housekeeping::AssociationHelpers
  include Shared::DataAttributes
  include Shared::Notes
  include Shared::Tags
  include Shared::Identifiers
  include Shared::RandomTokenFields[:password_reset]
  has_secure_password

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  attr_accessor :set_new_api_access_token
  attr_accessor :self_created

  before_validation { self.email = email.to_s.downcase }

  before_save :generate_api_access_token, if: :set_new_api_access_token
  # @todo downcase does not work for non-ascii characters which means our validation for uniqueness will fail ... why?
  # @see http://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-email-address
  # @see http://unicode-utils.rubyforge.org/
  before_save { self.email = email.to_s.downcase }

  after_save :configure_self_created, if: :self_created

  before_create :set_remember_token
  before_create { self.hub_tab_order = DEFAULT_HUB_TAB_ORDER }

  validates :email, presence: true,
            format:           {with: VALID_EMAIL_REGEX},
            uniqueness:       true

  validates :password,
            length:       {minimum: 8, :if => :validate_password?},
            :confirmation => {:if => :validate_password?}

  validates :name, presence: true
  validates :name, length: {minimum: 2}, unless: -> { self.name.blank? }

  has_many :project_members, dependent: :destroy
  has_many :projects, through: :project_members
  has_many :pinboard_items, dependent: :destroy

  scope :is_administrator, -> { where(is_administrator: true) }

  def administered_projects
    projects.where(id: project_members.where(is_project_administrator: true).pluck(:project_id))
  end

  def administers_projects?
    administered_projects.any?
  end

  # @param [String, User, Integer] user
  # @return [Integer] selected user id
  def self.get_user_id(user)
    # no way to know who the current user is, so can't pre-set user_id
    case user.class.name
      when 'String'
        # search by name or email
        ut     = User.arel_table
        c1     = ut[:name].eq(user).or(ut[:email].eq(user.downcase)).to_sql
        t_user = User.where(c1).first
        if t_user.present?
          user_id = t_user.id
        else  # try to convert to a number, to see if it came directly from a web page
          t_user = user.to_i
          if t_user > 0
            t_user = User.find(t_user).try(:id)
          else
            t_user = nil
          end
          user_id = t_user
        end
      when 'User'
        user_id = user.id
      when 'Integer'
        user_id = user
    end
    user_id
  end

  # @param [String, User, Integer, Array] users
  # @return [Array of Integers] selected user ids
  def self.get_user_ids(*users)
    user_ids = []
    users.flatten.each { |user|
      case user.class.name
        when 'String'
          # search by name or email
          ut = User.arel_table
          c1 = ut[:name].eq(user)
                 .or(ut[:name].matches("%#{user}"))
                 .or(ut[:name].matches("%#{user}%"))
                 .or(ut[:email].eq(user))
                 .or(ut[:email].matches("%#{user}"))
                 .or(ut[:email].matches("%#{user}%")).to_sql
          user_ids.push(User.where(c1).pluck(:id))
        when 'User'
          user_ids.push(user.id)
        when 'Integer'
          user_ids.push(user)
      end
    }
    user_ids.flatten.uniq
  end

  def self.not_in_project(project_id)
    ids = ProjectMember.where(project_id: project_id).pluck(:user_id)
    return where(false) if ids.empty?

    User.where(User.arel_table[:id].not_eq_all(ids))
  end

  # @param [Integer] project_id
  # @return [Scope] of ids for users in the project
  def self.in_project(project_id = $project_id)
    ProjectMember.where(project_id: project_id).distinct.pluck(:user_id)
  end

  def User.secure_random_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  # @return [true, false]
  # true if user is_administrator or is_project_administrator
  def is_superuser?(project = nil)
    is_administrator || is_project_administrator?(project)
  end

  # @return [Boolean]
  # true if is_administrator = true
  def is_administrator?
    is_administrator.blank? ? false : true
  end

  # @return [true, false]
  # true if user is_project_administrator for the project passed
  # @param project [Project]
  def is_project_administrator?(project = nil)
    return false if project.nil?
    project.project_members.where(user_id: id).first.is_project_administrator
  end

  # @params [Project, Integer]
  # @return [Boolean]
  def member_of?(project)
    ProjectMember.where(project_id: project, user_id: self.id).any?
  end

  def hub_favorites
    read_attribute(:hub_favorites) || {}
  end

  def add_page_to_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    n       = options[:name]
    p       = options[:project_id].to_s
    k       = options[:kind]
    u       = hub_favorites.clone

    u[p]    = {'data' => [], 'tasks' => []} if !u[p]
    u[p][k] = u[p][k].push(n).uniq[0..19].sort

    update_column(:hub_favorites, u)
    true
  end

  def remove_page_from_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    new_routes = hub_favorites.clone
    new_routes[options['project_id'].to_s][options['kind']].delete(options['name'])
    update_column(:hub_favorites, new_routes)
  end

  def validate_favorite_options(options)
    return false if !options.select { |k, v| k.nil? || v.nil? }.empty?
    return false if !member_of?(options['project_id'])
    true
  end

  def update_last_seen_at

    a = 0

    if !last_seen_at.nil?
      t = Time.now - last_seen_at
      a = t < 301 ? time_active + t : time_active
    end

    update_columns(last_seen_at: Time.now, time_active: a)

  end

  def add_recently_visited_to_footprint(recent_route, recent_object = nil)
    case recent_route
      when /\A\/\Z/ # the root path '/'
      when /\A\/hub/ # any path which starts with '/hub'
      when /\/autocomplete\?/ # any path used for AJAX autocomplete
      else

        fp                     = footprints.dup
        fp['recently_visited'] ||= []

        attrs = {recent_route => {}}
        if !recent_object.nil?
          attrs[recent_route].merge!(object_type: recent_object.class.to_s, object_id: recent_object.id)
        end

        fp['recently_visited'].unshift(attrs)
        fp['recently_visited'] = fp['recently_visited'].uniq { |a| a.keys }[0..19]

        self.footprints_will_change! # if this isn't thrown weird caching happens !
        self.update_column(:footprints, fp)
    end

    true
  end

  # TODO:  This needs to show cross-project pinboard items as well
  def pinboard_hash(project_id)
    pinboard_items.where(project_id: project_id).order('pinned_object_type DESC, position').to_a.group_by { |a| a.pinned_object_type }
  end

  # @return [Integer]
  #   the total records of this klass created by this user
  def total_objects(klass) # klass_name is a string, need .constantize in next line
    klass.where(creator: self).count
  end

  def total_objects2(klass_string)
    self.send("created_#{klass_string}").count #klass.where(creator:self).count
  end

  # @return [Hash]
  #
  # @user.get_class_created_updated # => { "projects" => {created: 10, first_created: datetime, updated: 10, last_updated: datetime} }
  def get_class_created_updated
    Rails.application.eager_load! if Rails.env.development?
    data = {}

    User.reflect_on_all_associations(:has_many).each do |r|
      key = nil
      puts r.name.to_s
      if r.name.to_s =~ /created_/
        # puts "after created"
        key = :created
      elsif r.name.to_s =~ /updated_/
        # puts "after updated"
        key = :updated
      end

      if key
        n     = r.klass.name.underscore.humanize.pluralize
        count = self.send(r.name).count

        if data[n]
          data[n][key] = count
        else
          data[n] = {key => count}
        end

        if count == 0
          data[n][:first_created] = 'n/a'
          data[n][:last_updated]  = 'n/a'
        else
          data[n][:first_created] = self.send(r.name).limit(1).order(created_at: :asc).first.created_at
          data[n][:last_updated]  = self.send(r.name).limit(1).order(updated_at: :desc).first.updated_at
        end
      end
    end
    data
  end

  def generate_api_access_token
    self.api_access_token = Utilities::RandomToken.generate
  end

  def require_password_presence
    @require_password_presence = true
  end

  private

  def set_remember_token
    self.remember_token = User.encrypt(User.secure_random_token)
  end

  def validate_password?
    password.present? || password_confirmation.present? || @require_password_presence
  end

  def configure_self_created
    if !self.new_record? && self.creator.nil? && self.updater.nil?
      self.update_columns(created_by_id: self.id, updated_by_id: self.id) # !?
    end
  end


end

- (ActiveSupport::TimeWithZone) current_sign_in_at

Returns time of current sign in

Returns:

  • (ActiveSupport::TimeWithZone)

    time of current sign in



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
# File 'app/models/user.rb', line 98

class User < ApplicationRecord
  include Housekeeping::Users
  include Housekeeping::Timestamps
  include Housekeeping::AssociationHelpers
  include Shared::DataAttributes
  include Shared::Notes
  include Shared::Tags
  include Shared::Identifiers
  include Shared::RandomTokenFields[:password_reset]
  has_secure_password

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  attr_accessor :set_new_api_access_token
  attr_accessor :self_created

  before_validation { self.email = email.to_s.downcase }

  before_save :generate_api_access_token, if: :set_new_api_access_token
  # @todo downcase does not work for non-ascii characters which means our validation for uniqueness will fail ... why?
  # @see http://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-email-address
  # @see http://unicode-utils.rubyforge.org/
  before_save { self.email = email.to_s.downcase }

  after_save :configure_self_created, if: :self_created

  before_create :set_remember_token
  before_create { self.hub_tab_order = DEFAULT_HUB_TAB_ORDER }

  validates :email, presence: true,
            format:           {with: VALID_EMAIL_REGEX},
            uniqueness:       true

  validates :password,
            length:       {minimum: 8, :if => :validate_password?},
            :confirmation => {:if => :validate_password?}

  validates :name, presence: true
  validates :name, length: {minimum: 2}, unless: -> { self.name.blank? }

  has_many :project_members, dependent: :destroy
  has_many :projects, through: :project_members
  has_many :pinboard_items, dependent: :destroy

  scope :is_administrator, -> { where(is_administrator: true) }

  def administered_projects
    projects.where(id: project_members.where(is_project_administrator: true).pluck(:project_id))
  end

  def administers_projects?
    administered_projects.any?
  end

  # @param [String, User, Integer] user
  # @return [Integer] selected user id
  def self.get_user_id(user)
    # no way to know who the current user is, so can't pre-set user_id
    case user.class.name
      when 'String'
        # search by name or email
        ut     = User.arel_table
        c1     = ut[:name].eq(user).or(ut[:email].eq(user.downcase)).to_sql
        t_user = User.where(c1).first
        if t_user.present?
          user_id = t_user.id
        else  # try to convert to a number, to see if it came directly from a web page
          t_user = user.to_i
          if t_user > 0
            t_user = User.find(t_user).try(:id)
          else
            t_user = nil
          end
          user_id = t_user
        end
      when 'User'
        user_id = user.id
      when 'Integer'
        user_id = user
    end
    user_id
  end

  # @param [String, User, Integer, Array] users
  # @return [Array of Integers] selected user ids
  def self.get_user_ids(*users)
    user_ids = []
    users.flatten.each { |user|
      case user.class.name
        when 'String'
          # search by name or email
          ut = User.arel_table
          c1 = ut[:name].eq(user)
                 .or(ut[:name].matches("%#{user}"))
                 .or(ut[:name].matches("%#{user}%"))
                 .or(ut[:email].eq(user))
                 .or(ut[:email].matches("%#{user}"))
                 .or(ut[:email].matches("%#{user}%")).to_sql
          user_ids.push(User.where(c1).pluck(:id))
        when 'User'
          user_ids.push(user.id)
        when 'Integer'
          user_ids.push(user)
      end
    }
    user_ids.flatten.uniq
  end

  def self.not_in_project(project_id)
    ids = ProjectMember.where(project_id: project_id).pluck(:user_id)
    return where(false) if ids.empty?

    User.where(User.arel_table[:id].not_eq_all(ids))
  end

  # @param [Integer] project_id
  # @return [Scope] of ids for users in the project
  def self.in_project(project_id = $project_id)
    ProjectMember.where(project_id: project_id).distinct.pluck(:user_id)
  end

  def User.secure_random_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  # @return [true, false]
  # true if user is_administrator or is_project_administrator
  def is_superuser?(project = nil)
    is_administrator || is_project_administrator?(project)
  end

  # @return [Boolean]
  # true if is_administrator = true
  def is_administrator?
    is_administrator.blank? ? false : true
  end

  # @return [true, false]
  # true if user is_project_administrator for the project passed
  # @param project [Project]
  def is_project_administrator?(project = nil)
    return false if project.nil?
    project.project_members.where(user_id: id).first.is_project_administrator
  end

  # @params [Project, Integer]
  # @return [Boolean]
  def member_of?(project)
    ProjectMember.where(project_id: project, user_id: self.id).any?
  end

  def hub_favorites
    read_attribute(:hub_favorites) || {}
  end

  def add_page_to_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    n       = options[:name]
    p       = options[:project_id].to_s
    k       = options[:kind]
    u       = hub_favorites.clone

    u[p]    = {'data' => [], 'tasks' => []} if !u[p]
    u[p][k] = u[p][k].push(n).uniq[0..19].sort

    update_column(:hub_favorites, u)
    true
  end

  def remove_page_from_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    new_routes = hub_favorites.clone
    new_routes[options['project_id'].to_s][options['kind']].delete(options['name'])
    update_column(:hub_favorites, new_routes)
  end

  def validate_favorite_options(options)
    return false if !options.select { |k, v| k.nil? || v.nil? }.empty?
    return false if !member_of?(options['project_id'])
    true
  end

  def update_last_seen_at

    a = 0

    if !last_seen_at.nil?
      t = Time.now - last_seen_at
      a = t < 301 ? time_active + t : time_active
    end

    update_columns(last_seen_at: Time.now, time_active: a)

  end

  def add_recently_visited_to_footprint(recent_route, recent_object = nil)
    case recent_route
      when /\A\/\Z/ # the root path '/'
      when /\A\/hub/ # any path which starts with '/hub'
      when /\/autocomplete\?/ # any path used for AJAX autocomplete
      else

        fp                     = footprints.dup
        fp['recently_visited'] ||= []

        attrs = {recent_route => {}}
        if !recent_object.nil?
          attrs[recent_route].merge!(object_type: recent_object.class.to_s, object_id: recent_object.id)
        end

        fp['recently_visited'].unshift(attrs)
        fp['recently_visited'] = fp['recently_visited'].uniq { |a| a.keys }[0..19]

        self.footprints_will_change! # if this isn't thrown weird caching happens !
        self.update_column(:footprints, fp)
    end

    true
  end

  # TODO:  This needs to show cross-project pinboard items as well
  def pinboard_hash(project_id)
    pinboard_items.where(project_id: project_id).order('pinned_object_type DESC, position').to_a.group_by { |a| a.pinned_object_type }
  end

  # @return [Integer]
  #   the total records of this klass created by this user
  def total_objects(klass) # klass_name is a string, need .constantize in next line
    klass.where(creator: self).count
  end

  def total_objects2(klass_string)
    self.send("created_#{klass_string}").count #klass.where(creator:self).count
  end

  # @return [Hash]
  #
  # @user.get_class_created_updated # => { "projects" => {created: 10, first_created: datetime, updated: 10, last_updated: datetime} }
  def get_class_created_updated
    Rails.application.eager_load! if Rails.env.development?
    data = {}

    User.reflect_on_all_associations(:has_many).each do |r|
      key = nil
      puts r.name.to_s
      if r.name.to_s =~ /created_/
        # puts "after created"
        key = :created
      elsif r.name.to_s =~ /updated_/
        # puts "after updated"
        key = :updated
      end

      if key
        n     = r.klass.name.underscore.humanize.pluralize
        count = self.send(r.name).count

        if data[n]
          data[n][key] = count
        else
          data[n] = {key => count}
        end

        if count == 0
          data[n][:first_created] = 'n/a'
          data[n][:last_updated]  = 'n/a'
        else
          data[n][:first_created] = self.send(r.name).limit(1).order(created_at: :asc).first.created_at
          data[n][:last_updated]  = self.send(r.name).limit(1).order(updated_at: :desc).first.updated_at
        end
      end
    end
    data
  end

  def generate_api_access_token
    self.api_access_token = Utilities::RandomToken.generate
  end

  def require_password_presence
    @require_password_presence = true
  end

  private

  def set_remember_token
    self.remember_token = User.encrypt(User.secure_random_token)
  end

  def validate_password?
    password.present? || password_confirmation.present? || @require_password_presence
  end

  def configure_self_created
    if !self.new_record? && self.creator.nil? && self.updater.nil?
      self.update_columns(created_by_id: self.id, updated_by_id: self.id) # !?
    end
  end


end

- (String) current_sign_in_ip

Returns IP address of the machine user is currently logged in from

Returns:

  • (String)

    IP address of the machine user is currently logged in from



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
# File 'app/models/user.rb', line 98

class User < ApplicationRecord
  include Housekeeping::Users
  include Housekeeping::Timestamps
  include Housekeeping::AssociationHelpers
  include Shared::DataAttributes
  include Shared::Notes
  include Shared::Tags
  include Shared::Identifiers
  include Shared::RandomTokenFields[:password_reset]
  has_secure_password

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  attr_accessor :set_new_api_access_token
  attr_accessor :self_created

  before_validation { self.email = email.to_s.downcase }

  before_save :generate_api_access_token, if: :set_new_api_access_token
  # @todo downcase does not work for non-ascii characters which means our validation for uniqueness will fail ... why?
  # @see http://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-email-address
  # @see http://unicode-utils.rubyforge.org/
  before_save { self.email = email.to_s.downcase }

  after_save :configure_self_created, if: :self_created

  before_create :set_remember_token
  before_create { self.hub_tab_order = DEFAULT_HUB_TAB_ORDER }

  validates :email, presence: true,
            format:           {with: VALID_EMAIL_REGEX},
            uniqueness:       true

  validates :password,
            length:       {minimum: 8, :if => :validate_password?},
            :confirmation => {:if => :validate_password?}

  validates :name, presence: true
  validates :name, length: {minimum: 2}, unless: -> { self.name.blank? }

  has_many :project_members, dependent: :destroy
  has_many :projects, through: :project_members
  has_many :pinboard_items, dependent: :destroy

  scope :is_administrator, -> { where(is_administrator: true) }

  def administered_projects
    projects.where(id: project_members.where(is_project_administrator: true).pluck(:project_id))
  end

  def administers_projects?
    administered_projects.any?
  end

  # @param [String, User, Integer] user
  # @return [Integer] selected user id
  def self.get_user_id(user)
    # no way to know who the current user is, so can't pre-set user_id
    case user.class.name
      when 'String'
        # search by name or email
        ut     = User.arel_table
        c1     = ut[:name].eq(user).or(ut[:email].eq(user.downcase)).to_sql
        t_user = User.where(c1).first
        if t_user.present?
          user_id = t_user.id
        else  # try to convert to a number, to see if it came directly from a web page
          t_user = user.to_i
          if t_user > 0
            t_user = User.find(t_user).try(:id)
          else
            t_user = nil
          end
          user_id = t_user
        end
      when 'User'
        user_id = user.id
      when 'Integer'
        user_id = user
    end
    user_id
  end

  # @param [String, User, Integer, Array] users
  # @return [Array of Integers] selected user ids
  def self.get_user_ids(*users)
    user_ids = []
    users.flatten.each { |user|
      case user.class.name
        when 'String'
          # search by name or email
          ut = User.arel_table
          c1 = ut[:name].eq(user)
                 .or(ut[:name].matches("%#{user}"))
                 .or(ut[:name].matches("%#{user}%"))
                 .or(ut[:email].eq(user))
                 .or(ut[:email].matches("%#{user}"))
                 .or(ut[:email].matches("%#{user}%")).to_sql
          user_ids.push(User.where(c1).pluck(:id))
        when 'User'
          user_ids.push(user.id)
        when 'Integer'
          user_ids.push(user)
      end
    }
    user_ids.flatten.uniq
  end

  def self.not_in_project(project_id)
    ids = ProjectMember.where(project_id: project_id).pluck(:user_id)
    return where(false) if ids.empty?

    User.where(User.arel_table[:id].not_eq_all(ids))
  end

  # @param [Integer] project_id
  # @return [Scope] of ids for users in the project
  def self.in_project(project_id = $project_id)
    ProjectMember.where(project_id: project_id).distinct.pluck(:user_id)
  end

  def User.secure_random_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  # @return [true, false]
  # true if user is_administrator or is_project_administrator
  def is_superuser?(project = nil)
    is_administrator || is_project_administrator?(project)
  end

  # @return [Boolean]
  # true if is_administrator = true
  def is_administrator?
    is_administrator.blank? ? false : true
  end

  # @return [true, false]
  # true if user is_project_administrator for the project passed
  # @param project [Project]
  def is_project_administrator?(project = nil)
    return false if project.nil?
    project.project_members.where(user_id: id).first.is_project_administrator
  end

  # @params [Project, Integer]
  # @return [Boolean]
  def member_of?(project)
    ProjectMember.where(project_id: project, user_id: self.id).any?
  end

  def hub_favorites
    read_attribute(:hub_favorites) || {}
  end

  def add_page_to_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    n       = options[:name]
    p       = options[:project_id].to_s
    k       = options[:kind]
    u       = hub_favorites.clone

    u[p]    = {'data' => [], 'tasks' => []} if !u[p]
    u[p][k] = u[p][k].push(n).uniq[0..19].sort

    update_column(:hub_favorites, u)
    true
  end

  def remove_page_from_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    new_routes = hub_favorites.clone
    new_routes[options['project_id'].to_s][options['kind']].delete(options['name'])
    update_column(:hub_favorites, new_routes)
  end

  def validate_favorite_options(options)
    return false if !options.select { |k, v| k.nil? || v.nil? }.empty?
    return false if !member_of?(options['project_id'])
    true
  end

  def update_last_seen_at

    a = 0

    if !last_seen_at.nil?
      t = Time.now - last_seen_at
      a = t < 301 ? time_active + t : time_active
    end

    update_columns(last_seen_at: Time.now, time_active: a)

  end

  def add_recently_visited_to_footprint(recent_route, recent_object = nil)
    case recent_route
      when /\A\/\Z/ # the root path '/'
      when /\A\/hub/ # any path which starts with '/hub'
      when /\/autocomplete\?/ # any path used for AJAX autocomplete
      else

        fp                     = footprints.dup
        fp['recently_visited'] ||= []

        attrs = {recent_route => {}}
        if !recent_object.nil?
          attrs[recent_route].merge!(object_type: recent_object.class.to_s, object_id: recent_object.id)
        end

        fp['recently_visited'].unshift(attrs)
        fp['recently_visited'] = fp['recently_visited'].uniq { |a| a.keys }[0..19]

        self.footprints_will_change! # if this isn't thrown weird caching happens !
        self.update_column(:footprints, fp)
    end

    true
  end

  # TODO:  This needs to show cross-project pinboard items as well
  def pinboard_hash(project_id)
    pinboard_items.where(project_id: project_id).order('pinned_object_type DESC, position').to_a.group_by { |a| a.pinned_object_type }
  end

  # @return [Integer]
  #   the total records of this klass created by this user
  def total_objects(klass) # klass_name is a string, need .constantize in next line
    klass.where(creator: self).count
  end

  def total_objects2(klass_string)
    self.send("created_#{klass_string}").count #klass.where(creator:self).count
  end

  # @return [Hash]
  #
  # @user.get_class_created_updated # => { "projects" => {created: 10, first_created: datetime, updated: 10, last_updated: datetime} }
  def get_class_created_updated
    Rails.application.eager_load! if Rails.env.development?
    data = {}

    User.reflect_on_all_associations(:has_many).each do |r|
      key = nil
      puts r.name.to_s
      if r.name.to_s =~ /created_/
        # puts "after created"
        key = :created
      elsif r.name.to_s =~ /updated_/
        # puts "after updated"
        key = :updated
      end

      if key
        n     = r.klass.name.underscore.humanize.pluralize
        count = self.send(r.name).count

        if data[n]
          data[n][key] = count
        else
          data[n] = {key => count}
        end

        if count == 0
          data[n][:first_created] = 'n/a'
          data[n][:last_updated]  = 'n/a'
        else
          data[n][:first_created] = self.send(r.name).limit(1).order(created_at: :asc).first.created_at
          data[n][:last_updated]  = self.send(r.name).limit(1).order(updated_at: :desc).first.updated_at
        end
      end
    end
    data
  end

  def generate_api_access_token
    self.api_access_token = Utilities::RandomToken.generate
  end

  def require_password_presence
    @require_password_presence = true
  end

  private

  def set_remember_token
    self.remember_token = User.encrypt(User.secure_random_token)
  end

  def validate_password?
    password.present? || password_confirmation.present? || @require_password_presence
  end

  def configure_self_created
    if !self.new_record? && self.creator.nil? && self.updater.nil?
      self.update_columns(created_by_id: self.id, updated_by_id: self.id) # !?
    end
  end


end

- (String) email

Returns the users email, and login.

Returns:

  • (String)

    the users email, and login.



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
# File 'app/models/user.rb', line 98

class User < ApplicationRecord
  include Housekeeping::Users
  include Housekeeping::Timestamps
  include Housekeeping::AssociationHelpers
  include Shared::DataAttributes
  include Shared::Notes
  include Shared::Tags
  include Shared::Identifiers
  include Shared::RandomTokenFields[:password_reset]
  has_secure_password

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  attr_accessor :set_new_api_access_token
  attr_accessor :self_created

  before_validation { self.email = email.to_s.downcase }

  before_save :generate_api_access_token, if: :set_new_api_access_token
  # @todo downcase does not work for non-ascii characters which means our validation for uniqueness will fail ... why?
  # @see http://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-email-address
  # @see http://unicode-utils.rubyforge.org/
  before_save { self.email = email.to_s.downcase }

  after_save :configure_self_created, if: :self_created

  before_create :set_remember_token
  before_create { self.hub_tab_order = DEFAULT_HUB_TAB_ORDER }

  validates :email, presence: true,
            format:           {with: VALID_EMAIL_REGEX},
            uniqueness:       true

  validates :password,
            length:       {minimum: 8, :if => :validate_password?},
            :confirmation => {:if => :validate_password?}

  validates :name, presence: true
  validates :name, length: {minimum: 2}, unless: -> { self.name.blank? }

  has_many :project_members, dependent: :destroy
  has_many :projects, through: :project_members
  has_many :pinboard_items, dependent: :destroy

  scope :is_administrator, -> { where(is_administrator: true) }

  def administered_projects
    projects.where(id: project_members.where(is_project_administrator: true).pluck(:project_id))
  end

  def administers_projects?
    administered_projects.any?
  end

  # @param [String, User, Integer] user
  # @return [Integer] selected user id
  def self.get_user_id(user)
    # no way to know who the current user is, so can't pre-set user_id
    case user.class.name
      when 'String'
        # search by name or email
        ut     = User.arel_table
        c1     = ut[:name].eq(user).or(ut[:email].eq(user.downcase)).to_sql
        t_user = User.where(c1).first
        if t_user.present?
          user_id = t_user.id
        else  # try to convert to a number, to see if it came directly from a web page
          t_user = user.to_i
          if t_user > 0
            t_user = User.find(t_user).try(:id)
          else
            t_user = nil
          end
          user_id = t_user
        end
      when 'User'
        user_id = user.id
      when 'Integer'
        user_id = user
    end
    user_id
  end

  # @param [String, User, Integer, Array] users
  # @return [Array of Integers] selected user ids
  def self.get_user_ids(*users)
    user_ids = []
    users.flatten.each { |user|
      case user.class.name
        when 'String'
          # search by name or email
          ut = User.arel_table
          c1 = ut[:name].eq(user)
                 .or(ut[:name].matches("%#{user}"))
                 .or(ut[:name].matches("%#{user}%"))
                 .or(ut[:email].eq(user))
                 .or(ut[:email].matches("%#{user}"))
                 .or(ut[:email].matches("%#{user}%")).to_sql
          user_ids.push(User.where(c1).pluck(:id))
        when 'User'
          user_ids.push(user.id)
        when 'Integer'
          user_ids.push(user)
      end
    }
    user_ids.flatten.uniq
  end

  def self.not_in_project(project_id)
    ids = ProjectMember.where(project_id: project_id).pluck(:user_id)
    return where(false) if ids.empty?

    User.where(User.arel_table[:id].not_eq_all(ids))
  end

  # @param [Integer] project_id
  # @return [Scope] of ids for users in the project
  def self.in_project(project_id = $project_id)
    ProjectMember.where(project_id: project_id).distinct.pluck(:user_id)
  end

  def User.secure_random_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  # @return [true, false]
  # true if user is_administrator or is_project_administrator
  def is_superuser?(project = nil)
    is_administrator || is_project_administrator?(project)
  end

  # @return [Boolean]
  # true if is_administrator = true
  def is_administrator?
    is_administrator.blank? ? false : true
  end

  # @return [true, false]
  # true if user is_project_administrator for the project passed
  # @param project [Project]
  def is_project_administrator?(project = nil)
    return false if project.nil?
    project.project_members.where(user_id: id).first.is_project_administrator
  end

  # @params [Project, Integer]
  # @return [Boolean]
  def member_of?(project)
    ProjectMember.where(project_id: project, user_id: self.id).any?
  end

  def hub_favorites
    read_attribute(:hub_favorites) || {}
  end

  def add_page_to_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    n       = options[:name]
    p       = options[:project_id].to_s
    k       = options[:kind]
    u       = hub_favorites.clone

    u[p]    = {'data' => [], 'tasks' => []} if !u[p]
    u[p][k] = u[p][k].push(n).uniq[0..19].sort

    update_column(:hub_favorites, u)
    true
  end

  def remove_page_from_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    new_routes = hub_favorites.clone
    new_routes[options['project_id'].to_s][options['kind']].delete(options['name'])
    update_column(:hub_favorites, new_routes)
  end

  def validate_favorite_options(options)
    return false if !options.select { |k, v| k.nil? || v.nil? }.empty?
    return false if !member_of?(options['project_id'])
    true
  end

  def update_last_seen_at

    a = 0

    if !last_seen_at.nil?
      t = Time.now - last_seen_at
      a = t < 301 ? time_active + t : time_active
    end

    update_columns(last_seen_at: Time.now, time_active: a)

  end

  def add_recently_visited_to_footprint(recent_route, recent_object = nil)
    case recent_route
      when /\A\/\Z/ # the root path '/'
      when /\A\/hub/ # any path which starts with '/hub'
      when /\/autocomplete\?/ # any path used for AJAX autocomplete
      else

        fp                     = footprints.dup
        fp['recently_visited'] ||= []

        attrs = {recent_route => {}}
        if !recent_object.nil?
          attrs[recent_route].merge!(object_type: recent_object.class.to_s, object_id: recent_object.id)
        end

        fp['recently_visited'].unshift(attrs)
        fp['recently_visited'] = fp['recently_visited'].uniq { |a| a.keys }[0..19]

        self.footprints_will_change! # if this isn't thrown weird caching happens !
        self.update_column(:footprints, fp)
    end

    true
  end

  # TODO:  This needs to show cross-project pinboard items as well
  def pinboard_hash(project_id)
    pinboard_items.where(project_id: project_id).order('pinned_object_type DESC, position').to_a.group_by { |a| a.pinned_object_type }
  end

  # @return [Integer]
  #   the total records of this klass created by this user
  def total_objects(klass) # klass_name is a string, need .constantize in next line
    klass.where(creator: self).count
  end

  def total_objects2(klass_string)
    self.send("created_#{klass_string}").count #klass.where(creator:self).count
  end

  # @return [Hash]
  #
  # @user.get_class_created_updated # => { "projects" => {created: 10, first_created: datetime, updated: 10, last_updated: datetime} }
  def get_class_created_updated
    Rails.application.eager_load! if Rails.env.development?
    data = {}

    User.reflect_on_all_associations(:has_many).each do |r|
      key = nil
      puts r.name.to_s
      if r.name.to_s =~ /created_/
        # puts "after created"
        key = :created
      elsif r.name.to_s =~ /updated_/
        # puts "after updated"
        key = :updated
      end

      if key
        n     = r.klass.name.underscore.humanize.pluralize
        count = self.send(r.name).count

        if data[n]
          data[n][key] = count
        else
          data[n] = {key => count}
        end

        if count == 0
          data[n][:first_created] = 'n/a'
          data[n][:last_updated]  = 'n/a'
        else
          data[n][:first_created] = self.send(r.name).limit(1).order(created_at: :asc).first.created_at
          data[n][:last_updated]  = self.send(r.name).limit(1).order(updated_at: :desc).first.updated_at
        end
      end
    end
    data
  end

  def generate_api_access_token
    self.api_access_token = Utilities::RandomToken.generate
  end

  def require_password_presence
    @require_password_presence = true
  end

  private

  def set_remember_token
    self.remember_token = User.encrypt(User.secure_random_token)
  end

  def validate_password?
    password.present? || password_confirmation.present? || @require_password_presence
  end

  def configure_self_created
    if !self.new_record? && self.creator.nil? && self.updater.nil?
      self.update_columns(created_by_id: self.id, updated_by_id: self.id) # !?
    end
  end


end

- (Hash) footprints

Returns tracks the users recent requests

Returns:

  • (Hash)

    tracks the users recent requests



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
# File 'app/models/user.rb', line 98

class User < ApplicationRecord
  include Housekeeping::Users
  include Housekeeping::Timestamps
  include Housekeeping::AssociationHelpers
  include Shared::DataAttributes
  include Shared::Notes
  include Shared::Tags
  include Shared::Identifiers
  include Shared::RandomTokenFields[:password_reset]
  has_secure_password

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  attr_accessor :set_new_api_access_token
  attr_accessor :self_created

  before_validation { self.email = email.to_s.downcase }

  before_save :generate_api_access_token, if: :set_new_api_access_token
  # @todo downcase does not work for non-ascii characters which means our validation for uniqueness will fail ... why?
  # @see http://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-email-address
  # @see http://unicode-utils.rubyforge.org/
  before_save { self.email = email.to_s.downcase }

  after_save :configure_self_created, if: :self_created

  before_create :set_remember_token
  before_create { self.hub_tab_order = DEFAULT_HUB_TAB_ORDER }

  validates :email, presence: true,
            format:           {with: VALID_EMAIL_REGEX},
            uniqueness:       true

  validates :password,
            length:       {minimum: 8, :if => :validate_password?},
            :confirmation => {:if => :validate_password?}

  validates :name, presence: true
  validates :name, length: {minimum: 2}, unless: -> { self.name.blank? }

  has_many :project_members, dependent: :destroy
  has_many :projects, through: :project_members
  has_many :pinboard_items, dependent: :destroy

  scope :is_administrator, -> { where(is_administrator: true) }

  def administered_projects
    projects.where(id: project_members.where(is_project_administrator: true).pluck(:project_id))
  end

  def administers_projects?
    administered_projects.any?
  end

  # @param [String, User, Integer] user
  # @return [Integer] selected user id
  def self.get_user_id(user)
    # no way to know who the current user is, so can't pre-set user_id
    case user.class.name
      when 'String'
        # search by name or email
        ut     = User.arel_table
        c1     = ut[:name].eq(user).or(ut[:email].eq(user.downcase)).to_sql
        t_user = User.where(c1).first
        if t_user.present?
          user_id = t_user.id
        else  # try to convert to a number, to see if it came directly from a web page
          t_user = user.to_i
          if t_user > 0
            t_user = User.find(t_user).try(:id)
          else
            t_user = nil
          end
          user_id = t_user
        end
      when 'User'
        user_id = user.id
      when 'Integer'
        user_id = user
    end
    user_id
  end

  # @param [String, User, Integer, Array] users
  # @return [Array of Integers] selected user ids
  def self.get_user_ids(*users)
    user_ids = []
    users.flatten.each { |user|
      case user.class.name
        when 'String'
          # search by name or email
          ut = User.arel_table
          c1 = ut[:name].eq(user)
                 .or(ut[:name].matches("%#{user}"))
                 .or(ut[:name].matches("%#{user}%"))
                 .or(ut[:email].eq(user))
                 .or(ut[:email].matches("%#{user}"))
                 .or(ut[:email].matches("%#{user}%")).to_sql
          user_ids.push(User.where(c1).pluck(:id))
        when 'User'
          user_ids.push(user.id)
        when 'Integer'
          user_ids.push(user)
      end
    }
    user_ids.flatten.uniq
  end

  def self.not_in_project(project_id)
    ids = ProjectMember.where(project_id: project_id).pluck(:user_id)
    return where(false) if ids.empty?

    User.where(User.arel_table[:id].not_eq_all(ids))
  end

  # @param [Integer] project_id
  # @return [Scope] of ids for users in the project
  def self.in_project(project_id = $project_id)
    ProjectMember.where(project_id: project_id).distinct.pluck(:user_id)
  end

  def User.secure_random_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  # @return [true, false]
  # true if user is_administrator or is_project_administrator
  def is_superuser?(project = nil)
    is_administrator || is_project_administrator?(project)
  end

  # @return [Boolean]
  # true if is_administrator = true
  def is_administrator?
    is_administrator.blank? ? false : true
  end

  # @return [true, false]
  # true if user is_project_administrator for the project passed
  # @param project [Project]
  def is_project_administrator?(project = nil)
    return false if project.nil?
    project.project_members.where(user_id: id).first.is_project_administrator
  end

  # @params [Project, Integer]
  # @return [Boolean]
  def member_of?(project)
    ProjectMember.where(project_id: project, user_id: self.id).any?
  end

  def hub_favorites
    read_attribute(:hub_favorites) || {}
  end

  def add_page_to_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    n       = options[:name]
    p       = options[:project_id].to_s
    k       = options[:kind]
    u       = hub_favorites.clone

    u[p]    = {'data' => [], 'tasks' => []} if !u[p]
    u[p][k] = u[p][k].push(n).uniq[0..19].sort

    update_column(:hub_favorites, u)
    true
  end

  def remove_page_from_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    new_routes = hub_favorites.clone
    new_routes[options['project_id'].to_s][options['kind']].delete(options['name'])
    update_column(:hub_favorites, new_routes)
  end

  def validate_favorite_options(options)
    return false if !options.select { |k, v| k.nil? || v.nil? }.empty?
    return false if !member_of?(options['project_id'])
    true
  end

  def update_last_seen_at

    a = 0

    if !last_seen_at.nil?
      t = Time.now - last_seen_at
      a = t < 301 ? time_active + t : time_active
    end

    update_columns(last_seen_at: Time.now, time_active: a)

  end

  def add_recently_visited_to_footprint(recent_route, recent_object = nil)
    case recent_route
      when /\A\/\Z/ # the root path '/'
      when /\A\/hub/ # any path which starts with '/hub'
      when /\/autocomplete\?/ # any path used for AJAX autocomplete
      else

        fp                     = footprints.dup
        fp['recently_visited'] ||= []

        attrs = {recent_route => {}}
        if !recent_object.nil?
          attrs[recent_route].merge!(object_type: recent_object.class.to_s, object_id: recent_object.id)
        end

        fp['recently_visited'].unshift(attrs)
        fp['recently_visited'] = fp['recently_visited'].uniq { |a| a.keys }[0..19]

        self.footprints_will_change! # if this isn't thrown weird caching happens !
        self.update_column(:footprints, fp)
    end

    true
  end

  # TODO:  This needs to show cross-project pinboard items as well
  def pinboard_hash(project_id)
    pinboard_items.where(project_id: project_id).order('pinned_object_type DESC, position').to_a.group_by { |a| a.pinned_object_type }
  end

  # @return [Integer]
  #   the total records of this klass created by this user
  def total_objects(klass) # klass_name is a string, need .constantize in next line
    klass.where(creator: self).count
  end

  def total_objects2(klass_string)
    self.send("created_#{klass_string}").count #klass.where(creator:self).count
  end

  # @return [Hash]
  #
  # @user.get_class_created_updated # => { "projects" => {created: 10, first_created: datetime, updated: 10, last_updated: datetime} }
  def get_class_created_updated
    Rails.application.eager_load! if Rails.env.development?
    data = {}

    User.reflect_on_all_associations(:has_many).each do |r|
      key = nil
      puts r.name.to_s
      if r.name.to_s =~ /created_/
        # puts "after created"
        key = :created
      elsif r.name.to_s =~ /updated_/
        # puts "after updated"
        key = :updated
      end

      if key
        n     = r.klass.name.underscore.humanize.pluralize
        count = self.send(r.name).count

        if data[n]
          data[n][key] = count
        else
          data[n] = {key => count}
        end

        if count == 0
          data[n][:first_created] = 'n/a'
          data[n][:last_updated]  = 'n/a'
        else
          data[n][:first_created] = self.send(r.name).limit(1).order(created_at: :asc).first.created_at
          data[n][:last_updated]  = self.send(r.name).limit(1).order(updated_at: :desc).first.updated_at
        end
      end
    end
    data
  end

  def generate_api_access_token
    self.api_access_token = Utilities::RandomToken.generate
  end

  def require_password_presence
    @require_password_presence = true
  end

  private

  def set_remember_token
    self.remember_token = User.encrypt(User.secure_random_token)
  end

  def validate_password?
    password.present? || password_confirmation.present? || @require_password_presence
  end

  def configure_self_created
    if !self.new_record? && self.creator.nil? && self.updater.nil?
      self.update_columns(created_by_id: self.id, updated_by_id: self.id) # !?
    end
  end


end

- (Hash) hub_favorites

Returns per project favorites named from items in user_tasks.yml or hub_data.yml format is { project_id: {data: [ 'ModelName' ], tasks: [ :task_index_name ] }, … }

Returns:

  • (Hash)

    per project favorites named from items in user_tasks.yml or hub_data.yml format is { project_id: {data: [ 'ModelName' ], tasks: [ :task_index_name ] }, … }



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
# File 'app/models/user.rb', line 98

class User < ApplicationRecord
  include Housekeeping::Users
  include Housekeeping::Timestamps
  include Housekeeping::AssociationHelpers
  include Shared::DataAttributes
  include Shared::Notes
  include Shared::Tags
  include Shared::Identifiers
  include Shared::RandomTokenFields[:password_reset]
  has_secure_password

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  attr_accessor :set_new_api_access_token
  attr_accessor :self_created

  before_validation { self.email = email.to_s.downcase }

  before_save :generate_api_access_token, if: :set_new_api_access_token
  # @todo downcase does not work for non-ascii characters which means our validation for uniqueness will fail ... why?
  # @see http://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-email-address
  # @see http://unicode-utils.rubyforge.org/
  before_save { self.email = email.to_s.downcase }

  after_save :configure_self_created, if: :self_created

  before_create :set_remember_token
  before_create { self.hub_tab_order = DEFAULT_HUB_TAB_ORDER }

  validates :email, presence: true,
            format:           {with: VALID_EMAIL_REGEX},
            uniqueness:       true

  validates :password,
            length:       {minimum: 8, :if => :validate_password?},
            :confirmation => {:if => :validate_password?}

  validates :name, presence: true
  validates :name, length: {minimum: 2}, unless: -> { self.name.blank? }

  has_many :project_members, dependent: :destroy
  has_many :projects, through: :project_members
  has_many :pinboard_items, dependent: :destroy

  scope :is_administrator, -> { where(is_administrator: true) }

  def administered_projects
    projects.where(id: project_members.where(is_project_administrator: true).pluck(:project_id))
  end

  def administers_projects?
    administered_projects.any?
  end

  # @param [String, User, Integer] user
  # @return [Integer] selected user id
  def self.get_user_id(user)
    # no way to know who the current user is, so can't pre-set user_id
    case user.class.name
      when 'String'
        # search by name or email
        ut     = User.arel_table
        c1     = ut[:name].eq(user).or(ut[:email].eq(user.downcase)).to_sql
        t_user = User.where(c1).first
        if t_user.present?
          user_id = t_user.id
        else  # try to convert to a number, to see if it came directly from a web page
          t_user = user.to_i
          if t_user > 0
            t_user = User.find(t_user).try(:id)
          else
            t_user = nil
          end
          user_id = t_user
        end
      when 'User'
        user_id = user.id
      when 'Integer'
        user_id = user
    end
    user_id
  end

  # @param [String, User, Integer, Array] users
  # @return [Array of Integers] selected user ids
  def self.get_user_ids(*users)
    user_ids = []
    users.flatten.each { |user|
      case user.class.name
        when 'String'
          # search by name or email
          ut = User.arel_table
          c1 = ut[:name].eq(user)
                 .or(ut[:name].matches("%#{user}"))
                 .or(ut[:name].matches("%#{user}%"))
                 .or(ut[:email].eq(user))
                 .or(ut[:email].matches("%#{user}"))
                 .or(ut[:email].matches("%#{user}%")).to_sql
          user_ids.push(User.where(c1).pluck(:id))
        when 'User'
          user_ids.push(user.id)
        when 'Integer'
          user_ids.push(user)
      end
    }
    user_ids.flatten.uniq
  end

  def self.not_in_project(project_id)
    ids = ProjectMember.where(project_id: project_id).pluck(:user_id)
    return where(false) if ids.empty?

    User.where(User.arel_table[:id].not_eq_all(ids))
  end

  # @param [Integer] project_id
  # @return [Scope] of ids for users in the project
  def self.in_project(project_id = $project_id)
    ProjectMember.where(project_id: project_id).distinct.pluck(:user_id)
  end

  def User.secure_random_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  # @return [true, false]
  # true if user is_administrator or is_project_administrator
  def is_superuser?(project = nil)
    is_administrator || is_project_administrator?(project)
  end

  # @return [Boolean]
  # true if is_administrator = true
  def is_administrator?
    is_administrator.blank? ? false : true
  end

  # @return [true, false]
  # true if user is_project_administrator for the project passed
  # @param project [Project]
  def is_project_administrator?(project = nil)
    return false if project.nil?
    project.project_members.where(user_id: id).first.is_project_administrator
  end

  # @params [Project, Integer]
  # @return [Boolean]
  def member_of?(project)
    ProjectMember.where(project_id: project, user_id: self.id).any?
  end

  def hub_favorites
    read_attribute(:hub_favorites) || {}
  end

  def add_page_to_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    n       = options[:name]
    p       = options[:project_id].to_s
    k       = options[:kind]
    u       = hub_favorites.clone

    u[p]    = {'data' => [], 'tasks' => []} if !u[p]
    u[p][k] = u[p][k].push(n).uniq[0..19].sort

    update_column(:hub_favorites, u)
    true
  end

  def remove_page_from_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    new_routes = hub_favorites.clone
    new_routes[options['project_id'].to_s][options['kind']].delete(options['name'])
    update_column(:hub_favorites, new_routes)
  end

  def validate_favorite_options(options)
    return false if !options.select { |k, v| k.nil? || v.nil? }.empty?
    return false if !member_of?(options['project_id'])
    true
  end

  def update_last_seen_at

    a = 0

    if !last_seen_at.nil?
      t = Time.now - last_seen_at
      a = t < 301 ? time_active + t : time_active
    end

    update_columns(last_seen_at: Time.now, time_active: a)

  end

  def add_recently_visited_to_footprint(recent_route, recent_object = nil)
    case recent_route
      when /\A\/\Z/ # the root path '/'
      when /\A\/hub/ # any path which starts with '/hub'
      when /\/autocomplete\?/ # any path used for AJAX autocomplete
      else

        fp                     = footprints.dup
        fp['recently_visited'] ||= []

        attrs = {recent_route => {}}
        if !recent_object.nil?
          attrs[recent_route].merge!(object_type: recent_object.class.to_s, object_id: recent_object.id)
        end

        fp['recently_visited'].unshift(attrs)
        fp['recently_visited'] = fp['recently_visited'].uniq { |a| a.keys }[0..19]

        self.footprints_will_change! # if this isn't thrown weird caching happens !
        self.update_column(:footprints, fp)
    end

    true
  end

  # TODO:  This needs to show cross-project pinboard items as well
  def pinboard_hash(project_id)
    pinboard_items.where(project_id: project_id).order('pinned_object_type DESC, position').to_a.group_by { |a| a.pinned_object_type }
  end

  # @return [Integer]
  #   the total records of this klass created by this user
  def total_objects(klass) # klass_name is a string, need .constantize in next line
    klass.where(creator: self).count
  end

  def total_objects2(klass_string)
    self.send("created_#{klass_string}").count #klass.where(creator:self).count
  end

  # @return [Hash]
  #
  # @user.get_class_created_updated # => { "projects" => {created: 10, first_created: datetime, updated: 10, last_updated: datetime} }
  def get_class_created_updated
    Rails.application.eager_load! if Rails.env.development?
    data = {}

    User.reflect_on_all_associations(:has_many).each do |r|
      key = nil
      puts r.name.to_s
      if r.name.to_s =~ /created_/
        # puts "after created"
        key = :created
      elsif r.name.to_s =~ /updated_/
        # puts "after updated"
        key = :updated
      end

      if key
        n     = r.klass.name.underscore.humanize.pluralize
        count = self.send(r.name).count

        if data[n]
          data[n][key] = count
        else
          data[n] = {key => count}
        end

        if count == 0
          data[n][:first_created] = 'n/a'
          data[n][:last_updated]  = 'n/a'
        else
          data[n][:first_created] = self.send(r.name).limit(1).order(created_at: :asc).first.created_at
          data[n][:last_updated]  = self.send(r.name).limit(1).order(updated_at: :desc).first.updated_at
        end
      end
    end
    data
  end

  def generate_api_access_token
    self.api_access_token = Utilities::RandomToken.generate
  end

  def require_password_presence
    @require_password_presence = true
  end

  private

  def set_remember_token
    self.remember_token = User.encrypt(User.secure_random_token)
  end

  def validate_password?
    password.present? || password_confirmation.present? || @require_password_presence
  end

  def configure_self_created
    if !self.new_record? && self.creator.nil? && self.updater.nil?
      self.update_columns(created_by_id: self.id, updated_by_id: self.id) # !?
    end
  end


end

- (Array) hub_tab_order

Returns tabs, referenced as Strings, defining the users preference for their order

Returns:

  • (Array)

    tabs, referenced as Strings, defining the users preference for their order



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
# File 'app/models/user.rb', line 98

class User < ApplicationRecord
  include Housekeeping::Users
  include Housekeeping::Timestamps
  include Housekeeping::AssociationHelpers
  include Shared::DataAttributes
  include Shared::Notes
  include Shared::Tags
  include Shared::Identifiers
  include Shared::RandomTokenFields[:password_reset]
  has_secure_password

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  attr_accessor :set_new_api_access_token
  attr_accessor :self_created

  before_validation { self.email = email.to_s.downcase }

  before_save :generate_api_access_token, if: :set_new_api_access_token
  # @todo downcase does not work for non-ascii characters which means our validation for uniqueness will fail ... why?
  # @see http://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-email-address
  # @see http://unicode-utils.rubyforge.org/
  before_save { self.email = email.to_s.downcase }

  after_save :configure_self_created, if: :self_created

  before_create :set_remember_token
  before_create { self.hub_tab_order = DEFAULT_HUB_TAB_ORDER }

  validates :email, presence: true,
            format:           {with: VALID_EMAIL_REGEX},
            uniqueness:       true

  validates :password,
            length:       {minimum: 8, :if => :validate_password?},
            :confirmation => {:if => :validate_password?}

  validates :name, presence: true
  validates :name, length: {minimum: 2}, unless: -> { self.name.blank? }

  has_many :project_members, dependent: :destroy
  has_many :projects, through: :project_members
  has_many :pinboard_items, dependent: :destroy

  scope :is_administrator, -> { where(is_administrator: true) }

  def administered_projects
    projects.where(id: project_members.where(is_project_administrator: true).pluck(:project_id))
  end

  def administers_projects?
    administered_projects.any?
  end

  # @param [String, User, Integer] user
  # @return [Integer] selected user id
  def self.get_user_id(user)
    # no way to know who the current user is, so can't pre-set user_id
    case user.class.name
      when 'String'
        # search by name or email
        ut     = User.arel_table
        c1     = ut[:name].eq(user).or(ut[:email].eq(user.downcase)).to_sql
        t_user = User.where(c1).first
        if t_user.present?
          user_id = t_user.id
        else  # try to convert to a number, to see if it came directly from a web page
          t_user = user.to_i
          if t_user > 0
            t_user = User.find(t_user).try(:id)
          else
            t_user = nil
          end
          user_id = t_user
        end
      when 'User'
        user_id = user.id
      when 'Integer'
        user_id = user
    end
    user_id
  end

  # @param [String, User, Integer, Array] users
  # @return [Array of Integers] selected user ids
  def self.get_user_ids(*users)
    user_ids = []
    users.flatten.each { |user|
      case user.class.name
        when 'String'
          # search by name or email
          ut = User.arel_table
          c1 = ut[:name].eq(user)
                 .or(ut[:name].matches("%#{user}"))
                 .or(ut[:name].matches("%#{user}%"))
                 .or(ut[:email].eq(user))
                 .or(ut[:email].matches("%#{user}"))
                 .or(ut[:email].matches("%#{user}%")).to_sql
          user_ids.push(User.where(c1).pluck(:id))
        when 'User'
          user_ids.push(user.id)
        when 'Integer'
          user_ids.push(user)
      end
    }
    user_ids.flatten.uniq
  end

  def self.not_in_project(project_id)
    ids = ProjectMember.where(project_id: project_id).pluck(:user_id)
    return where(false) if ids.empty?

    User.where(User.arel_table[:id].not_eq_all(ids))
  end

  # @param [Integer] project_id
  # @return [Scope] of ids for users in the project
  def self.in_project(project_id = $project_id)
    ProjectMember.where(project_id: project_id).distinct.pluck(:user_id)
  end

  def User.secure_random_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  # @return [true, false]
  # true if user is_administrator or is_project_administrator
  def is_superuser?(project = nil)
    is_administrator || is_project_administrator?(project)
  end

  # @return [Boolean]
  # true if is_administrator = true
  def is_administrator?
    is_administrator.blank? ? false : true
  end

  # @return [true, false]
  # true if user is_project_administrator for the project passed
  # @param project [Project]
  def is_project_administrator?(project = nil)
    return false if project.nil?
    project.project_members.where(user_id: id).first.is_project_administrator
  end

  # @params [Project, Integer]
  # @return [Boolean]
  def member_of?(project)
    ProjectMember.where(project_id: project, user_id: self.id).any?
  end

  def hub_favorites
    read_attribute(:hub_favorites) || {}
  end

  def add_page_to_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    n       = options[:name]
    p       = options[:project_id].to_s
    k       = options[:kind]
    u       = hub_favorites.clone

    u[p]    = {'data' => [], 'tasks' => []} if !u[p]
    u[p][k] = u[p][k].push(n).uniq[0..19].sort

    update_column(:hub_favorites, u)
    true
  end

  def remove_page_from_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    new_routes = hub_favorites.clone
    new_routes[options['project_id'].to_s][options['kind']].delete(options['name'])
    update_column(:hub_favorites, new_routes)
  end

  def validate_favorite_options(options)
    return false if !options.select { |k, v| k.nil? || v.nil? }.empty?
    return false if !member_of?(options['project_id'])
    true
  end

  def update_last_seen_at

    a = 0

    if !last_seen_at.nil?
      t = Time.now - last_seen_at
      a = t < 301 ? time_active + t : time_active
    end

    update_columns(last_seen_at: Time.now, time_active: a)

  end

  def add_recently_visited_to_footprint(recent_route, recent_object = nil)
    case recent_route
      when /\A\/\Z/ # the root path '/'
      when /\A\/hub/ # any path which starts with '/hub'
      when /\/autocomplete\?/ # any path used for AJAX autocomplete
      else

        fp                     = footprints.dup
        fp['recently_visited'] ||= []

        attrs = {recent_route => {}}
        if !recent_object.nil?
          attrs[recent_route].merge!(object_type: recent_object.class.to_s, object_id: recent_object.id)
        end

        fp['recently_visited'].unshift(attrs)
        fp['recently_visited'] = fp['recently_visited'].uniq { |a| a.keys }[0..19]

        self.footprints_will_change! # if this isn't thrown weird caching happens !
        self.update_column(:footprints, fp)
    end

    true
  end

  # TODO:  This needs to show cross-project pinboard items as well
  def pinboard_hash(project_id)
    pinboard_items.where(project_id: project_id).order('pinned_object_type DESC, position').to_a.group_by { |a| a.pinned_object_type }
  end

  # @return [Integer]
  #   the total records of this klass created by this user
  def total_objects(klass) # klass_name is a string, need .constantize in next line
    klass.where(creator: self).count
  end

  def total_objects2(klass_string)
    self.send("created_#{klass_string}").count #klass.where(creator:self).count
  end

  # @return [Hash]
  #
  # @user.get_class_created_updated # => { "projects" => {created: 10, first_created: datetime, updated: 10, last_updated: datetime} }
  def get_class_created_updated
    Rails.application.eager_load! if Rails.env.development?
    data = {}

    User.reflect_on_all_associations(:has_many).each do |r|
      key = nil
      puts r.name.to_s
      if r.name.to_s =~ /created_/
        # puts "after created"
        key = :created
      elsif r.name.to_s =~ /updated_/
        # puts "after updated"
        key = :updated
      end

      if key
        n     = r.klass.name.underscore.humanize.pluralize
        count = self.send(r.name).count

        if data[n]
          data[n][key] = count
        else
          data[n] = {key => count}
        end

        if count == 0
          data[n][:first_created] = 'n/a'
          data[n][:last_updated]  = 'n/a'
        else
          data[n][:first_created] = self.send(r.name).limit(1).order(created_at: :asc).first.created_at
          data[n][:last_updated]  = self.send(r.name).limit(1).order(updated_at: :desc).first.updated_at
        end
      end
    end
    data
  end

  def generate_api_access_token
    self.api_access_token = Utilities::RandomToken.generate
  end

  def require_password_presence
    @require_password_presence = true
  end

  private

  def set_remember_token
    self.remember_token = User.encrypt(User.secure_random_token)
  end

  def validate_password?
    password.present? || password_confirmation.present? || @require_password_presence
  end

  def configure_self_created
    if !self.new_record? && self.creator.nil? && self.updater.nil?
      self.update_columns(created_by_id: self.id, updated_by_id: self.id) # !?
    end
  end


end

- (Boolean) is_administrator

Returns true if user is an administrator, administrators can do everything in any project taxonworks

Returns:

  • (Boolean)

    true if user is an administrator, administrators can do everything in any project taxonworks



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
# File 'app/models/user.rb', line 98

class User < ApplicationRecord
  include Housekeeping::Users
  include Housekeeping::Timestamps
  include Housekeeping::AssociationHelpers
  include Shared::DataAttributes
  include Shared::Notes
  include Shared::Tags
  include Shared::Identifiers
  include Shared::RandomTokenFields[:password_reset]
  has_secure_password

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  attr_accessor :set_new_api_access_token
  attr_accessor :self_created

  before_validation { self.email = email.to_s.downcase }

  before_save :generate_api_access_token, if: :set_new_api_access_token
  # @todo downcase does not work for non-ascii characters which means our validation for uniqueness will fail ... why?
  # @see http://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-email-address
  # @see http://unicode-utils.rubyforge.org/
  before_save { self.email = email.to_s.downcase }

  after_save :configure_self_created, if: :self_created

  before_create :set_remember_token
  before_create { self.hub_tab_order = DEFAULT_HUB_TAB_ORDER }

  validates :email, presence: true,
            format:           {with: VALID_EMAIL_REGEX},
            uniqueness:       true

  validates :password,
            length:       {minimum: 8, :if => :validate_password?},
            :confirmation => {:if => :validate_password?}

  validates :name, presence: true
  validates :name, length: {minimum: 2}, unless: -> { self.name.blank? }

  has_many :project_members, dependent: :destroy
  has_many :projects, through: :project_members
  has_many :pinboard_items, dependent: :destroy

  scope :is_administrator, -> { where(is_administrator: true) }

  def administered_projects
    projects.where(id: project_members.where(is_project_administrator: true).pluck(:project_id))
  end

  def administers_projects?
    administered_projects.any?
  end

  # @param [String, User, Integer] user
  # @return [Integer] selected user id
  def self.get_user_id(user)
    # no way to know who the current user is, so can't pre-set user_id
    case user.class.name
      when 'String'
        # search by name or email
        ut     = User.arel_table
        c1     = ut[:name].eq(user).or(ut[:email].eq(user.downcase)).to_sql
        t_user = User.where(c1).first
        if t_user.present?
          user_id = t_user.id
        else  # try to convert to a number, to see if it came directly from a web page
          t_user = user.to_i
          if t_user > 0
            t_user = User.find(t_user).try(:id)
          else
            t_user = nil
          end
          user_id = t_user
        end
      when 'User'
        user_id = user.id
      when 'Integer'
        user_id = user
    end
    user_id
  end

  # @param [String, User, Integer, Array] users
  # @return [Array of Integers] selected user ids
  def self.get_user_ids(*users)
    user_ids = []
    users.flatten.each { |user|
      case user.class.name
        when 'String'
          # search by name or email
          ut = User.arel_table
          c1 = ut[:name].eq(user)
                 .or(ut[:name].matches("%#{user}"))
                 .or(ut[:name].matches("%#{user}%"))
                 .or(ut[:email].eq(user))
                 .or(ut[:email].matches("%#{user}"))
                 .or(ut[:email].matches("%#{user}%")).to_sql
          user_ids.push(User.where(c1).pluck(:id))
        when 'User'
          user_ids.push(user.id)
        when 'Integer'
          user_ids.push(user)
      end
    }
    user_ids.flatten.uniq
  end

  def self.not_in_project(project_id)
    ids = ProjectMember.where(project_id: project_id).pluck(:user_id)
    return where(false) if ids.empty?

    User.where(User.arel_table[:id].not_eq_all(ids))
  end

  # @param [Integer] project_id
  # @return [Scope] of ids for users in the project
  def self.in_project(project_id = $project_id)
    ProjectMember.where(project_id: project_id).distinct.pluck(:user_id)
  end

  def User.secure_random_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  # @return [true, false]
  # true if user is_administrator or is_project_administrator
  def is_superuser?(project = nil)
    is_administrator || is_project_administrator?(project)
  end

  # @return [Boolean]
  # true if is_administrator = true
  def is_administrator?
    is_administrator.blank? ? false : true
  end

  # @return [true, false]
  # true if user is_project_administrator for the project passed
  # @param project [Project]
  def is_project_administrator?(project = nil)
    return false if project.nil?
    project.project_members.where(user_id: id).first.is_project_administrator
  end

  # @params [Project, Integer]
  # @return [Boolean]
  def member_of?(project)
    ProjectMember.where(project_id: project, user_id: self.id).any?
  end

  def hub_favorites
    read_attribute(:hub_favorites) || {}
  end

  def add_page_to_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    n       = options[:name]
    p       = options[:project_id].to_s
    k       = options[:kind]
    u       = hub_favorites.clone

    u[p]    = {'data' => [], 'tasks' => []} if !u[p]
    u[p][k] = u[p][k].push(n).uniq[0..19].sort

    update_column(:hub_favorites, u)
    true
  end

  def remove_page_from_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    new_routes = hub_favorites.clone
    new_routes[options['project_id'].to_s][options['kind']].delete(options['name'])
    update_column(:hub_favorites, new_routes)
  end

  def validate_favorite_options(options)
    return false if !options.select { |k, v| k.nil? || v.nil? }.empty?
    return false if !member_of?(options['project_id'])
    true
  end

  def update_last_seen_at

    a = 0

    if !last_seen_at.nil?
      t = Time.now - last_seen_at
      a = t < 301 ? time_active + t : time_active
    end

    update_columns(last_seen_at: Time.now, time_active: a)

  end

  def add_recently_visited_to_footprint(recent_route, recent_object = nil)
    case recent_route
      when /\A\/\Z/ # the root path '/'
      when /\A\/hub/ # any path which starts with '/hub'
      when /\/autocomplete\?/ # any path used for AJAX autocomplete
      else

        fp                     = footprints.dup
        fp['recently_visited'] ||= []

        attrs = {recent_route => {}}
        if !recent_object.nil?
          attrs[recent_route].merge!(object_type: recent_object.class.to_s, object_id: recent_object.id)
        end

        fp['recently_visited'].unshift(attrs)
        fp['recently_visited'] = fp['recently_visited'].uniq { |a| a.keys }[0..19]

        self.footprints_will_change! # if this isn't thrown weird caching happens !
        self.update_column(:footprints, fp)
    end

    true
  end

  # TODO:  This needs to show cross-project pinboard items as well
  def pinboard_hash(project_id)
    pinboard_items.where(project_id: project_id).order('pinned_object_type DESC, position').to_a.group_by { |a| a.pinned_object_type }
  end

  # @return [Integer]
  #   the total records of this klass created by this user
  def total_objects(klass) # klass_name is a string, need .constantize in next line
    klass.where(creator: self).count
  end

  def total_objects2(klass_string)
    self.send("created_#{klass_string}").count #klass.where(creator:self).count
  end

  # @return [Hash]
  #
  # @user.get_class_created_updated # => { "projects" => {created: 10, first_created: datetime, updated: 10, last_updated: datetime} }
  def get_class_created_updated
    Rails.application.eager_load! if Rails.env.development?
    data = {}

    User.reflect_on_all_associations(:has_many).each do |r|
      key = nil
      puts r.name.to_s
      if r.name.to_s =~ /created_/
        # puts "after created"
        key = :created
      elsif r.name.to_s =~ /updated_/
        # puts "after updated"
        key = :updated
      end

      if key
        n     = r.klass.name.underscore.humanize.pluralize
        count = self.send(r.name).count

        if data[n]
          data[n][key] = count
        else
          data[n] = {key => count}
        end

        if count == 0
          data[n][:first_created] = 'n/a'
          data[n][:last_updated]  = 'n/a'
        else
          data[n][:first_created] = self.send(r.name).limit(1).order(created_at: :asc).first.created_at
          data[n][:last_updated]  = self.send(r.name).limit(1).order(updated_at: :desc).first.updated_at
        end
      end
    end
    data
  end

  def generate_api_access_token
    self.api_access_token = Utilities::RandomToken.generate
  end

  def require_password_presence
    @require_password_presence = true
  end

  private

  def set_remember_token
    self.remember_token = User.encrypt(User.secure_random_token)
  end

  def validate_password?
    password.present? || password_confirmation.present? || @require_password_presence
  end

  def configure_self_created
    if !self.new_record? && self.creator.nil? && self.updater.nil?
      self.update_columns(created_by_id: self.id, updated_by_id: self.id) # !?
    end
  end


end

- (Boolean) is_flagged_for_password_reset

Returns when true user must reset their password before doing anything further

Returns:

  • (Boolean)

    when true user must reset their password before doing anything further



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
# File 'app/models/user.rb', line 98

class User < ApplicationRecord
  include Housekeeping::Users
  include Housekeeping::Timestamps
  include Housekeeping::AssociationHelpers
  include Shared::DataAttributes
  include Shared::Notes
  include Shared::Tags
  include Shared::Identifiers
  include Shared::RandomTokenFields[:password_reset]
  has_secure_password

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  attr_accessor :set_new_api_access_token
  attr_accessor :self_created

  before_validation { self.email = email.to_s.downcase }

  before_save :generate_api_access_token, if: :set_new_api_access_token
  # @todo downcase does not work for non-ascii characters which means our validation for uniqueness will fail ... why?
  # @see http://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-email-address
  # @see http://unicode-utils.rubyforge.org/
  before_save { self.email = email.to_s.downcase }

  after_save :configure_self_created, if: :self_created

  before_create :set_remember_token
  before_create { self.hub_tab_order = DEFAULT_HUB_TAB_ORDER }

  validates :email, presence: true,
            format:           {with: VALID_EMAIL_REGEX},
            uniqueness:       true

  validates :password,
            length:       {minimum: 8, :if => :validate_password?},
            :confirmation => {:if => :validate_password?}

  validates :name, presence: true
  validates :name, length: {minimum: 2}, unless: -> { self.name.blank? }

  has_many :project_members, dependent: :destroy
  has_many :projects, through: :project_members
  has_many :pinboard_items, dependent: :destroy

  scope :is_administrator, -> { where(is_administrator: true) }

  def administered_projects
    projects.where(id: project_members.where(is_project_administrator: true).pluck(:project_id))
  end

  def administers_projects?
    administered_projects.any?
  end

  # @param [String, User, Integer] user
  # @return [Integer] selected user id
  def self.get_user_id(user)
    # no way to know who the current user is, so can't pre-set user_id
    case user.class.name
      when 'String'
        # search by name or email
        ut     = User.arel_table
        c1     = ut[:name].eq(user).or(ut[:email].eq(user.downcase)).to_sql
        t_user = User.where(c1).first
        if t_user.present?
          user_id = t_user.id
        else  # try to convert to a number, to see if it came directly from a web page
          t_user = user.to_i
          if t_user > 0
            t_user = User.find(t_user).try(:id)
          else
            t_user = nil
          end
          user_id = t_user
        end
      when 'User'
        user_id = user.id
      when 'Integer'
        user_id = user
    end
    user_id
  end

  # @param [String, User, Integer, Array] users
  # @return [Array of Integers] selected user ids
  def self.get_user_ids(*users)
    user_ids = []
    users.flatten.each { |user|
      case user.class.name
        when 'String'
          # search by name or email
          ut = User.arel_table
          c1 = ut[:name].eq(user)
                 .or(ut[:name].matches("%#{user}"))
                 .or(ut[:name].matches("%#{user}%"))
                 .or(ut[:email].eq(user))
                 .or(ut[:email].matches("%#{user}"))
                 .or(ut[:email].matches("%#{user}%")).to_sql
          user_ids.push(User.where(c1).pluck(:id))
        when 'User'
          user_ids.push(user.id)
        when 'Integer'
          user_ids.push(user)
      end
    }
    user_ids.flatten.uniq
  end

  def self.not_in_project(project_id)
    ids = ProjectMember.where(project_id: project_id).pluck(:user_id)
    return where(false) if ids.empty?

    User.where(User.arel_table[:id].not_eq_all(ids))
  end

  # @param [Integer] project_id
  # @return [Scope] of ids for users in the project
  def self.in_project(project_id = $project_id)
    ProjectMember.where(project_id: project_id).distinct.pluck(:user_id)
  end

  def User.secure_random_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  # @return [true, false]
  # true if user is_administrator or is_project_administrator
  def is_superuser?(project = nil)
    is_administrator || is_project_administrator?(project)
  end

  # @return [Boolean]
  # true if is_administrator = true
  def is_administrator?
    is_administrator.blank? ? false : true
  end

  # @return [true, false]
  # true if user is_project_administrator for the project passed
  # @param project [Project]
  def is_project_administrator?(project = nil)
    return false if project.nil?
    project.project_members.where(user_id: id).first.is_project_administrator
  end

  # @params [Project, Integer]
  # @return [Boolean]
  def member_of?(project)
    ProjectMember.where(project_id: project, user_id: self.id).any?
  end

  def hub_favorites
    read_attribute(:hub_favorites) || {}
  end

  def add_page_to_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    n       = options[:name]
    p       = options[:project_id].to_s
    k       = options[:kind]
    u       = hub_favorites.clone

    u[p]    = {'data' => [], 'tasks' => []} if !u[p]
    u[p][k] = u[p][k].push(n).uniq[0..19].sort

    update_column(:hub_favorites, u)
    true
  end

  def remove_page_from_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    new_routes = hub_favorites.clone
    new_routes[options['project_id'].to_s][options['kind']].delete(options['name'])
    update_column(:hub_favorites, new_routes)
  end

  def validate_favorite_options(options)
    return false if !options.select { |k, v| k.nil? || v.nil? }.empty?
    return false if !member_of?(options['project_id'])
    true
  end

  def update_last_seen_at

    a = 0

    if !last_seen_at.nil?
      t = Time.now - last_seen_at
      a = t < 301 ? time_active + t : time_active
    end

    update_columns(last_seen_at: Time.now, time_active: a)

  end

  def add_recently_visited_to_footprint(recent_route, recent_object = nil)
    case recent_route
      when /\A\/\Z/ # the root path '/'
      when /\A\/hub/ # any path which starts with '/hub'
      when /\/autocomplete\?/ # any path used for AJAX autocomplete
      else

        fp                     = footprints.dup
        fp['recently_visited'] ||= []

        attrs = {recent_route => {}}
        if !recent_object.nil?
          attrs[recent_route].merge!(object_type: recent_object.class.to_s, object_id: recent_object.id)
        end

        fp['recently_visited'].unshift(attrs)
        fp['recently_visited'] = fp['recently_visited'].uniq { |a| a.keys }[0..19]

        self.footprints_will_change! # if this isn't thrown weird caching happens !
        self.update_column(:footprints, fp)
    end

    true
  end

  # TODO:  This needs to show cross-project pinboard items as well
  def pinboard_hash(project_id)
    pinboard_items.where(project_id: project_id).order('pinned_object_type DESC, position').to_a.group_by { |a| a.pinned_object_type }
  end

  # @return [Integer]
  #   the total records of this klass created by this user
  def total_objects(klass) # klass_name is a string, need .constantize in next line
    klass.where(creator: self).count
  end

  def total_objects2(klass_string)
    self.send("created_#{klass_string}").count #klass.where(creator:self).count
  end

  # @return [Hash]
  #
  # @user.get_class_created_updated # => { "projects" => {created: 10, first_created: datetime, updated: 10, last_updated: datetime} }
  def get_class_created_updated
    Rails.application.eager_load! if Rails.env.development?
    data = {}

    User.reflect_on_all_associations(:has_many).each do |r|
      key = nil
      puts r.name.to_s
      if r.name.to_s =~ /created_/
        # puts "after created"
        key = :created
      elsif r.name.to_s =~ /updated_/
        # puts "after updated"
        key = :updated
      end

      if key
        n     = r.klass.name.underscore.humanize.pluralize
        count = self.send(r.name).count

        if data[n]
          data[n][key] = count
        else
          data[n] = {key => count}
        end

        if count == 0
          data[n][:first_created] = 'n/a'
          data[n][:last_updated]  = 'n/a'
        else
          data[n][:first_created] = self.send(r.name).limit(1).order(created_at: :asc).first.created_at
          data[n][:last_updated]  = self.send(r.name).limit(1).order(updated_at: :desc).first.updated_at
        end
      end
    end
    data
  end

  def generate_api_access_token
    self.api_access_token = Utilities::RandomToken.generate
  end

  def require_password_presence
    @require_password_presence = true
  end

  private

  def set_remember_token
    self.remember_token = User.encrypt(User.secure_random_token)
  end

  def validate_password?
    password.present? || password_confirmation.present? || @require_password_presence
  end

  def configure_self_created
    if !self.new_record? && self.creator.nil? && self.updater.nil?
      self.update_columns(created_by_id: self.id, updated_by_id: self.id) # !?
    end
  end


end

- (ActiveSupport::TimeWithZone) last_sign_in_at

Returns time of sign in prior to this sign in

Returns:

  • (ActiveSupport::TimeWithZone)

    time of sign in prior to this sign in



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
# File 'app/models/user.rb', line 98

class User < ApplicationRecord
  include Housekeeping::Users
  include Housekeeping::Timestamps
  include Housekeeping::AssociationHelpers
  include Shared::DataAttributes
  include Shared::Notes
  include Shared::Tags
  include Shared::Identifiers
  include Shared::RandomTokenFields[:password_reset]
  has_secure_password

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  attr_accessor :set_new_api_access_token
  attr_accessor :self_created

  before_validation { self.email = email.to_s.downcase }

  before_save :generate_api_access_token, if: :set_new_api_access_token
  # @todo downcase does not work for non-ascii characters which means our validation for uniqueness will fail ... why?
  # @see http://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-email-address
  # @see http://unicode-utils.rubyforge.org/
  before_save { self.email = email.to_s.downcase }

  after_save :configure_self_created, if: :self_created

  before_create :set_remember_token
  before_create { self.hub_tab_order = DEFAULT_HUB_TAB_ORDER }

  validates :email, presence: true,
            format:           {with: VALID_EMAIL_REGEX},
            uniqueness:       true

  validates :password,
            length:       {minimum: 8, :if => :validate_password?},
            :confirmation => {:if => :validate_password?}

  validates :name, presence: true
  validates :name, length: {minimum: 2}, unless: -> { self.name.blank? }

  has_many :project_members, dependent: :destroy
  has_many :projects, through: :project_members
  has_many :pinboard_items, dependent: :destroy

  scope :is_administrator, -> { where(is_administrator: true) }

  def administered_projects
    projects.where(id: project_members.where(is_project_administrator: true).pluck(:project_id))
  end

  def administers_projects?
    administered_projects.any?
  end

  # @param [String, User, Integer] user
  # @return [Integer] selected user id
  def self.get_user_id(user)
    # no way to know who the current user is, so can't pre-set user_id
    case user.class.name
      when 'String'
        # search by name or email
        ut     = User.arel_table
        c1     = ut[:name].eq(user).or(ut[:email].eq(user.downcase)).to_sql
        t_user = User.where(c1).first
        if t_user.present?
          user_id = t_user.id
        else  # try to convert to a number, to see if it came directly from a web page
          t_user = user.to_i
          if t_user > 0
            t_user = User.find(t_user).try(:id)
          else
            t_user = nil
          end
          user_id = t_user
        end
      when 'User'
        user_id = user.id
      when 'Integer'
        user_id = user
    end
    user_id
  end

  # @param [String, User, Integer, Array] users
  # @return [Array of Integers] selected user ids
  def self.get_user_ids(*users)
    user_ids = []
    users.flatten.each { |user|
      case user.class.name
        when 'String'
          # search by name or email
          ut = User.arel_table
          c1 = ut[:name].eq(user)
                 .or(ut[:name].matches("%#{user}"))
                 .or(ut[:name].matches("%#{user}%"))
                 .or(ut[:email].eq(user))
                 .or(ut[:email].matches("%#{user}"))
                 .or(ut[:email].matches("%#{user}%")).to_sql
          user_ids.push(User.where(c1).pluck(:id))
        when 'User'
          user_ids.push(user.id)
        when 'Integer'
          user_ids.push(user)
      end
    }
    user_ids.flatten.uniq
  end

  def self.not_in_project(project_id)
    ids = ProjectMember.where(project_id: project_id).pluck(:user_id)
    return where(false) if ids.empty?

    User.where(User.arel_table[:id].not_eq_all(ids))
  end

  # @param [Integer] project_id
  # @return [Scope] of ids for users in the project
  def self.in_project(project_id = $project_id)
    ProjectMember.where(project_id: project_id).distinct.pluck(:user_id)
  end

  def User.secure_random_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  # @return [true, false]
  # true if user is_administrator or is_project_administrator
  def is_superuser?(project = nil)
    is_administrator || is_project_administrator?(project)
  end

  # @return [Boolean]
  # true if is_administrator = true
  def is_administrator?
    is_administrator.blank? ? false : true
  end

  # @return [true, false]
  # true if user is_project_administrator for the project passed
  # @param project [Project]
  def is_project_administrator?(project = nil)
    return false if project.nil?
    project.project_members.where(user_id: id).first.is_project_administrator
  end

  # @params [Project, Integer]
  # @return [Boolean]
  def member_of?(project)
    ProjectMember.where(project_id: project, user_id: self.id).any?
  end

  def hub_favorites
    read_attribute(:hub_favorites) || {}
  end

  def add_page_to_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    n       = options[:name]
    p       = options[:project_id].to_s
    k       = options[:kind]
    u       = hub_favorites.clone

    u[p]    = {'data' => [], 'tasks' => []} if !u[p]
    u[p][k] = u[p][k].push(n).uniq[0..19].sort

    update_column(:hub_favorites, u)
    true
  end

  def remove_page_from_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    new_routes = hub_favorites.clone
    new_routes[options['project_id'].to_s][options['kind']].delete(options['name'])
    update_column(:hub_favorites, new_routes)
  end

  def validate_favorite_options(options)
    return false if !options.select { |k, v| k.nil? || v.nil? }.empty?
    return false if !member_of?(options['project_id'])
    true
  end

  def update_last_seen_at

    a = 0

    if !last_seen_at.nil?
      t = Time.now - last_seen_at
      a = t < 301 ? time_active + t : time_active
    end

    update_columns(last_seen_at: Time.now, time_active: a)

  end

  def add_recently_visited_to_footprint(recent_route, recent_object = nil)
    case recent_route
      when /\A\/\Z/ # the root path '/'
      when /\A\/hub/ # any path which starts with '/hub'
      when /\/autocomplete\?/ # any path used for AJAX autocomplete
      else

        fp                     = footprints.dup
        fp['recently_visited'] ||= []

        attrs = {recent_route => {}}
        if !recent_object.nil?
          attrs[recent_route].merge!(object_type: recent_object.class.to_s, object_id: recent_object.id)
        end

        fp['recently_visited'].unshift(attrs)
        fp['recently_visited'] = fp['recently_visited'].uniq { |a| a.keys }[0..19]

        self.footprints_will_change! # if this isn't thrown weird caching happens !
        self.update_column(:footprints, fp)
    end

    true
  end

  # TODO:  This needs to show cross-project pinboard items as well
  def pinboard_hash(project_id)
    pinboard_items.where(project_id: project_id).order('pinned_object_type DESC, position').to_a.group_by { |a| a.pinned_object_type }
  end

  # @return [Integer]
  #   the total records of this klass created by this user
  def total_objects(klass) # klass_name is a string, need .constantize in next line
    klass.where(creator: self).count
  end

  def total_objects2(klass_string)
    self.send("created_#{klass_string}").count #klass.where(creator:self).count
  end

  # @return [Hash]
  #
  # @user.get_class_created_updated # => { "projects" => {created: 10, first_created: datetime, updated: 10, last_updated: datetime} }
  def get_class_created_updated
    Rails.application.eager_load! if Rails.env.development?
    data = {}

    User.reflect_on_all_associations(:has_many).each do |r|
      key = nil
      puts r.name.to_s
      if r.name.to_s =~ /created_/
        # puts "after created"
        key = :created
      elsif r.name.to_s =~ /updated_/
        # puts "after updated"
        key = :updated
      end

      if key
        n     = r.klass.name.underscore.humanize.pluralize
        count = self.send(r.name).count

        if data[n]
          data[n][key] = count
        else
          data[n] = {key => count}
        end

        if count == 0
          data[n][:first_created] = 'n/a'
          data[n][:last_updated]  = 'n/a'
        else
          data[n][:first_created] = self.send(r.name).limit(1).order(created_at: :asc).first.created_at
          data[n][:last_updated]  = self.send(r.name).limit(1).order(updated_at: :desc).first.updated_at
        end
      end
    end
    data
  end

  def generate_api_access_token
    self.api_access_token = Utilities::RandomToken.generate
  end

  def require_password_presence
    @require_password_presence = true
  end

  private

  def set_remember_token
    self.remember_token = User.encrypt(User.secure_random_token)
  end

  def validate_password?
    password.present? || password_confirmation.present? || @require_password_presence
  end

  def configure_self_created
    if !self.new_record? && self.creator.nil? && self.updater.nil?
      self.update_columns(created_by_id: self.id, updated_by_id: self.id) # !?
    end
  end


end

- (String) last_sign_in_ip

Returns IP address of the machine user used to log in from prior to this current log in

Returns:

  • (String)

    IP address of the machine user used to log in from prior to this current log in



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
# File 'app/models/user.rb', line 98

class User < ApplicationRecord
  include Housekeeping::Users
  include Housekeeping::Timestamps
  include Housekeeping::AssociationHelpers
  include Shared::DataAttributes
  include Shared::Notes
  include Shared::Tags
  include Shared::Identifiers
  include Shared::RandomTokenFields[:password_reset]
  has_secure_password

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  attr_accessor :set_new_api_access_token
  attr_accessor :self_created

  before_validation { self.email = email.to_s.downcase }

  before_save :generate_api_access_token, if: :set_new_api_access_token
  # @todo downcase does not work for non-ascii characters which means our validation for uniqueness will fail ... why?
  # @see http://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-email-address
  # @see http://unicode-utils.rubyforge.org/
  before_save { self.email = email.to_s.downcase }

  after_save :configure_self_created, if: :self_created

  before_create :set_remember_token
  before_create { self.hub_tab_order = DEFAULT_HUB_TAB_ORDER }

  validates :email, presence: true,
            format:           {with: VALID_EMAIL_REGEX},
            uniqueness:       true

  validates :password,
            length:       {minimum: 8, :if => :validate_password?},
            :confirmation => {:if => :validate_password?}

  validates :name, presence: true
  validates :name, length: {minimum: 2}, unless: -> { self.name.blank? }

  has_many :project_members, dependent: :destroy
  has_many :projects, through: :project_members
  has_many :pinboard_items, dependent: :destroy

  scope :is_administrator, -> { where(is_administrator: true) }

  def administered_projects
    projects.where(id: project_members.where(is_project_administrator: true).pluck(:project_id))
  end

  def administers_projects?
    administered_projects.any?
  end

  # @param [String, User, Integer] user
  # @return [Integer] selected user id
  def self.get_user_id(user)
    # no way to know who the current user is, so can't pre-set user_id
    case user.class.name
      when 'String'
        # search by name or email
        ut     = User.arel_table
        c1     = ut[:name].eq(user).or(ut[:email].eq(user.downcase)).to_sql
        t_user = User.where(c1).first
        if t_user.present?
          user_id = t_user.id
        else  # try to convert to a number, to see if it came directly from a web page
          t_user = user.to_i
          if t_user > 0
            t_user = User.find(t_user).try(:id)
          else
            t_user = nil
          end
          user_id = t_user
        end
      when 'User'
        user_id = user.id
      when 'Integer'
        user_id = user
    end
    user_id
  end

  # @param [String, User, Integer, Array] users
  # @return [Array of Integers] selected user ids
  def self.get_user_ids(*users)
    user_ids = []
    users.flatten.each { |user|
      case user.class.name
        when 'String'
          # search by name or email
          ut = User.arel_table
          c1 = ut[:name].eq(user)
                 .or(ut[:name].matches("%#{user}"))
                 .or(ut[:name].matches("%#{user}%"))
                 .or(ut[:email].eq(user))
                 .or(ut[:email].matches("%#{user}"))
                 .or(ut[:email].matches("%#{user}%")).to_sql
          user_ids.push(User.where(c1).pluck(:id))
        when 'User'
          user_ids.push(user.id)
        when 'Integer'
          user_ids.push(user)
      end
    }
    user_ids.flatten.uniq
  end

  def self.not_in_project(project_id)
    ids = ProjectMember.where(project_id: project_id).pluck(:user_id)
    return where(false) if ids.empty?

    User.where(User.arel_table[:id].not_eq_all(ids))
  end

  # @param [Integer] project_id
  # @return [Scope] of ids for users in the project
  def self.in_project(project_id = $project_id)
    ProjectMember.where(project_id: project_id).distinct.pluck(:user_id)
  end

  def User.secure_random_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  # @return [true, false]
  # true if user is_administrator or is_project_administrator
  def is_superuser?(project = nil)
    is_administrator || is_project_administrator?(project)
  end

  # @return [Boolean]
  # true if is_administrator = true
  def is_administrator?
    is_administrator.blank? ? false : true
  end

  # @return [true, false]
  # true if user is_project_administrator for the project passed
  # @param project [Project]
  def is_project_administrator?(project = nil)
    return false if project.nil?
    project.project_members.where(user_id: id).first.is_project_administrator
  end

  # @params [Project, Integer]
  # @return [Boolean]
  def member_of?(project)
    ProjectMember.where(project_id: project, user_id: self.id).any?
  end

  def hub_favorites
    read_attribute(:hub_favorites) || {}
  end

  def add_page_to_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    n       = options[:name]
    p       = options[:project_id].to_s
    k       = options[:kind]
    u       = hub_favorites.clone

    u[p]    = {'data' => [], 'tasks' => []} if !u[p]
    u[p][k] = u[p][k].push(n).uniq[0..19].sort

    update_column(:hub_favorites, u)
    true
  end

  def remove_page_from_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    new_routes = hub_favorites.clone
    new_routes[options['project_id'].to_s][options['kind']].delete(options['name'])
    update_column(:hub_favorites, new_routes)
  end

  def validate_favorite_options(options)
    return false if !options.select { |k, v| k.nil? || v.nil? }.empty?
    return false if !member_of?(options['project_id'])
    true
  end

  def update_last_seen_at

    a = 0

    if !last_seen_at.nil?
      t = Time.now - last_seen_at
      a = t < 301 ? time_active + t : time_active
    end

    update_columns(last_seen_at: Time.now, time_active: a)

  end

  def add_recently_visited_to_footprint(recent_route, recent_object = nil)
    case recent_route
      when /\A\/\Z/ # the root path '/'
      when /\A\/hub/ # any path which starts with '/hub'
      when /\/autocomplete\?/ # any path used for AJAX autocomplete
      else

        fp                     = footprints.dup
        fp['recently_visited'] ||= []

        attrs = {recent_route => {}}
        if !recent_object.nil?
          attrs[recent_route].merge!(object_type: recent_object.class.to_s, object_id: recent_object.id)
        end

        fp['recently_visited'].unshift(attrs)
        fp['recently_visited'] = fp['recently_visited'].uniq { |a| a.keys }[0..19]

        self.footprints_will_change! # if this isn't thrown weird caching happens !
        self.update_column(:footprints, fp)
    end

    true
  end

  # TODO:  This needs to show cross-project pinboard items as well
  def pinboard_hash(project_id)
    pinboard_items.where(project_id: project_id).order('pinned_object_type DESC, position').to_a.group_by { |a| a.pinned_object_type }
  end

  # @return [Integer]
  #   the total records of this klass created by this user
  def total_objects(klass) # klass_name is a string, need .constantize in next line
    klass.where(creator: self).count
  end

  def total_objects2(klass_string)
    self.send("created_#{klass_string}").count #klass.where(creator:self).count
  end

  # @return [Hash]
  #
  # @user.get_class_created_updated # => { "projects" => {created: 10, first_created: datetime, updated: 10, last_updated: datetime} }
  def get_class_created_updated
    Rails.application.eager_load! if Rails.env.development?
    data = {}

    User.reflect_on_all_associations(:has_many).each do |r|
      key = nil
      puts r.name.to_s
      if r.name.to_s =~ /created_/
        # puts "after created"
        key = :created
      elsif r.name.to_s =~ /updated_/
        # puts "after updated"
        key = :updated
      end

      if key
        n     = r.klass.name.underscore.humanize.pluralize
        count = self.send(r.name).count

        if data[n]
          data[n][key] = count
        else
          data[n] = {key => count}
        end

        if count == 0
          data[n][:first_created] = 'n/a'
          data[n][:last_updated]  = 'n/a'
        else
          data[n][:first_created] = self.send(r.name).limit(1).order(created_at: :asc).first.created_at
          data[n][:last_updated]  = self.send(r.name).limit(1).order(updated_at: :desc).first.updated_at
        end
      end
    end
    data
  end

  def generate_api_access_token
    self.api_access_token = Utilities::RandomToken.generate
  end

  def require_password_presence
    @require_password_presence = true
  end

  private

  def set_remember_token
    self.remember_token = User.encrypt(User.secure_random_token)
  end

  def validate_password?
    password.present? || password_confirmation.present? || @require_password_presence
  end

  def configure_self_created
    if !self.new_record? && self.creator.nil? && self.updater.nil?
      self.update_columns(created_by_id: self.id, updated_by_id: self.id) # !?
    end
  end


end

- (String) name

a users name: Not intended to be a nickname, but this is loosely enforced. Attribute is intended to identify a human who owns this account.

Returns:

  • (String)


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
# File 'app/models/user.rb', line 98

class User < ApplicationRecord
  include Housekeeping::Users
  include Housekeeping::Timestamps
  include Housekeeping::AssociationHelpers
  include Shared::DataAttributes
  include Shared::Notes
  include Shared::Tags
  include Shared::Identifiers
  include Shared::RandomTokenFields[:password_reset]
  has_secure_password

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  attr_accessor :set_new_api_access_token
  attr_accessor :self_created

  before_validation { self.email = email.to_s.downcase }

  before_save :generate_api_access_token, if: :set_new_api_access_token
  # @todo downcase does not work for non-ascii characters which means our validation for uniqueness will fail ... why?
  # @see http://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-email-address
  # @see http://unicode-utils.rubyforge.org/
  before_save { self.email = email.to_s.downcase }

  after_save :configure_self_created, if: :self_created

  before_create :set_remember_token
  before_create { self.hub_tab_order = DEFAULT_HUB_TAB_ORDER }

  validates :email, presence: true,
            format:           {with: VALID_EMAIL_REGEX},
            uniqueness:       true

  validates :password,
            length:       {minimum: 8, :if => :validate_password?},
            :confirmation => {:if => :validate_password?}

  validates :name, presence: true
  validates :name, length: {minimum: 2}, unless: -> { self.name.blank? }

  has_many :project_members, dependent: :destroy
  has_many :projects, through: :project_members
  has_many :pinboard_items, dependent: :destroy

  scope :is_administrator, -> { where(is_administrator: true) }

  def administered_projects
    projects.where(id: project_members.where(is_project_administrator: true).pluck(:project_id))
  end

  def administers_projects?
    administered_projects.any?
  end

  # @param [String, User, Integer] user
  # @return [Integer] selected user id
  def self.get_user_id(user)
    # no way to know who the current user is, so can't pre-set user_id
    case user.class.name
      when 'String'
        # search by name or email
        ut     = User.arel_table
        c1     = ut[:name].eq(user).or(ut[:email].eq(user.downcase)).to_sql
        t_user = User.where(c1).first
        if t_user.present?
          user_id = t_user.id
        else  # try to convert to a number, to see if it came directly from a web page
          t_user = user.to_i
          if t_user > 0
            t_user = User.find(t_user).try(:id)
          else
            t_user = nil
          end
          user_id = t_user
        end
      when 'User'
        user_id = user.id
      when 'Integer'
        user_id = user
    end
    user_id
  end

  # @param [String, User, Integer, Array] users
  # @return [Array of Integers] selected user ids
  def self.get_user_ids(*users)
    user_ids = []
    users.flatten.each { |user|
      case user.class.name
        when 'String'
          # search by name or email
          ut = User.arel_table
          c1 = ut[:name].eq(user)
                 .or(ut[:name].matches("%#{user}"))
                 .or(ut[:name].matches("%#{user}%"))
                 .or(ut[:email].eq(user))
                 .or(ut[:email].matches("%#{user}"))
                 .or(ut[:email].matches("%#{user}%")).to_sql
          user_ids.push(User.where(c1).pluck(:id))
        when 'User'
          user_ids.push(user.id)
        when 'Integer'
          user_ids.push(user)
      end
    }
    user_ids.flatten.uniq
  end

  def self.not_in_project(project_id)
    ids = ProjectMember.where(project_id: project_id).pluck(:user_id)
    return where(false) if ids.empty?

    User.where(User.arel_table[:id].not_eq_all(ids))
  end

  # @param [Integer] project_id
  # @return [Scope] of ids for users in the project
  def self.in_project(project_id = $project_id)
    ProjectMember.where(project_id: project_id).distinct.pluck(:user_id)
  end

  def User.secure_random_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  # @return [true, false]
  # true if user is_administrator or is_project_administrator
  def is_superuser?(project = nil)
    is_administrator || is_project_administrator?(project)
  end

  # @return [Boolean]
  # true if is_administrator = true
  def is_administrator?
    is_administrator.blank? ? false : true
  end

  # @return [true, false]
  # true if user is_project_administrator for the project passed
  # @param project [Project]
  def is_project_administrator?(project = nil)
    return false if project.nil?
    project.project_members.where(user_id: id).first.is_project_administrator
  end

  # @params [Project, Integer]
  # @return [Boolean]
  def member_of?(project)
    ProjectMember.where(project_id: project, user_id: self.id).any?
  end

  def hub_favorites
    read_attribute(:hub_favorites) || {}
  end

  def add_page_to_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    n       = options[:name]
    p       = options[:project_id].to_s
    k       = options[:kind]
    u       = hub_favorites.clone

    u[p]    = {'data' => [], 'tasks' => []} if !u[p]
    u[p][k] = u[p][k].push(n).uniq[0..19].sort

    update_column(:hub_favorites, u)
    true
  end

  def remove_page_from_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    new_routes = hub_favorites.clone
    new_routes[options['project_id'].to_s][options['kind']].delete(options['name'])
    update_column(:hub_favorites, new_routes)
  end

  def validate_favorite_options(options)
    return false if !options.select { |k, v| k.nil? || v.nil? }.empty?
    return false if !member_of?(options['project_id'])
    true
  end

  def update_last_seen_at

    a = 0

    if !last_seen_at.nil?
      t = Time.now - last_seen_at
      a = t < 301 ? time_active + t : time_active
    end

    update_columns(last_seen_at: Time.now, time_active: a)

  end

  def add_recently_visited_to_footprint(recent_route, recent_object = nil)
    case recent_route
      when /\A\/\Z/ # the root path '/'
      when /\A\/hub/ # any path which starts with '/hub'
      when /\/autocomplete\?/ # any path used for AJAX autocomplete
      else

        fp                     = footprints.dup
        fp['recently_visited'] ||= []

        attrs = {recent_route => {}}
        if !recent_object.nil?
          attrs[recent_route].merge!(object_type: recent_object.class.to_s, object_id: recent_object.id)
        end

        fp['recently_visited'].unshift(attrs)
        fp['recently_visited'] = fp['recently_visited'].uniq { |a| a.keys }[0..19]

        self.footprints_will_change! # if this isn't thrown weird caching happens !
        self.update_column(:footprints, fp)
    end

    true
  end

  # TODO:  This needs to show cross-project pinboard items as well
  def pinboard_hash(project_id)
    pinboard_items.where(project_id: project_id).order('pinned_object_type DESC, position').to_a.group_by { |a| a.pinned_object_type }
  end

  # @return [Integer]
  #   the total records of this klass created by this user
  def total_objects(klass) # klass_name is a string, need .constantize in next line
    klass.where(creator: self).count
  end

  def total_objects2(klass_string)
    self.send("created_#{klass_string}").count #klass.where(creator:self).count
  end

  # @return [Hash]
  #
  # @user.get_class_created_updated # => { "projects" => {created: 10, first_created: datetime, updated: 10, last_updated: datetime} }
  def get_class_created_updated
    Rails.application.eager_load! if Rails.env.development?
    data = {}

    User.reflect_on_all_associations(:has_many).each do |r|
      key = nil
      puts r.name.to_s
      if r.name.to_s =~ /created_/
        # puts "after created"
        key = :created
      elsif r.name.to_s =~ /updated_/
        # puts "after updated"
        key = :updated
      end

      if key
        n     = r.klass.name.underscore.humanize.pluralize
        count = self.send(r.name).count

        if data[n]
          data[n][key] = count
        else
          data[n] = {key => count}
        end

        if count == 0
          data[n][:first_created] = 'n/a'
          data[n][:last_updated]  = 'n/a'
        else
          data[n][:first_created] = self.send(r.name).limit(1).order(created_at: :asc).first.created_at
          data[n][:last_updated]  = self.send(r.name).limit(1).order(updated_at: :desc).first.updated_at
        end
      end
    end
    data
  end

  def generate_api_access_token
    self.api_access_token = Utilities::RandomToken.generate
  end

  def require_password_presence
    @require_password_presence = true
  end

  private

  def set_remember_token
    self.remember_token = User.encrypt(User.secure_random_token)
  end

  def validate_password?
    password.present? || password_confirmation.present? || @require_password_presence
  end

  def configure_self_created
    if !self.new_record? && self.creator.nil? && self.updater.nil?
      self.update_columns(created_by_id: self.id, updated_by_id: self.id) # !?
    end
  end


end

- (String) password_digest

Returns the users password

Returns:

  • (String)

    the users password



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
# File 'app/models/user.rb', line 98

class User < ApplicationRecord
  include Housekeeping::Users
  include Housekeeping::Timestamps
  include Housekeeping::AssociationHelpers
  include Shared::DataAttributes
  include Shared::Notes
  include Shared::Tags
  include Shared::Identifiers
  include Shared::RandomTokenFields[:password_reset]
  has_secure_password

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  attr_accessor :set_new_api_access_token
  attr_accessor :self_created

  before_validation { self.email = email.to_s.downcase }

  before_save :generate_api_access_token, if: :set_new_api_access_token
  # @todo downcase does not work for non-ascii characters which means our validation for uniqueness will fail ... why?
  # @see http://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-email-address
  # @see http://unicode-utils.rubyforge.org/
  before_save { self.email = email.to_s.downcase }

  after_save :configure_self_created, if: :self_created

  before_create :set_remember_token
  before_create { self.hub_tab_order = DEFAULT_HUB_TAB_ORDER }

  validates :email, presence: true,
            format:           {with: VALID_EMAIL_REGEX},
            uniqueness:       true

  validates :password,
            length:       {minimum: 8, :if => :validate_password?},
            :confirmation => {:if => :validate_password?}

  validates :name, presence: true
  validates :name, length: {minimum: 2}, unless: -> { self.name.blank? }

  has_many :project_members, dependent: :destroy
  has_many :projects, through: :project_members
  has_many :pinboard_items, dependent: :destroy

  scope :is_administrator, -> { where(is_administrator: true) }

  def administered_projects
    projects.where(id: project_members.where(is_project_administrator: true).pluck(:project_id))
  end

  def administers_projects?
    administered_projects.any?
  end

  # @param [String, User, Integer] user
  # @return [Integer] selected user id
  def self.get_user_id(user)
    # no way to know who the current user is, so can't pre-set user_id
    case user.class.name
      when 'String'
        # search by name or email
        ut     = User.arel_table
        c1     = ut[:name].eq(user).or(ut[:email].eq(user.downcase)).to_sql
        t_user = User.where(c1).first
        if t_user.present?
          user_id = t_user.id
        else  # try to convert to a number, to see if it came directly from a web page
          t_user = user.to_i
          if t_user > 0
            t_user = User.find(t_user).try(:id)
          else
            t_user = nil
          end
          user_id = t_user
        end
      when 'User'
        user_id = user.id
      when 'Integer'
        user_id = user
    end
    user_id
  end

  # @param [String, User, Integer, Array] users
  # @return [Array of Integers] selected user ids
  def self.get_user_ids(*users)
    user_ids = []
    users.flatten.each { |user|
      case user.class.name
        when 'String'
          # search by name or email
          ut = User.arel_table
          c1 = ut[:name].eq(user)
                 .or(ut[:name].matches("%#{user}"))
                 .or(ut[:name].matches("%#{user}%"))
                 .or(ut[:email].eq(user))
                 .or(ut[:email].matches("%#{user}"))
                 .or(ut[:email].matches("%#{user}%")).to_sql
          user_ids.push(User.where(c1).pluck(:id))
        when 'User'
          user_ids.push(user.id)
        when 'Integer'
          user_ids.push(user)
      end
    }
    user_ids.flatten.uniq
  end

  def self.not_in_project(project_id)
    ids = ProjectMember.where(project_id: project_id).pluck(:user_id)
    return where(false) if ids.empty?

    User.where(User.arel_table[:id].not_eq_all(ids))
  end

  # @param [Integer] project_id
  # @return [Scope] of ids for users in the project
  def self.in_project(project_id = $project_id)
    ProjectMember.where(project_id: project_id).distinct.pluck(:user_id)
  end

  def User.secure_random_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  # @return [true, false]
  # true if user is_administrator or is_project_administrator
  def is_superuser?(project = nil)
    is_administrator || is_project_administrator?(project)
  end

  # @return [Boolean]
  # true if is_administrator = true
  def is_administrator?
    is_administrator.blank? ? false : true
  end

  # @return [true, false]
  # true if user is_project_administrator for the project passed
  # @param project [Project]
  def is_project_administrator?(project = nil)
    return false if project.nil?
    project.project_members.where(user_id: id).first.is_project_administrator
  end

  # @params [Project, Integer]
  # @return [Boolean]
  def member_of?(project)
    ProjectMember.where(project_id: project, user_id: self.id).any?
  end

  def hub_favorites
    read_attribute(:hub_favorites) || {}
  end

  def add_page_to_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    n       = options[:name]
    p       = options[:project_id].to_s
    k       = options[:kind]
    u       = hub_favorites.clone

    u[p]    = {'data' => [], 'tasks' => []} if !u[p]
    u[p][k] = u[p][k].push(n).uniq[0..19].sort

    update_column(:hub_favorites, u)
    true
  end

  def remove_page_from_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    new_routes = hub_favorites.clone
    new_routes[options['project_id'].to_s][options['kind']].delete(options['name'])
    update_column(:hub_favorites, new_routes)
  end

  def validate_favorite_options(options)
    return false if !options.select { |k, v| k.nil? || v.nil? }.empty?
    return false if !member_of?(options['project_id'])
    true
  end

  def update_last_seen_at

    a = 0

    if !last_seen_at.nil?
      t = Time.now - last_seen_at
      a = t < 301 ? time_active + t : time_active
    end

    update_columns(last_seen_at: Time.now, time_active: a)

  end

  def add_recently_visited_to_footprint(recent_route, recent_object = nil)
    case recent_route
      when /\A\/\Z/ # the root path '/'
      when /\A\/hub/ # any path which starts with '/hub'
      when /\/autocomplete\?/ # any path used for AJAX autocomplete
      else

        fp                     = footprints.dup
        fp['recently_visited'] ||= []

        attrs = {recent_route => {}}
        if !recent_object.nil?
          attrs[recent_route].merge!(object_type: recent_object.class.to_s, object_id: recent_object.id)
        end

        fp['recently_visited'].unshift(attrs)
        fp['recently_visited'] = fp['recently_visited'].uniq { |a| a.keys }[0..19]

        self.footprints_will_change! # if this isn't thrown weird caching happens !
        self.update_column(:footprints, fp)
    end

    true
  end

  # TODO:  This needs to show cross-project pinboard items as well
  def pinboard_hash(project_id)
    pinboard_items.where(project_id: project_id).order('pinned_object_type DESC, position').to_a.group_by { |a| a.pinned_object_type }
  end

  # @return [Integer]
  #   the total records of this klass created by this user
  def total_objects(klass) # klass_name is a string, need .constantize in next line
    klass.where(creator: self).count
  end

  def total_objects2(klass_string)
    self.send("created_#{klass_string}").count #klass.where(creator:self).count
  end

  # @return [Hash]
  #
  # @user.get_class_created_updated # => { "projects" => {created: 10, first_created: datetime, updated: 10, last_updated: datetime} }
  def get_class_created_updated
    Rails.application.eager_load! if Rails.env.development?
    data = {}

    User.reflect_on_all_associations(:has_many).each do |r|
      key = nil
      puts r.name.to_s
      if r.name.to_s =~ /created_/
        # puts "after created"
        key = :created
      elsif r.name.to_s =~ /updated_/
        # puts "after updated"
        key = :updated
      end

      if key
        n     = r.klass.name.underscore.humanize.pluralize
        count = self.send(r.name).count

        if data[n]
          data[n][key] = count
        else
          data[n] = {key => count}
        end

        if count == 0
          data[n][:first_created] = 'n/a'
          data[n][:last_updated]  = 'n/a'
        else
          data[n][:first_created] = self.send(r.name).limit(1).order(created_at: :asc).first.created_at
          data[n][:last_updated]  = self.send(r.name).limit(1).order(updated_at: :desc).first.updated_at
        end
      end
    end
    data
  end

  def generate_api_access_token
    self.api_access_token = Utilities::RandomToken.generate
  end

  def require_password_presence
    @require_password_presence = true
  end

  private

  def set_remember_token
    self.remember_token = User.encrypt(User.secure_random_token)
  end

  def validate_password?
    password.present? || password_confirmation.present? || @require_password_presence
  end

  def configure_self_created
    if !self.new_record? && self.creator.nil? && self.updater.nil?
      self.update_columns(created_by_id: self.id, updated_by_id: self.id) # !?
    end
  end


end

- (String) password_reset_token

TODO:

Returns:

  • (String)


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
# File 'app/models/user.rb', line 98

class User < ApplicationRecord
  include Housekeeping::Users
  include Housekeeping::Timestamps
  include Housekeeping::AssociationHelpers
  include Shared::DataAttributes
  include Shared::Notes
  include Shared::Tags
  include Shared::Identifiers
  include Shared::RandomTokenFields[:password_reset]
  has_secure_password

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  attr_accessor :set_new_api_access_token
  attr_accessor :self_created

  before_validation { self.email = email.to_s.downcase }

  before_save :generate_api_access_token, if: :set_new_api_access_token
  # @todo downcase does not work for non-ascii characters which means our validation for uniqueness will fail ... why?
  # @see http://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-email-address
  # @see http://unicode-utils.rubyforge.org/
  before_save { self.email = email.to_s.downcase }

  after_save :configure_self_created, if: :self_created

  before_create :set_remember_token
  before_create { self.hub_tab_order = DEFAULT_HUB_TAB_ORDER }

  validates :email, presence: true,
            format:           {with: VALID_EMAIL_REGEX},
            uniqueness:       true

  validates :password,
            length:       {minimum: 8, :if => :validate_password?},
            :confirmation => {:if => :validate_password?}

  validates :name, presence: true
  validates :name, length: {minimum: 2}, unless: -> { self.name.blank? }

  has_many :project_members, dependent: :destroy
  has_many :projects, through: :project_members
  has_many :pinboard_items, dependent: :destroy

  scope :is_administrator, -> { where(is_administrator: true) }

  def administered_projects
    projects.where(id: project_members.where(is_project_administrator: true).pluck(:project_id))
  end

  def administers_projects?
    administered_projects.any?
  end

  # @param [String, User, Integer] user
  # @return [Integer] selected user id
  def self.get_user_id(user)
    # no way to know who the current user is, so can't pre-set user_id
    case user.class.name
      when 'String'
        # search by name or email
        ut     = User.arel_table
        c1     = ut[:name].eq(user).or(ut[:email].eq(user.downcase)).to_sql
        t_user = User.where(c1).first
        if t_user.present?
          user_id = t_user.id
        else  # try to convert to a number, to see if it came directly from a web page
          t_user = user.to_i
          if t_user > 0
            t_user = User.find(t_user).try(:id)
          else
            t_user = nil
          end
          user_id = t_user
        end
      when 'User'
        user_id = user.id
      when 'Integer'
        user_id = user
    end
    user_id
  end

  # @param [String, User, Integer, Array] users
  # @return [Array of Integers] selected user ids
  def self.get_user_ids(*users)
    user_ids = []
    users.flatten.each { |user|
      case user.class.name
        when 'String'
          # search by name or email
          ut = User.arel_table
          c1 = ut[:name].eq(user)
                 .or(ut[:name].matches("%#{user}"))
                 .or(ut[:name].matches("%#{user}%"))
                 .or(ut[:email].eq(user))
                 .or(ut[:email].matches("%#{user}"))
                 .or(ut[:email].matches("%#{user}%")).to_sql
          user_ids.push(User.where(c1).pluck(:id))
        when 'User'
          user_ids.push(user.id)
        when 'Integer'
          user_ids.push(user)
      end
    }
    user_ids.flatten.uniq
  end

  def self.not_in_project(project_id)
    ids = ProjectMember.where(project_id: project_id).pluck(:user_id)
    return where(false) if ids.empty?

    User.where(User.arel_table[:id].not_eq_all(ids))
  end

  # @param [Integer] project_id
  # @return [Scope] of ids for users in the project
  def self.in_project(project_id = $project_id)
    ProjectMember.where(project_id: project_id).distinct.pluck(:user_id)
  end

  def User.secure_random_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  # @return [true, false]
  # true if user is_administrator or is_project_administrator
  def is_superuser?(project = nil)
    is_administrator || is_project_administrator?(project)
  end

  # @return [Boolean]
  # true if is_administrator = true
  def is_administrator?
    is_administrator.blank? ? false : true
  end

  # @return [true, false]
  # true if user is_project_administrator for the project passed
  # @param project [Project]
  def is_project_administrator?(project = nil)
    return false if project.nil?
    project.project_members.where(user_id: id).first.is_project_administrator
  end

  # @params [Project, Integer]
  # @return [Boolean]
  def member_of?(project)
    ProjectMember.where(project_id: project, user_id: self.id).any?
  end

  def hub_favorites
    read_attribute(:hub_favorites) || {}
  end

  def add_page_to_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    n       = options[:name]
    p       = options[:project_id].to_s
    k       = options[:kind]
    u       = hub_favorites.clone

    u[p]    = {'data' => [], 'tasks' => []} if !u[p]
    u[p][k] = u[p][k].push(n).uniq[0..19].sort

    update_column(:hub_favorites, u)
    true
  end

  def remove_page_from_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    new_routes = hub_favorites.clone
    new_routes[options['project_id'].to_s][options['kind']].delete(options['name'])
    update_column(:hub_favorites, new_routes)
  end

  def validate_favorite_options(options)
    return false if !options.select { |k, v| k.nil? || v.nil? }.empty?
    return false if !member_of?(options['project_id'])
    true
  end

  def update_last_seen_at

    a = 0

    if !last_seen_at.nil?
      t = Time.now - last_seen_at
      a = t < 301 ? time_active + t : time_active
    end

    update_columns(last_seen_at: Time.now, time_active: a)

  end

  def add_recently_visited_to_footprint(recent_route, recent_object = nil)
    case recent_route
      when /\A\/\Z/ # the root path '/'
      when /\A\/hub/ # any path which starts with '/hub'
      when /\/autocomplete\?/ # any path used for AJAX autocomplete
      else

        fp                     = footprints.dup
        fp['recently_visited'] ||= []

        attrs = {recent_route => {}}
        if !recent_object.nil?
          attrs[recent_route].merge!(object_type: recent_object.class.to_s, object_id: recent_object.id)
        end

        fp['recently_visited'].unshift(attrs)
        fp['recently_visited'] = fp['recently_visited'].uniq { |a| a.keys }[0..19]

        self.footprints_will_change! # if this isn't thrown weird caching happens !
        self.update_column(:footprints, fp)
    end

    true
  end

  # TODO:  This needs to show cross-project pinboard items as well
  def pinboard_hash(project_id)
    pinboard_items.where(project_id: project_id).order('pinned_object_type DESC, position').to_a.group_by { |a| a.pinned_object_type }
  end

  # @return [Integer]
  #   the total records of this klass created by this user
  def total_objects(klass) # klass_name is a string, need .constantize in next line
    klass.where(creator: self).count
  end

  def total_objects2(klass_string)
    self.send("created_#{klass_string}").count #klass.where(creator:self).count
  end

  # @return [Hash]
  #
  # @user.get_class_created_updated # => { "projects" => {created: 10, first_created: datetime, updated: 10, last_updated: datetime} }
  def get_class_created_updated
    Rails.application.eager_load! if Rails.env.development?
    data = {}

    User.reflect_on_all_associations(:has_many).each do |r|
      key = nil
      puts r.name.to_s
      if r.name.to_s =~ /created_/
        # puts "after created"
        key = :created
      elsif r.name.to_s =~ /updated_/
        # puts "after updated"
        key = :updated
      end

      if key
        n     = r.klass.name.underscore.humanize.pluralize
        count = self.send(r.name).count

        if data[n]
          data[n][key] = count
        else
          data[n] = {key => count}
        end

        if count == 0
          data[n][:first_created] = 'n/a'
          data[n][:last_updated]  = 'n/a'
        else
          data[n][:first_created] = self.send(r.name).limit(1).order(created_at: :asc).first.created_at
          data[n][:last_updated]  = self.send(r.name).limit(1).order(updated_at: :desc).first.updated_at
        end
      end
    end
    data
  end

  def generate_api_access_token
    self.api_access_token = Utilities::RandomToken.generate
  end

  def require_password_presence
    @require_password_presence = true
  end

  private

  def set_remember_token
    self.remember_token = User.encrypt(User.secure_random_token)
  end

  def validate_password?
    password.present? || password_confirmation.present? || @require_password_presence
  end

  def configure_self_created
    if !self.new_record? && self.creator.nil? && self.updater.nil?
      self.update_columns(created_by_id: self.id, updated_by_id: self.id) # !?
    end
  end


end

- (DateTime) password_reset_token_date

TODO:

Is return data type correct?

Returns:

  • (DateTime)


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
# File 'app/models/user.rb', line 98

class User < ApplicationRecord
  include Housekeeping::Users
  include Housekeeping::Timestamps
  include Housekeeping::AssociationHelpers
  include Shared::DataAttributes
  include Shared::Notes
  include Shared::Tags
  include Shared::Identifiers
  include Shared::RandomTokenFields[:password_reset]
  has_secure_password

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  attr_accessor :set_new_api_access_token
  attr_accessor :self_created

  before_validation { self.email = email.to_s.downcase }

  before_save :generate_api_access_token, if: :set_new_api_access_token
  # @todo downcase does not work for non-ascii characters which means our validation for uniqueness will fail ... why?
  # @see http://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-email-address
  # @see http://unicode-utils.rubyforge.org/
  before_save { self.email = email.to_s.downcase }

  after_save :configure_self_created, if: :self_created

  before_create :set_remember_token
  before_create { self.hub_tab_order = DEFAULT_HUB_TAB_ORDER }

  validates :email, presence: true,
            format:           {with: VALID_EMAIL_REGEX},
            uniqueness:       true

  validates :password,
            length:       {minimum: 8, :if => :validate_password?},
            :confirmation => {:if => :validate_password?}

  validates :name, presence: true
  validates :name, length: {minimum: 2}, unless: -> { self.name.blank? }

  has_many :project_members, dependent: :destroy
  has_many :projects, through: :project_members
  has_many :pinboard_items, dependent: :destroy

  scope :is_administrator, -> { where(is_administrator: true) }

  def administered_projects
    projects.where(id: project_members.where(is_project_administrator: true).pluck(:project_id))
  end

  def administers_projects?
    administered_projects.any?
  end

  # @param [String, User, Integer] user
  # @return [Integer] selected user id
  def self.get_user_id(user)
    # no way to know who the current user is, so can't pre-set user_id
    case user.class.name
      when 'String'
        # search by name or email
        ut     = User.arel_table
        c1     = ut[:name].eq(user).or(ut[:email].eq(user.downcase)).to_sql
        t_user = User.where(c1).first
        if t_user.present?
          user_id = t_user.id
        else  # try to convert to a number, to see if it came directly from a web page
          t_user = user.to_i
          if t_user > 0
            t_user = User.find(t_user).try(:id)
          else
            t_user = nil
          end
          user_id = t_user
        end
      when 'User'
        user_id = user.id
      when 'Integer'
        user_id = user
    end
    user_id
  end

  # @param [String, User, Integer, Array] users
  # @return [Array of Integers] selected user ids
  def self.get_user_ids(*users)
    user_ids = []
    users.flatten.each { |user|
      case user.class.name
        when 'String'
          # search by name or email
          ut = User.arel_table
          c1 = ut[:name].eq(user)
                 .or(ut[:name].matches("%#{user}"))
                 .or(ut[:name].matches("%#{user}%"))
                 .or(ut[:email].eq(user))
                 .or(ut[:email].matches("%#{user}"))
                 .or(ut[:email].matches("%#{user}%")).to_sql
          user_ids.push(User.where(c1).pluck(:id))
        when 'User'
          user_ids.push(user.id)
        when 'Integer'
          user_ids.push(user)
      end
    }
    user_ids.flatten.uniq
  end

  def self.not_in_project(project_id)
    ids = ProjectMember.where(project_id: project_id).pluck(:user_id)
    return where(false) if ids.empty?

    User.where(User.arel_table[:id].not_eq_all(ids))
  end

  # @param [Integer] project_id
  # @return [Scope] of ids for users in the project
  def self.in_project(project_id = $project_id)
    ProjectMember.where(project_id: project_id).distinct.pluck(:user_id)
  end

  def User.secure_random_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  # @return [true, false]
  # true if user is_administrator or is_project_administrator
  def is_superuser?(project = nil)
    is_administrator || is_project_administrator?(project)
  end

  # @return [Boolean]
  # true if is_administrator = true
  def is_administrator?
    is_administrator.blank? ? false : true
  end

  # @return [true, false]
  # true if user is_project_administrator for the project passed
  # @param project [Project]
  def is_project_administrator?(project = nil)
    return false if project.nil?
    project.project_members.where(user_id: id).first.is_project_administrator
  end

  # @params [Project, Integer]
  # @return [Boolean]
  def member_of?(project)
    ProjectMember.where(project_id: project, user_id: self.id).any?
  end

  def hub_favorites
    read_attribute(:hub_favorites) || {}
  end

  def add_page_to_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    n       = options[:name]
    p       = options[:project_id].to_s
    k       = options[:kind]
    u       = hub_favorites.clone

    u[p]    = {'data' => [], 'tasks' => []} if !u[p]
    u[p][k] = u[p][k].push(n).uniq[0..19].sort

    update_column(:hub_favorites, u)
    true
  end

  def remove_page_from_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    new_routes = hub_favorites.clone
    new_routes[options['project_id'].to_s][options['kind']].delete(options['name'])
    update_column(:hub_favorites, new_routes)
  end

  def validate_favorite_options(options)
    return false if !options.select { |k, v| k.nil? || v.nil? }.empty?
    return false if !member_of?(options['project_id'])
    true
  end

  def update_last_seen_at

    a = 0

    if !last_seen_at.nil?
      t = Time.now - last_seen_at
      a = t < 301 ? time_active + t : time_active
    end

    update_columns(last_seen_at: Time.now, time_active: a)

  end

  def add_recently_visited_to_footprint(recent_route, recent_object = nil)
    case recent_route
      when /\A\/\Z/ # the root path '/'
      when /\A\/hub/ # any path which starts with '/hub'
      when /\/autocomplete\?/ # any path used for AJAX autocomplete
      else

        fp                     = footprints.dup
        fp['recently_visited'] ||= []

        attrs = {recent_route => {}}
        if !recent_object.nil?
          attrs[recent_route].merge!(object_type: recent_object.class.to_s, object_id: recent_object.id)
        end

        fp['recently_visited'].unshift(attrs)
        fp['recently_visited'] = fp['recently_visited'].uniq { |a| a.keys }[0..19]

        self.footprints_will_change! # if this isn't thrown weird caching happens !
        self.update_column(:footprints, fp)
    end

    true
  end

  # TODO:  This needs to show cross-project pinboard items as well
  def pinboard_hash(project_id)
    pinboard_items.where(project_id: project_id).order('pinned_object_type DESC, position').to_a.group_by { |a| a.pinned_object_type }
  end

  # @return [Integer]
  #   the total records of this klass created by this user
  def total_objects(klass) # klass_name is a string, need .constantize in next line
    klass.where(creator: self).count
  end

  def total_objects2(klass_string)
    self.send("created_#{klass_string}").count #klass.where(creator:self).count
  end

  # @return [Hash]
  #
  # @user.get_class_created_updated # => { "projects" => {created: 10, first_created: datetime, updated: 10, last_updated: datetime} }
  def get_class_created_updated
    Rails.application.eager_load! if Rails.env.development?
    data = {}

    User.reflect_on_all_associations(:has_many).each do |r|
      key = nil
      puts r.name.to_s
      if r.name.to_s =~ /created_/
        # puts "after created"
        key = :created
      elsif r.name.to_s =~ /updated_/
        # puts "after updated"
        key = :updated
      end

      if key
        n     = r.klass.name.underscore.humanize.pluralize
        count = self.send(r.name).count

        if data[n]
          data[n][key] = count
        else
          data[n] = {key => count}
        end

        if count == 0
          data[n][:first_created] = 'n/a'
          data[n][:last_updated]  = 'n/a'
        else
          data[n][:first_created] = self.send(r.name).limit(1).order(created_at: :asc).first.created_at
          data[n][:last_updated]  = self.send(r.name).limit(1).order(updated_at: :desc).first.updated_at
        end
      end
    end
    data
  end

  def generate_api_access_token
    self.api_access_token = Utilities::RandomToken.generate
  end

  def require_password_presence
    @require_password_presence = true
  end

  private

  def set_remember_token
    self.remember_token = User.encrypt(User.secure_random_token)
  end

  def validate_password?
    password.present? || password_confirmation.present? || @require_password_presence
  end

  def configure_self_created
    if !self.new_record? && self.creator.nil? && self.updater.nil?
      self.update_columns(created_by_id: self.id, updated_by_id: self.id) # !?
    end
  end


end

- (String) remember_token

TODO:

Returns:

  • (String)


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
# File 'app/models/user.rb', line 98

class User < ApplicationRecord
  include Housekeeping::Users
  include Housekeeping::Timestamps
  include Housekeeping::AssociationHelpers
  include Shared::DataAttributes
  include Shared::Notes
  include Shared::Tags
  include Shared::Identifiers
  include Shared::RandomTokenFields[:password_reset]
  has_secure_password

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  attr_accessor :set_new_api_access_token
  attr_accessor :self_created

  before_validation { self.email = email.to_s.downcase }

  before_save :generate_api_access_token, if: :set_new_api_access_token
  # @todo downcase does not work for non-ascii characters which means our validation for uniqueness will fail ... why?
  # @see http://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-email-address
  # @see http://unicode-utils.rubyforge.org/
  before_save { self.email = email.to_s.downcase }

  after_save :configure_self_created, if: :self_created

  before_create :set_remember_token
  before_create { self.hub_tab_order = DEFAULT_HUB_TAB_ORDER }

  validates :email, presence: true,
            format:           {with: VALID_EMAIL_REGEX},
            uniqueness:       true

  validates :password,
            length:       {minimum: 8, :if => :validate_password?},
            :confirmation => {:if => :validate_password?}

  validates :name, presence: true
  validates :name, length: {minimum: 2}, unless: -> { self.name.blank? }

  has_many :project_members, dependent: :destroy
  has_many :projects, through: :project_members
  has_many :pinboard_items, dependent: :destroy

  scope :is_administrator, -> { where(is_administrator: true) }

  def administered_projects
    projects.where(id: project_members.where(is_project_administrator: true).pluck(:project_id))
  end

  def administers_projects?
    administered_projects.any?
  end

  # @param [String, User, Integer] user
  # @return [Integer] selected user id
  def self.get_user_id(user)
    # no way to know who the current user is, so can't pre-set user_id
    case user.class.name
      when 'String'
        # search by name or email
        ut     = User.arel_table
        c1     = ut[:name].eq(user).or(ut[:email].eq(user.downcase)).to_sql
        t_user = User.where(c1).first
        if t_user.present?
          user_id = t_user.id
        else  # try to convert to a number, to see if it came directly from a web page
          t_user = user.to_i
          if t_user > 0
            t_user = User.find(t_user).try(:id)
          else
            t_user = nil
          end
          user_id = t_user
        end
      when 'User'
        user_id = user.id
      when 'Integer'
        user_id = user
    end
    user_id
  end

  # @param [String, User, Integer, Array] users
  # @return [Array of Integers] selected user ids
  def self.get_user_ids(*users)
    user_ids = []
    users.flatten.each { |user|
      case user.class.name
        when 'String'
          # search by name or email
          ut = User.arel_table
          c1 = ut[:name].eq(user)
                 .or(ut[:name].matches("%#{user}"))
                 .or(ut[:name].matches("%#{user}%"))
                 .or(ut[:email].eq(user))
                 .or(ut[:email].matches("%#{user}"))
                 .or(ut[:email].matches("%#{user}%")).to_sql
          user_ids.push(User.where(c1).pluck(:id))
        when 'User'
          user_ids.push(user.id)
        when 'Integer'
          user_ids.push(user)
      end
    }
    user_ids.flatten.uniq
  end

  def self.not_in_project(project_id)
    ids = ProjectMember.where(project_id: project_id).pluck(:user_id)
    return where(false) if ids.empty?

    User.where(User.arel_table[:id].not_eq_all(ids))
  end

  # @param [Integer] project_id
  # @return [Scope] of ids for users in the project
  def self.in_project(project_id = $project_id)
    ProjectMember.where(project_id: project_id).distinct.pluck(:user_id)
  end

  def User.secure_random_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  # @return [true, false]
  # true if user is_administrator or is_project_administrator
  def is_superuser?(project = nil)
    is_administrator || is_project_administrator?(project)
  end

  # @return [Boolean]
  # true if is_administrator = true
  def is_administrator?
    is_administrator.blank? ? false : true
  end

  # @return [true, false]
  # true if user is_project_administrator for the project passed
  # @param project [Project]
  def is_project_administrator?(project = nil)
    return false if project.nil?
    project.project_members.where(user_id: id).first.is_project_administrator
  end

  # @params [Project, Integer]
  # @return [Boolean]
  def member_of?(project)
    ProjectMember.where(project_id: project, user_id: self.id).any?
  end

  def hub_favorites
    read_attribute(:hub_favorites) || {}
  end

  def add_page_to_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    n       = options[:name]
    p       = options[:project_id].to_s
    k       = options[:kind]
    u       = hub_favorites.clone

    u[p]    = {'data' => [], 'tasks' => []} if !u[p]
    u[p][k] = u[p][k].push(n).uniq[0..19].sort

    update_column(:hub_favorites, u)
    true
  end

  def remove_page_from_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    new_routes = hub_favorites.clone
    new_routes[options['project_id'].to_s][options['kind']].delete(options['name'])
    update_column(:hub_favorites, new_routes)
  end

  def validate_favorite_options(options)
    return false if !options.select { |k, v| k.nil? || v.nil? }.empty?
    return false if !member_of?(options['project_id'])
    true
  end

  def update_last_seen_at

    a = 0

    if !last_seen_at.nil?
      t = Time.now - last_seen_at
      a = t < 301 ? time_active + t : time_active
    end

    update_columns(last_seen_at: Time.now, time_active: a)

  end

  def add_recently_visited_to_footprint(recent_route, recent_object = nil)
    case recent_route
      when /\A\/\Z/ # the root path '/'
      when /\A\/hub/ # any path which starts with '/hub'
      when /\/autocomplete\?/ # any path used for AJAX autocomplete
      else

        fp                     = footprints.dup
        fp['recently_visited'] ||= []

        attrs = {recent_route => {}}
        if !recent_object.nil?
          attrs[recent_route].merge!(object_type: recent_object.class.to_s, object_id: recent_object.id)
        end

        fp['recently_visited'].unshift(attrs)
        fp['recently_visited'] = fp['recently_visited'].uniq { |a| a.keys }[0..19]

        self.footprints_will_change! # if this isn't thrown weird caching happens !
        self.update_column(:footprints, fp)
    end

    true
  end

  # TODO:  This needs to show cross-project pinboard items as well
  def pinboard_hash(project_id)
    pinboard_items.where(project_id: project_id).order('pinned_object_type DESC, position').to_a.group_by { |a| a.pinned_object_type }
  end

  # @return [Integer]
  #   the total records of this klass created by this user
  def total_objects(klass) # klass_name is a string, need .constantize in next line
    klass.where(creator: self).count
  end

  def total_objects2(klass_string)
    self.send("created_#{klass_string}").count #klass.where(creator:self).count
  end

  # @return [Hash]
  #
  # @user.get_class_created_updated # => { "projects" => {created: 10, first_created: datetime, updated: 10, last_updated: datetime} }
  def get_class_created_updated
    Rails.application.eager_load! if Rails.env.development?
    data = {}

    User.reflect_on_all_associations(:has_many).each do |r|
      key = nil
      puts r.name.to_s
      if r.name.to_s =~ /created_/
        # puts "after created"
        key = :created
      elsif r.name.to_s =~ /updated_/
        # puts "after updated"
        key = :updated
      end

      if key
        n     = r.klass.name.underscore.humanize.pluralize
        count = self.send(r.name).count

        if data[n]
          data[n][key] = count
        else
          data[n] = {key => count}
        end

        if count == 0
          data[n][:first_created] = 'n/a'
          data[n][:last_updated]  = 'n/a'
        else
          data[n][:first_created] = self.send(r.name).limit(1).order(created_at: :asc).first.created_at
          data[n][:last_updated]  = self.send(r.name).limit(1).order(updated_at: :desc).first.updated_at
        end
      end
    end
    data
  end

  def generate_api_access_token
    self.api_access_token = Utilities::RandomToken.generate
  end

  def require_password_presence
    @require_password_presence = true
  end

  private

  def set_remember_token
    self.remember_token = User.encrypt(User.secure_random_token)
  end

  def validate_password?
    password.present? || password_confirmation.present? || @require_password_presence
  end

  def configure_self_created
    if !self.new_record? && self.creator.nil? && self.updater.nil?
      self.update_columns(created_by_id: self.id, updated_by_id: self.id) # !?
    end
  end


end

- (true, false) self_created

Only used for when .new_record? is true. If true assigns creator and updater as self.

Returns:

  • (true, false)


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
# File 'app/models/user.rb', line 98

class User < ApplicationRecord
  include Housekeeping::Users
  include Housekeeping::Timestamps
  include Housekeeping::AssociationHelpers
  include Shared::DataAttributes
  include Shared::Notes
  include Shared::Tags
  include Shared::Identifiers
  include Shared::RandomTokenFields[:password_reset]
  has_secure_password

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  attr_accessor :set_new_api_access_token
  attr_accessor :self_created

  before_validation { self.email = email.to_s.downcase }

  before_save :generate_api_access_token, if: :set_new_api_access_token
  # @todo downcase does not work for non-ascii characters which means our validation for uniqueness will fail ... why?
  # @see http://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-email-address
  # @see http://unicode-utils.rubyforge.org/
  before_save { self.email = email.to_s.downcase }

  after_save :configure_self_created, if: :self_created

  before_create :set_remember_token
  before_create { self.hub_tab_order = DEFAULT_HUB_TAB_ORDER }

  validates :email, presence: true,
            format:           {with: VALID_EMAIL_REGEX},
            uniqueness:       true

  validates :password,
            length:       {minimum: 8, :if => :validate_password?},
            :confirmation => {:if => :validate_password?}

  validates :name, presence: true
  validates :name, length: {minimum: 2}, unless: -> { self.name.blank? }

  has_many :project_members, dependent: :destroy
  has_many :projects, through: :project_members
  has_many :pinboard_items, dependent: :destroy

  scope :is_administrator, -> { where(is_administrator: true) }

  def administered_projects
    projects.where(id: project_members.where(is_project_administrator: true).pluck(:project_id))
  end

  def administers_projects?
    administered_projects.any?
  end

  # @param [String, User, Integer] user
  # @return [Integer] selected user id
  def self.get_user_id(user)
    # no way to know who the current user is, so can't pre-set user_id
    case user.class.name
      when 'String'
        # search by name or email
        ut     = User.arel_table
        c1     = ut[:name].eq(user).or(ut[:email].eq(user.downcase)).to_sql
        t_user = User.where(c1).first
        if t_user.present?
          user_id = t_user.id
        else  # try to convert to a number, to see if it came directly from a web page
          t_user = user.to_i
          if t_user > 0
            t_user = User.find(t_user).try(:id)
          else
            t_user = nil
          end
          user_id = t_user
        end
      when 'User'
        user_id = user.id
      when 'Integer'
        user_id = user
    end
    user_id
  end

  # @param [String, User, Integer, Array] users
  # @return [Array of Integers] selected user ids
  def self.get_user_ids(*users)
    user_ids = []
    users.flatten.each { |user|
      case user.class.name
        when 'String'
          # search by name or email
          ut = User.arel_table
          c1 = ut[:name].eq(user)
                 .or(ut[:name].matches("%#{user}"))
                 .or(ut[:name].matches("%#{user}%"))
                 .or(ut[:email].eq(user))
                 .or(ut[:email].matches("%#{user}"))
                 .or(ut[:email].matches("%#{user}%")).to_sql
          user_ids.push(User.where(c1).pluck(:id))
        when 'User'
          user_ids.push(user.id)
        when 'Integer'
          user_ids.push(user)
      end
    }
    user_ids.flatten.uniq
  end

  def self.not_in_project(project_id)
    ids = ProjectMember.where(project_id: project_id).pluck(:user_id)
    return where(false) if ids.empty?

    User.where(User.arel_table[:id].not_eq_all(ids))
  end

  # @param [Integer] project_id
  # @return [Scope] of ids for users in the project
  def self.in_project(project_id = $project_id)
    ProjectMember.where(project_id: project_id).distinct.pluck(:user_id)
  end

  def User.secure_random_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  # @return [true, false]
  # true if user is_administrator or is_project_administrator
  def is_superuser?(project = nil)
    is_administrator || is_project_administrator?(project)
  end

  # @return [Boolean]
  # true if is_administrator = true
  def is_administrator?
    is_administrator.blank? ? false : true
  end

  # @return [true, false]
  # true if user is_project_administrator for the project passed
  # @param project [Project]
  def is_project_administrator?(project = nil)
    return false if project.nil?
    project.project_members.where(user_id: id).first.is_project_administrator
  end

  # @params [Project, Integer]
  # @return [Boolean]
  def member_of?(project)
    ProjectMember.where(project_id: project, user_id: self.id).any?
  end

  def hub_favorites
    read_attribute(:hub_favorites) || {}
  end

  def add_page_to_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    n       = options[:name]
    p       = options[:project_id].to_s
    k       = options[:kind]
    u       = hub_favorites.clone

    u[p]    = {'data' => [], 'tasks' => []} if !u[p]
    u[p][k] = u[p][k].push(n).uniq[0..19].sort

    update_column(:hub_favorites, u)
    true
  end

  def remove_page_from_favorites(options = {}) # name: nil, kind: nil, project_id: nil
    validate_favorite_options(options)
    new_routes = hub_favorites.clone
    new_routes[options['project_id'].to_s][