Class: User

Inherits:
Ekylibre::Record::Base show all
Includes:
Rightable
Defined in:
app/models/user.rb

Overview

Informations

License

Ekylibre - Simple agricultural ERP Copyright (C) 2008-2009 Brice Texier, Thibaud Merigon Copyright (C) 2010-2012 Brice Texier Copyright (C) 2012-2016 Brice Texier, David Joulin

This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License along with this program. If not, see www.gnu.org/licenses.

Table: users

administrator                          :boolean          default(FALSE), not null
authentication_token                   :string
commercial                             :boolean          default(FALSE), not null
confirmation_sent_at                   :datetime
confirmation_token                     :string
confirmed_at                           :datetime
created_at                             :datetime         not null
creator_id                             :integer
current_sign_in_at                     :datetime
current_sign_in_ip                     :string
description                            :text
email                                  :string           not null
employed                               :boolean          default(FALSE), not null
employment                             :string
encrypted_password                     :string           default(""), not null
failed_attempts                        :integer          default(0)
first_name                             :string           not null
id                                     :integer          not null, primary key
invitation_accepted_at                 :datetime
invitation_created_at                  :datetime
invitation_limit                       :integer
invitation_sent_at                     :datetime
invitation_token                       :string
invitations_count                      :integer          default(0)
invited_by_id                          :integer
language                               :string           not null
last_name                              :string           not null
last_sign_in_at                        :datetime
last_sign_in_ip                        :string
lock_version                           :integer          default(0), not null
locked                                 :boolean          default(FALSE), not null
locked_at                              :datetime
maximal_grantable_reduction_percentage :decimal(19, 4)   default(5.0), not null
person_id                              :integer
remember_created_at                    :datetime
reset_password_sent_at                 :datetime
reset_password_token                   :string
rights                                 :text
role_id                                :integer
sign_in_count                          :integer          default(0)
signup_at                              :datetime
team_id                                :integer
unconfirmed_email                      :string
unlock_token                           :string
updated_at                             :datetime         not null
updater_id                             :integer

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Rightable

#each_right, #resource_actions, #right_exist?, #rights_array

Methods inherited from Ekylibre::Record::Base

#already_updated?, attr_readonly_with_conditions, #check_if_destroyable?, #check_if_updateable?, columns_definition, complex_scopes, customizable?, #customizable?, #customized?, #destroyable?, #editable?, has_picture, #human_attribute_name, human_attribute_name_with_id, nomenclature_reflections, #old_record, #others, refers_to, scope_with_registration, simple_scopes, #updateable?

Class Method Details

.generate_authentication_tokenObject



317
318
319
320
321
322
# File 'app/models/user.rb', line 317

def self.generate_authentication_token
  loop do
    token = Devise.friendly_token
    break token unless exists?(authentication_token: token)
  end
end

.give_password(length = 8, mode = :complex) ⇒ Object

Used for generic password creation



325
326
327
# File 'app/models/user.rb', line 325

def self.give_password(length = 8, mode = :complex)
  generate_password(length, mode)
end

.notify_administrators(*args) ⇒ Object

Notify all administrators



210
211
212
213
214
# File 'app/models/user.rb', line 210

def self.notify_administrators(*args)
  User.administrators.each do |user|
    user.notify(*args)
  end
end

Instance Method Details

#active_for_authentication?Boolean



224
225
226
# File 'app/models/user.rb', line 224

def active_for_authentication?
  super && approved?
end

#approved?Boolean



220
221
222
# File 'app/models/user.rb', line 220

def approved?
  !pending_approval?
end

#authorization(controller_name, action_name, rights_list = nil) ⇒ Object



236
237
238
239
240
241
242
243
244
245
246
247
# File 'app/models/user.rb', line 236

def authorization(controller_name, action_name, rights_list = nil)
  rights_list = rights_array if rights_list.blank?
  message = nil
  if self.class.rights[controller_name.to_sym].nil?
    message = :no_right_defined_for_this_part_of_the_application.tl(controller: controller_name, action: action_name)
  elsif (rights = self.class.rights[controller_name.to_sym][action_name.to_sym]).nil?
    message = :no_right_defined_for_this_part_of_the_application.tl(controller: controller_name, action: action_name)
  elsif (rights & [:__minimum__, :__public__]).empty? && (rights_list & rights).empty? && !administrator?
    message = :no_right_defined_for_this_part_of_the_application_and_this_user.tl
  end
  message
end

#avatar_url(options = {}) ⇒ Object

Returns the URL of the avatar of the user



181
182
183
184
185
# File 'app/models/user.rb', line 181

def avatar_url(options = {})
  size = options[:size] || 200
  hash = Digest::MD5.hexdigest(email)
  "https://secure.gravatar.com/avatar/#{hash}?size=#{size}"
end

#can?(action, resource) ⇒ Boolean



249
250
251
# File 'app/models/user.rb', line 249

