facebook.rb 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. class ExternalCredential::Facebook
  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: 'facebook')
  8. if !credentials[:application_id]
  9. credentials[:application_id] = external_credential.credentials['application_id']
  10. end
  11. if !credentials[:application_secret]
  12. credentials[:application_secret] = external_credential.credentials['application_secret']
  13. end
  14. oauth = Koala::Facebook::OAuth.new(
  15. credentials[:application_id],
  16. credentials[:application_secret],
  17. ExternalCredential.callback_url('facebook'),
  18. )
  19. oauth.get_app_access_token.inspect
  20. state = rand(999_999_999_999).to_s
  21. {
  22. request_token: state,
  23. #authorize_url: oauth.url_for_oauth_code(permissions: 'publish_pages, manage_pages, user_posts', state: state),
  24. authorize_url: oauth.url_for_oauth_code(permissions: 'publish_pages, manage_pages', state: state),
  25. }
  26. end
  27. def self.link_account(_request_token, params)
  28. # fail if request_token.params[:oauth_token] != params[:state]
  29. external_credential = ExternalCredential.find_by(name: 'facebook')
  30. raise 'No such account' if !external_credential
  31. oauth = Koala::Facebook::OAuth.new(
  32. external_credential.credentials['application_id'],
  33. external_credential.credentials['application_secret'],
  34. ExternalCredential.callback_url('facebook'),
  35. )
  36. access_token = oauth.get_access_token(params[:code])
  37. client = Koala::Facebook::API.new(access_token)
  38. user = client.get_object('me')
  39. #p client.get_connections('me', 'accounts').inspect
  40. pages = []
  41. client.get_connections('me', 'accounts').each { |page|
  42. pages.push(
  43. id: page['id'],
  44. name: page['name'],
  45. access_token: page['access_token'],
  46. perms: page['perms'],
  47. )
  48. }
  49. # check if account already exists
  50. Channel.where(area: 'Facebook::Account').each { |channel|
  51. next if !channel.options
  52. next if !channel.options['user']
  53. next if !channel.options['user']['id']
  54. next if channel.options['user']['id'] != user['id']
  55. channel.options['auth']['access_token'] = access_token
  56. channel.options['pages'] = pages
  57. channel.save
  58. return channel
  59. }
  60. # create channel
  61. Channel.create(
  62. area: 'Facebook::Account',
  63. options: {
  64. adapter: 'facebook',
  65. auth: {
  66. access_token: access_token
  67. },
  68. user: user,
  69. pages: pages,
  70. sync: {
  71. wall: {},
  72. pages: [],
  73. }
  74. },
  75. active: true,
  76. created_by_id: 1,
  77. updated_by_id: 1,
  78. )
  79. end
  80. end