user.rb 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # frozen_string_literal: true
  2. class User < ApplicationRecord
  3. devise :omniauthable, omniauth_providers: [:twitter, :mastodon]
  4. has_many :authorizations
  5. has_one :twitter, -> { where(provider: 'twitter') }, class_name: 'Authorization'
  6. has_one :mastodon, -> { where(provider: 'mastodon') }, class_name: 'Authorization'
  7. attr_accessor :relative_account_id, :following
  8. def twitter_client
  9. return if twitter.nil?
  10. @twitter_client ||= Twitter::REST::Client.new do |config|
  11. config.consumer_key = ENV['TWITTER_CLIENT_ID']
  12. config.consumer_secret = ENV['TWITTER_CLIENT_SECRET']
  13. config.access_token = twitter.token
  14. config.access_token_secret = twitter.secret
  15. end
  16. end
  17. def mastodon_client
  18. return if mastodon.nil?
  19. @mastodon_client ||= Mastodon::REST::Client.new(base_url: "https://#{mastodon.domain}", bearer_token: mastodon.token)
  20. end
  21. class << self
  22. def from_omniauth(auth, current_user)
  23. authorization = Authorization.where(provider: auth.provider, uid: auth.uid.to_s).first_or_initialize(provider: auth.provider, uid: auth.uid.to_s)
  24. user = current_user || authorization.user || User.new
  25. authorization.user = user
  26. authorization.token = auth.credentials.token
  27. authorization.secret = auth.credentials.secret
  28. if auth.provider == 'twitter'
  29. authorization.profile_url = auth.info.urls['Twitter']
  30. authorization.display_name = auth.info.nickname
  31. elsif auth.provider == 'mastodon'
  32. authorization.profile_url = auth.info.urls['Profile']
  33. authorization.display_name = auth.info.nickname
  34. end
  35. authorization.save
  36. authorization.user
  37. end
  38. end
  39. end