reddit.rb 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # frozen_string_literal: true
  2. module OmniAuth
  3. module Strategies
  4. class Reddit < OmniAuth::Strategies::OAuth2
  5. option :name, 'reddit'
  6. option :authorize_options, %i[scope duration]
  7. option :client_options,
  8. site: 'https://oauth.reddit.com',
  9. token_url: 'https://www.reddit.com/api/v1/access_token'
  10. uid { raw_info['id'] }
  11. info do
  12. {
  13. name: raw_info['name'],
  14. }
  15. end
  16. extra do
  17. {'raw_info' => raw_info}
  18. end
  19. def raw_info
  20. @raw_info ||= access_token.get('/api/v1/me').parsed || {}
  21. end
  22. def build_access_token
  23. options.token_params[:headers] = {'Authorization' => basic_auth_header}
  24. super
  25. end
  26. def basic_auth_header
  27. 'Basic ' + Base64.strict_encode64(
  28. "#{options[:client_id]}:#{options[:client_secret]}",
  29. )
  30. end
  31. MOBILE_USER_AGENTS = 'webos|ipod|iphone|mobile'
  32. def request_phase
  33. options[:client_options].authorize_url =
  34. if mobile_request?
  35. 'https://www.reddit.com/api/v1/authorize.compact'
  36. else
  37. 'https://www.reddit.com/api/v1/authorize'
  38. end
  39. super
  40. end
  41. def mobile_request?
  42. ua = Rack::Request.new(@env).user_agent.to_s
  43. ua.downcase =~ Regexp.new(MOBILE_USER_AGENTS)
  44. end
  45. def callback_url
  46. options[:redirect_uri] || (full_host + script_name + callback_path)
  47. end
  48. end
  49. end
  50. end