Class: Ninsho::Authentication

Inherits:
Object
  • Object
show all
Defined in:
lib/ninsho/authentication.rb

Overview

Responsible for manage the authentication process with the omniauth hash

Instance Method Summary collapse

Constructor Details

#initialize(omniauth = nil) ⇒ Authentication

Returns a new instance of Authentication.



7
8
9
10
11
12
13
# File 'lib/ninsho/authentication.rb', line 7

def initialize(omniauth = nil)
 @omniauth = omniauth
 @provider = omniauth['provider'] 
 @uid = omniauth['uid']
 @oauth_token = @omniauth.credentials.token
 @email = omniauth['info']['email']
end

Instance Method Details

#authenticated?Boolean

Returns:

  • (Boolean)


15
16
17
# File 'lib/ninsho/authentication.rb', line 15

def authenticated?
  user.present?
end

#from_oauthObject

Little method to check if the record is find by the provider and uid



20
21
22
23
24
25
26
27
28
# File 'lib/ninsho/authentication.rb', line 20

def from_oauth
  resource_class = Ninsho.resource_class.where(@omniauth.slice(:provider, :uid)).first_or_initialize
  resource_class.tap do |resource|
    resource.provider = @provider
    resource.uid = @uid
    resource.oauth_token = @oauth_token
    resource.save if resource.respond_to?(Ninsho.parent_resource_name.to_s.downcase.to_sym) && !resource.new_record?
  end
end

#from_userObject

Method to create an authentication record when user is find, otherwise creates a user with the authentication



32
33
34
35
36
37
38
39
40
# File 'lib/ninsho/authentication.rb', line 32

def from_user
  attrs = { email: @email }
  user = Ninsho.parent_resource_name.where(attrs).first_or_initialize
  user = Ninsho.parent_resource_name.new if @provider == "twitter"
  user.attributes = holding_attributes(attrs) if user.new_record?
  user.send("#{Ninsho.resource_name.pluralize}").build(provider: @provider, uid: @uid, oauth_token: @oauth_token)
  user.save
  user
end

#holding_attributes(attrs = {}) ⇒ Object

Holding user attributes



48
49
50
51
52
53
# File 'lib/ninsho/authentication.rb', line 48

def holding_attributes(attrs = {})
  Ninsho.parent_resource_holding_attributes.each do |attr|
    attrs[attr] = nested_hash_value(@omniauth, attr)
  end
  attrs
end

#userObject

Check if a parent record is returned, commonly the User model



43
44
45
# File 'lib/ninsho/authentication.rb', line 43

def user
   from_oauth.try(Ninsho.parent_resource_name.to_s.downcase.to_sym) || from_user
end