user.rb 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. class User < ApplicationRecord
  2. validates :username, presence: :true, uniqueness: { case_sensitive: false }
  3. validates_format_of :username, with: /^[a-zA-Z0-9_\.]*$/, :multiline => true
  4. validate :validate_username
  5. # Include default devise modules. Others available are:
  6. # :timeoutable and :omniauthable
  7. devise :database_authenticatable, :registerable, :trackable,
  8. :recoverable, :rememberable, :validatable, :confirmable, :lockable
  9. def self.find_first_by_auth_conditions(warden_conditions)
  10. conditions = warden_conditions.dup
  11. if login = conditions.delete(:login)
  12. where(conditions).where(["lower(username) = :value OR lower(email) = :value", { value: login.downcase }]).first
  13. else
  14. if conditions[:username].nil?
  15. where(conditions).first
  16. else
  17. where(username: conditions[:username]).first
  18. end
  19. end
  20. end
  21. attr_writer :login
  22. def login
  23. @login || self.username || self.email
  24. end
  25. private
  26. def validate_username
  27. if User.where(email: username).exists?
  28. errors.add(:username, :invalid)
  29. end
  30. end
  31. end