twitter.rb 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. class ExternalCredential::Twitter
  2. def self.app_verify(params)
  3. request_account_to_link(params)
  4. params
  5. end
  6. def self.request_account_to_link(credentials = {})
  7. external_credential = ExternalCredential.find_by(name: 'twitter')
  8. if !credentials[:consumer_key]
  9. credentials[:consumer_key] = external_credential.credentials['consumer_key']
  10. end
  11. if !credentials[:consumer_secret]
  12. credentials[:consumer_secret] = external_credential.credentials['consumer_secret']
  13. end
  14. consumer = OAuth::Consumer.new(
  15. credentials[:consumer_key],
  16. credentials[:consumer_secret], {
  17. site: 'https://api.twitter.com'
  18. }
  19. )
  20. request_token = consumer.get_request_token(oauth_callback: ExternalCredential.callback_url('twitter'))
  21. {
  22. request_token: request_token,
  23. authorize_url: request_token.authorize_url,
  24. }
  25. end
  26. def self.link_account(request_token, params)
  27. raise if request_token.params[:oauth_token] != params[:oauth_token]
  28. external_credential = ExternalCredential.find_by(name: 'twitter')
  29. access_token = request_token.get_access_token(oauth_verifier: params[:oauth_verifier])
  30. client = Twitter::REST::Client.new(
  31. consumer_key: external_credential.credentials[:consumer_key],
  32. consumer_secret: external_credential.credentials[:consumer_secret],
  33. access_token: access_token.token,
  34. access_token_secret: access_token.secret,
  35. )
  36. user = client.user
  37. # check if account already exists
  38. Channel.where(area: 'Twitter::Account').each do |channel|
  39. next if !channel.options
  40. next if !channel.options['user']
  41. next if !channel.options['user']['id']
  42. next if channel.options['user']['id'] != user['id']
  43. # update access_token
  44. channel.options['auth']['external_credential_id'] = external_credential.id
  45. channel.options['auth']['oauth_token'] = access_token.token
  46. channel.options['auth']['oauth_token_secret'] = access_token.secret
  47. channel.save
  48. return channel
  49. end
  50. # create channel
  51. Channel.create(
  52. area: 'Twitter::Account',
  53. options: {
  54. adapter: 'twitter',
  55. user: {
  56. id: user.id,
  57. screen_name: user.screen_name,
  58. name: user.name,
  59. },
  60. auth: {
  61. external_credential_id: external_credential.id,
  62. oauth_token: access_token.token,
  63. oauth_token_secret: access_token.secret,
  64. },
  65. sync: {
  66. limit: 20,
  67. search: [],
  68. mentions: {},
  69. direct_messages: {},
  70. track_retweets: false
  71. }
  72. },
  73. active: true,
  74. created_by_id: 1,
  75. updated_by_id: 1,
  76. )
  77. end
  78. end