user.rb 1.73 KB
Newer Older
Eugen Rochko's avatar
Eugen Rochko committed
1 2
# frozen_string_literal: true

Eugen Rochko's avatar
Eugen Rochko committed
3 4 5
class User < ApplicationRecord
  devise :omniauthable, omniauth_providers: [:twitter, :mastodon]

Yamagishi Kazutoshi's avatar
Yamagishi Kazutoshi committed
6
  has_many :authorizations, dependent: :destroy
Eugen Rochko's avatar
Eugen Rochko committed
7

Yamagishi Kazutoshi's avatar
Yamagishi Kazutoshi committed
8 9
  has_one :twitter,  -> { where(provider: 'twitter') },  class_name: 'Authorization', inverse_of: :user
  has_one :mastodon, -> { where(provider: 'mastodon') }, class_name: 'Authorization', inverse_of: :user
10

11
  attr_accessor :relative_account_id, :following
12

13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
  def twitter_client
    return if twitter.nil?

    @twitter_client ||= Twitter::REST::Client.new do |config|
      config.consumer_key        = ENV['TWITTER_CLIENT_ID']
      config.consumer_secret     = ENV['TWITTER_CLIENT_SECRET']
      config.access_token        = twitter.token
      config.access_token_secret = twitter.secret
    end
  end

  def mastodon_client
    return if mastodon.nil?

    @mastodon_client ||= Mastodon::REST::Client.new(base_url: "https://#{mastodon.domain}", bearer_token: mastodon.token)
  end

Eugen Rochko's avatar
Eugen Rochko committed
30 31
  class << self
    def from_omniauth(auth, current_user)
Eugen Rochko's avatar
Eugen Rochko committed
32
      authorization = Authorization.where(provider: auth.provider, uid: auth.uid.to_s).first_or_initialize(provider: auth.provider, uid: auth.uid.to_s)
Eugen Rochko's avatar
Eugen Rochko committed
33
      user = current_user || authorization.user || User.new
Eugen Rochko's avatar
Eugen Rochko committed
34 35 36
      authorization.user   = user
      authorization.token  = auth.credentials.token
      authorization.secret = auth.credentials.secret
37 38 39 40 41 42 43 44 45

      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
46 47 48 49 50
      authorization.save
      authorization.user
    end
  end
end