Class: Devise::Oauth2Authenticatable::Strategies::Oauth2Authenticatable

Inherits:
Strategies::Base
  • Object
show all
Defined in:
lib/devise_oauth2_authenticatable/strategy.rb

Overview

Default strategy for signing in a user using Facebook Connect (a Facebook account). Redirects to sign_in page if it’s not authenticated

Instance Method Summary collapse

Instance Method Details

#authenticate!Object

Authenticate user with OAuth2



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/devise_oauth2_authenticatable/strategy.rb', line 20

def authenticate!
  klass = mapping.to
  begin

    # Verify User Auth code and get access token from auth server: will error on failue
    access_token = Devise::oauth2_client.web_server.get_access_token(
      params[:code], :redirect_uri => Devise::(request,mapping)
    )

    # retrieve user attributes

    # Get user details from OAuth2 Service
    oauth2_user_attributes = JSON.parse(access_token.get(OAUTH2_CONFIG['user_attributes_path']))

    # find uid from user attributes
    oauth2_uid_field = OAUTH2_CONFIG['user_attribute_uid_key'] || 'id'
    oauth2_uid = oauth2_uid_field.split('/').inject(oauth2_user_attributes) do |attributes, key|
      attributes[key] rescue {}
    end || raise("can not find #{oauth2_uid_field.inspect} in #{oauth2_user_attributes.inspect}")

    user = klass.authenticate_with_oauth2(oauth2_uid, access_token.token)

    if user.present?
      user.on_after_oauth2_connect(oauth2_user_attributes)
      success!(user)
    elsif klass.oauth2_auto_create_account?
      user = klass.new.tap do |u|
        u.store_oauth2_credentials!(:token => access_token.token, :uid => oauth2_uid)
        u.on_before_oauth2_auto_create(oauth2_user_attributes)
      end

      begin
        user.save(true)
        user.on_after_oauth2_connect(oauth2_user_attributes)
        success!(user)
      rescue
        fail!(:oauth2_invalid)
      end
    else
      fail!(:oauth2_invalid)
    end

  rescue => e
    fail!(e.message)
  end
end

#valid?Boolean

Without a oauth session authentication cannot proceed.

Returns:

  • (Boolean)


14
15
16
# File 'lib/devise_oauth2_authenticatable/strategy.rb', line 14

def valid?
 valid_controller? && valid_params? && mapping.to.respond_to?('authenticate_with_oauth2')
end