user.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # Huginn is designed to be a multi-User system. Users have many Agents (and Events created by those Agents).
  2. class User < ActiveRecord::Base
  3. # Include default devise modules. Others available are:
  4. # :token_authenticatable, :confirmable,
  5. # :lockable, :timeoutable and :omniauthable
  6. devise :database_authenticatable, :registerable,
  7. :recoverable, :rememberable, :trackable, :validatable, :lockable
  8. INVITATION_CODES = [ENV['INVITATION_CODE'] || 'try-huginn']
  9. # Virtual attribute for authenticating by either username or email
  10. # This is in addition to a real persisted field like 'username'
  11. attr_accessor :login
  12. ACCESSIBLE_ATTRIBUTES = [ :email, :username, :login, :password, :password_confirmation, :remember_me, :invitation_code ]
  13. attr_accessible *ACCESSIBLE_ATTRIBUTES
  14. attr_accessible *(ACCESSIBLE_ATTRIBUTES + [:admin]), :as => :admin
  15. validates_presence_of :username
  16. validates_uniqueness_of :username
  17. validates_format_of :username, :with => /\A[a-zA-Z0-9_-]{3,15}\Z/, :message => "can only contain letters, numbers, underscores, and dashes, and must be between 3 and 15 characters in length."
  18. validates_inclusion_of :invitation_code, :on => :create, :in => INVITATION_CODES, :message => "is not valid"
  19. has_many :user_credentials, :dependent => :destroy, :inverse_of => :user
  20. has_many :events, -> { order("events.created_at desc") }, :dependent => :delete_all, :inverse_of => :user
  21. has_many :agents, -> { order("agents.created_at desc") }, :dependent => :destroy, :inverse_of => :user
  22. has_many :logs, :through => :agents, :class_name => "AgentLog"
  23. has_many :scenarios, :inverse_of => :user, :dependent => :destroy
  24. has_many :services, -> { by_name('asc') }, :dependent => :destroy
  25. def available_services
  26. Service.available_to_user(self).by_name
  27. end
  28. # Allow users to login via either email or username.
  29. def self.find_first_by_auth_conditions(warden_conditions)
  30. conditions = warden_conditions.dup
  31. if login = conditions.delete(:login)
  32. where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
  33. else
  34. where(conditions).first
  35. end
  36. end
  37. end