user.rb 1.6KB

12345678910111213141516171819202122232425262728293031323334353637
  1. class User < ActiveRecord::Base
  2. # Include default devise modules. Others available are:
  3. # :token_authenticatable, :confirmable,
  4. # :lockable, :timeoutable and :omniauthable
  5. devise :database_authenticatable, :registerable,
  6. :recoverable, :rememberable, :trackable, :validatable, :lockable
  7. INVITATION_CODES = %w[try-huginn]
  8. # Virtual attribute for authenticating by either username or email
  9. # This is in addition to a real persisted field like 'username'
  10. attr_accessor :login
  11. ACCESSIBLE_ATTRIBUTES = [ :email, :username, :login, :password, :password_confirmation, :remember_me, :invitation_code ]
  12. attr_accessible *ACCESSIBLE_ATTRIBUTES
  13. attr_accessible *(ACCESSIBLE_ATTRIBUTES + [:admin]), :as => :admin
  14. validates_presence_of :username
  15. validates_uniqueness_of :username
  16. 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."
  17. validates_inclusion_of :invitation_code, :in => INVITATION_CODES, :message => "is not valid"
  18. has_many :events, :order => "events.created_at desc", :dependent => :delete_all, :inverse_of => :user
  19. has_many :agents, :order => "agents.created_at desc", :dependent => :destroy, :inverse_of => :user
  20. # Allow users to login via either email or username.
  21. def self.find_first_by_auth_conditions(warden_conditions)
  22. conditions = warden_conditions.dup
  23. if login = conditions.delete(:login)
  24. where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
  25. else
  26. where(conditions).first
  27. end
  28. end
  29. end