def can?(action, resource)
  administrator? || right_exist?(action, resource)
end

#can_access?(url) ⇒ Boolean



253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'app/models/user.rb', line 253

def can_access?(url)
  return true if administrator?
  if url.is_a?(Hash)
    unless url[:controller] && url[:action]
      raise "Invalid URL for accessibility test: #{url.inspect}"
    end
    key = "#{url[:controller].to_s.gsub(/^\//, '')}##{url[:action]}"
  else
    key = url.to_s
  end
  list = Ekylibre::Access.rights_of(key)
  if list.empty?
    logger.debug "Unable to check access for action: #{key}. #{url.inspect}".yellow
    return true
  end
  list &= resource_actions
  list.any?
end

#cardObject



313
314
315
# File 'app/models/user.rb', line 313

def card
  nil
end

#current_campaignObject



299
300
301
302
303
304
305
306
307
# File 'app/models/user.rb', line 299

def current_campaign
  return nil unless default_campaign = Campaign.order(harvest_year: :desc).first
  preference = self.preference('current_campaign.id', default_campaign.id, :integer)
  unless campaign = Campaign.find_by(id: preference.value)
    campaign = default
    prefer!('current_campaign.id', campaign.id)
  end
  campaign
end

#current_campaign=(campaign) ⇒ Object



309
310
311
# File 'app/models/user.rb', line 309

def current_campaign=(campaign)
  prefer!('current_campaign.id', campaign.id, :integer)
end

#full_nameObject



150
151
152
# File 'app/models/user.rb', line 150

def full_name
  name
end

#inactive_messageObject



228
229
230
231
232
233
234
# File 'app/models/user.rb', line 228

def inactive_message
  if !approved?
    :not_approved
  else
    super
  end
end

#interventions_paths(options = {}) ⇒ Object

Returns all crumbs, grouped by interventions paths, for the current user. The result is an array of interventions paths. An intervention path is an array of crumbs, for a user, ordered by read_at, between a start crumb and a stop crumb.



291
292
293
294
295
296
297
# File 'app/models/user.rb', line 291

def interventions_paths(options = {})
  crumbs = reload.crumbs.unconverted.where(nature: :start)
  if options[:on]
    crumbs = crumbs.where(read_at: options[:on].beginning_of_day..options[:on].end_of_day)
  end
  crumbs.order(read_at: :asc).map(&:intervention_path)
end

#invitation_statusObject



154
155
156
157
158
159
160
161
162
163
164
# File 'app/models/user.rb', line 154

def invitation_status
  if created_by_invite?
    if invitation_accepted?
      tc('invitation.accepted')
    else
      tc('invitation.pending')
    end
  else
    tc('invitation.not_invited')
  end
end

#labelObject



176
177
178
# File 'app/models/user.rb', line 176

def label
  name
end

#lockObject

Lock the user



273
274
275
# File 'app/models/user.rb', line 273

def lock
  update_column(:locked, true)
end

#nameObject



171
172
173
174
# File 'app/models/user.rb', line 171

def name
  # TODO: I18nize the method User#name !
  "#{first_name} #{last_name}"
end

#notify(message, interpolations = {}, options = {}) ⇒ Object

Create a notification with message for given user



204
205
206
207
# File 'app/models/user.rb', line 204

def notify(message, interpolations = {}, options = {})
  attributes = options.slice(:target, :target_url, :level)
  notifications.create!(attributes.merge(message: message, interpolations: interpolations))
end

#pending_approval?Boolean



216
217
218
# File 'app/models/user.rb', line 216

def pending_approval?
  .present?
end

#prefer!(name, value, nature = nil) ⇒ Object



195
196
197
198
199
200
201
# File 'app/models/user.rb', line 195

def prefer!(name, value, nature = nil)
  p = preferences.find_or_initialize_by(name: name)
  p.nature ||= nature if nature
  p.value = value
  p.save!
  p
end

#preference(name, default_value = nil, nature = nil) ⇒ Object Also known as: pref

Find or create preference for given name



188
189
190
191
192
# File 'app/models/user.rb', line 188

def preference(name, default_value = nil, nature = nil)
  p = preferences.find_by(name: name)
  p ||= prefer!(name, default_value, nature)
  p
end

#statusObject



166
167
168
169
# File 'app/models/user.rb', line 166

def status
  return tc('status.invitation.pending') if created_by_invite? && !invitation_accepted?
  return tc('status.registration.pending') if pending_approval?
end

#unconverted_crumb_daysObject

Returns the days where the user has crumbs present



283
284
285
# File 'app/models/user.rb', line 283

def unconverted_crumb_days
  crumbs.unconverted.pluck(:read_at).map(&:to_date).uniq.sort
end

#unlockObject

Unlock the user



278
279
280
# File 'app/models/user.rb', line 278

def unlock
  update_column(:locked, false)
end