20140525150140_migrate_agents_to_service_authentication.rb 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. class MigrateAgentsToServiceAuthentication < ActiveRecord::Migration
  2. def twitter_consumer_key(agent)
  3. agent.options['consumer_key'].presence || agent.credential('twitter_consumer_key')
  4. end
  5. def twitter_consumer_secret(agent)
  6. agent.options['consumer_secret'].presence || agent.credential('twitter_consumer_secret')
  7. end
  8. def twitter_oauth_token(agent)
  9. agent.options['oauth_token'].presence || agent.options['access_key'].presence || agent.credential('twitter_oauth_token')
  10. end
  11. def twitter_oauth_token_secret(agent)
  12. agent.options['oauth_token_secret'].presence || agent.options['access_secret'].presence || agent.credential('twitter_oauth_token_secret')
  13. end
  14. def up
  15. agents = Agent.where(type: ['Agents::TwitterUserAgent', 'Agents::TwitterStreamAgent', 'Agents::TwitterPublishAgent']).each do |agent|
  16. service = agent.user.services.create!(
  17. provider: 'twitter',
  18. name: "Migrated '#{agent.name}'",
  19. token: twitter_oauth_token(agent),
  20. secret: twitter_oauth_token_secret(agent)
  21. )
  22. agent.service_id = service.id
  23. agent.save!(validate: false)
  24. end
  25. migrated = false
  26. if agents.length > 0
  27. puts <<-EOF.strip_heredoc
  28. Your Twitter agents were successfully migrated. You need to update your .env file and add the following two lines:
  29. TWITTER_OAUTH_KEY=#{twitter_consumer_key(agents.first)}
  30. TWITTER_OAUTH_SECRET=#{twitter_consumer_secret(agents.first)}
  31. To authenticate new accounts with your twitter OAuth application you need to log in the to twitter application management page (https://apps.twitter.com/)
  32. and set the callback URL of your application to "http#{ENV['FORCE_SSL'] == 'true' ? 's' : ''}://#{ENV['DOMAIN']}/auth/twitter/callback"
  33. EOF
  34. migrated = true
  35. end
  36. if Agent.where(type: ['Agents::BasecampAgent']).count > 0
  37. puts <<-EOF.strip_heredoc
  38. Your Basecamp agents can not be migrated automatically. You need to manually register an application with 37signals and authenticate Huginn to use it.
  39. Have a look at the wiki (https://github.com/cantino/huginn/wiki/Configuring-OAuth-applications) if you need help.
  40. EOF
  41. migrated = true
  42. end
  43. sleep 20 if migrated
  44. end
  45. def down
  46. raise ActiveRecord::IrreversibleMigration, "Cannot revert migration to OAuth services"
  47. end
  48. end