Sha256: 7db171904620be532598e25faff691f13fd6cf4d9cfbeee28a3143bd706322b0

Contents?: true

Size: 1.72 KB

Versions: 17

Compression:

Stored size: 1.72 KB

Contents

module Sorcery
  module Providers
    # This class adds support for OAuth with github.com.
    #
    #   config.github.key = <key>
    #   config.github.secret = <secret>
    #   ...
    #
    class Github < Base
      include Protocols::Oauth2

      attr_accessor :auth_path, :scope, :token_url, :user_info_path

      def initialize
        super

        @scope          = nil
        @site           = 'https://github.com/'
        @user_info_path = 'https://api.github.com/user'
        @auth_path      = '/login/oauth/authorize'
        @token_url      = '/login/oauth/access_token'
      end

      def get_user_hash(access_token)
        response = access_token.get(user_info_path)

        auth_hash(access_token).tap do |h|
          h[:user_info] = JSON.parse(response.body).tap do |uih|
            uih['email'] = primary_email(access_token) if scope =~ /user/
          end
          h[:uid] = h[:user_info]['id']
        end
      end

      # calculates and returns the url to which the user should be redirected,
      # to get authenticated at the external provider's site.
      def login_url(_params, _session)
        authorize_url(authorize_url: auth_path)
      end

      # tries to login the user from access token
      def process_callback(params, _session)
        args = {}.tap do |a|
          a[:code] = params[:code] if params[:code]
        end

        get_access_token(args, token_url: token_url, token_method: :post)
      end

      def primary_email(access_token)
        response = access_token.get(user_info_path + '/emails')
        emails = JSON.parse(response.body)
        primary = emails.find { |i| i['primary'] }
        primary && primary['email'] || emails.first && emails.first['email']
      end
    end
  end
end

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
sorcery-0.17.0 lib/sorcery/providers/github.rb
sorcery-0.16.5 lib/sorcery/providers/github.rb
sorcery-0.16.4 lib/sorcery/providers/github.rb
sorcery-0.16.3 lib/sorcery/providers/github.rb
sorcery-0.16.2 lib/sorcery/providers/github.rb
sorcery-0.16.1 lib/sorcery/providers/github.rb
sorcery-0.15.1 lib/sorcery/providers/github.rb
sorcery-0.16.0 lib/sorcery/providers/github.rb
sorcery-0.15.0 lib/sorcery/providers/github.rb
sorcery-0.14.0 lib/sorcery/providers/github.rb
sorcery-0.13.0 lib/sorcery/providers/github.rb
sorcery-0.12.0 lib/sorcery/providers/github.rb
sorcery-0.11.0 lib/sorcery/providers/github.rb
sorcery-0.10.3 lib/sorcery/providers/github.rb
sorcery-0.10.2 lib/sorcery/providers/github.rb
sorcery-0.10.1 lib/sorcery/providers/github.rb
sorcery-0.10.0 lib/sorcery/providers/github.rb