user.rb 1.02 KB
Newer Older
Eugen Rochko's avatar
Eugen Rochko committed
1 2 3 4 5
class User < ApplicationRecord
  devise :omniauthable, omniauth_providers: [:twitter, :mastodon]

  has_many :authorizations

6 7 8 9 10 11 12 13
  def twitter
    @twitter ||= authorizations.find_by(provider: :twitter)
  end

  def mastodon
    @mastodon ||= authorizations.find_by(provider: :mastodon)
  end

Eugen Rochko's avatar
Eugen Rochko committed
14 15 16
  class << self
    def from_omniauth(auth, current_user)
      authorization = Authorization.where(provider: auth.provider, uid: auth.uid.to_s).first_or_initialize
Eugen Rochko's avatar
Eugen Rochko committed
17
      user = current_user || authorization.user || User.new
Eugen Rochko's avatar
Eugen Rochko committed
18 19 20
      authorization.user   = user
      authorization.token  = auth.credentials.token
      authorization.secret = auth.credentials.secret
21 22 23 24 25 26 27 28 29

      if auth.provider == 'twitter'
        authorization.profile_url  = auth.info.urls['Twitter']
        authorization.display_name = auth.info.nickname
      elsif auth.provider == 'mastodon'
        authorization.profile_url  = auth.info.urls['Profile']
        authorization.display_name = auth.info.nickname
      end

Eugen Rochko's avatar
Eugen Rochko committed
30 31 32 33 34
      authorization.save
      authorization.user
    end
  end
end