user.rb 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. # frozen_string_literal: true
  2. class User < ApplicationRecord
  3. devise :database_authenticatable, :lockable, :recoverable, :rememberable,
  4. :trackable, :validatable, :confirmable, :registerable
  5. devise :omniauthable, omniauth_providers: %i[reddit google_oauth2 discord]
  6. attr_accessor :login
  7. # Note: devise :validatable above adds validations for :email and :password
  8. # validates :username, presence: true, length: {maximum: 128}
  9. validates :email, confirmation: true
  10. class << self
  11. # Devise method overridden to allow sign in with email or username
  12. def find_for_database_authentication(warden_conditions)
  13. conditions = warden_conditions.dup
  14. if (login = conditions.delete(:login))
  15. where(conditions).find_by(
  16. 'lower(username) = :value OR lower(email) = :value',
  17. value: login.downcase.strip,
  18. )
  19. else
  20. find_by(conditions)
  21. end
  22. end
  23. end
  24. def self.from_omniauth(auth)
  25. where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
  26. user.email = auth.info.email
  27. user.password = Devise.friendly_token[0, 20]
  28. # Reddit, Google, and Discord both have email verification already
  29. user.skip_confirmation!
  30. end
  31. end
  32. end