Class: Merb::Authentication

Inherits:
Object
  • Object
show all
Includes:
Extlib::Hook
Defined in:
lib/merb-auth-core/responses.rb,
lib/merb-auth-core/errors.rb,
lib/merb-auth-core/strategy.rb,
lib/merb-auth-core/callbacks.rb,
lib/merb-auth-core/authentication.rb,
lib/merb-auth-core/customizations.rb

Overview

These are not intended to be used directly

Defined Under Namespace

Modules: Strategies Classes: DuplicateStrategy, Errors, MissingStrategy, NotImplemented, Strategy

Constant Summary collapse

@@after_callbacks =
[]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(session) ⇒ Authentication

Returns a new instance of Authentication.



24
25
26
# File 'lib/merb-auth-core/authentication.rb', line 24

def initialize(session)
  @session = session
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



4
5
6
# File 'lib/merb-auth-core/responses.rb', line 4

def body
  @body
end

#error_messageObject

A simple error message mechanism to provide general information. For more specific information

This message is the default message passed to the Merb::Controller::Unauthenticated exception during authentication.

This is a very simple mechanism for error messages. For more detailed control see Authenticaiton#errors



126
127
128
# File 'lib/merb-auth-core/authentication.rb', line 126

def error_message
  @error_message || "Could not log in"
end

#sessionObject

Returns the value of attribute session.



5
6
7
# File 'lib/merb-auth-core/authentication.rb', line 5

def session
  @session
end

Class Method Details

.activate!(label) ⇒ Object

Activates a registered strategy by it’s label. Intended for use with plugin authors. There is little need to register your own strategies. Just declare them and they will be active.



40
41
42
43
44
# File 'lib/merb-auth-core/strategy.rb', line 40

def self.activate!(label)
  path = self.registered_strategies[label]
  raise "The #{label} Strategy is not registered" unless path
  require path
end

.after_authentication(*callbacks, &block) ⇒ Object

Use the after_authentication callbacks to setup things that should occur after the user is authenticated.

Pass in symbols, procs and or a block to the method to setup the callbacks. Callbacks are executed in the order they are added.

<*callbacks:> The callback.. Symbol == method on the user object

Proc will be passed the user, request and param objects

<&block> A block to check. The user, request and params will be passed into the block

To confirm that the user is still eligable to login, simply return the user from the method or block. To stop the user from being authenticated return false or nil

Example

Merb::Authentication.after_authentication do |user,request,params|
   user.active? ? user : nil
end


28
29
30
31
# File 'lib/merb-auth-core/callbacks.rb', line 28

def self.after_authentication(*callbacks, &block)
  self.after_callbacks = after_callbacks + callbacks.flatten unless callbacks.blank?
  after_callbacks << block if block_given?
end

.customize_default(&block) ⇒ Object

Adds any customizations just before the after_app_loads boot loader so that plugins can offer default customization. This will still allow for a user to overwrite any customizations if required in the after_app_loads block



11
12
13
14
# File 'lib/merb-auth-core/customizations.rb', line 11

def customize_default(&block)
  default_customizations << block
  default_customizations
end

.default_customizationsObject

Gets the list of declared customizations



17
18
19
# File 'lib/merb-auth-core/customizations.rb', line 17

def default_customizations
  @custom_default_blocks ||= []
end

.default_strategy_order=(*order) ⇒ Object

Use this to set the default order of strategies if you need to in your application. You don’t need to use all avaiable strategies in this array, but you may not include a strategy that has not yet been defined.

Raises:

  • (ArgumentError)


13
14
15
16
17
18
# File 'lib/merb-auth-core/strategy.rb', line 13

def self.default_strategy_order=(*order)
  order = order.flatten
  bad = order.select{|s| !s.ancestors.include?(Strategy)}
  raise ArgumentError, "#{bad.join(",")} do not inherit from Merb::Authentication::Strategy" unless bad.empty?
  @@default_strategy_order = order
end

.lookup_strategyObject

Keeps track of strategies by class or string When loading from string, strategies are loaded withing the Merb::Authentication::Strategies namespace When loaded by class, the class is stored directly



152
153
154
# File 'lib/merb-auth-core/authentication.rb', line 152

def self.lookup_strategy
  @strategy_lookup || reset_strategy_lookup!
end

.maintain_session_keysObject

Maintains a list of keys to maintain when needing to keep some state in the face of session.abandon! You need to maintain this state yourself



171
172
173
# File 'lib/merb-auth-core/authentication.rb', line 171

def self.maintain_session_keys
  @maintain_session_keys ||= [:authentication_strategies]
end

.register(label, path) ⇒ Object

Allows for the registration of strategies. Registering a strategy does not add it to the list of strategies to use it simply makes it available through the Merb::Authentication.activate method

This is for plugin writers to make a strategy availalbe but this should not stop you from declaring your own strategies



32
33
34
# File 'lib/merb-auth-core/strategy.rb', line 32

def self.register(label, path)
  self.registered_strategies[label] = path
end

.reset_strategy_lookup!Object

Restets the strategy lookup. Useful in specs



157
158
159
160
161
162
163
164
165
166
# File 'lib/merb-auth-core/authentication.rb', line 157

def self.reset_strategy_lookup!
  @strategy_lookup = Mash.new do |h,k|
    case k
    when Class
      h[k] = k
    when String, Symbol
      h[k] = Merb::Authentication::Strategies.full_const_get(k.to_s)
    end
  end
end

Instance Method Details

#abandon!Object

“Logs Out” a user from the session. Also clears out all session data



113
114
115
116
# File 'lib/merb-auth-core/authentication.rb', line 113

def abandon!
  @user = nil
  session.clear
end

#authenticate!(request, params, *rest) ⇒ Object

The workhorse of the framework. The authentiate! method is where the work is done. authenticate! will try each strategy in order either passed in, or in the default_strategy_order.

If a strategy returns some kind of user object, this will be stored in the session, otherwise a Merb::Controller::Unauthenticated exception is raised

Pass in a list of strategy objects to have this list take precedence over the normal defaults

Use an options hash to provide an error message to be passed into the exception.

Returns:

  • user object of the verified user. An exception is raised if no user is found

Raises:

  • (Merb::Controller::Unauthenticated)


69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/merb-auth-core/authentication.rb', line 69

def authenticate!(request, params, *rest)
  opts = rest.last.kind_of?(Hash) ? rest.pop : {}
  rest = rest.flatten

  strategies = if rest.empty?
    if request.session[:authentication_strategies]
      request.session[:authentication_strategies]
    else
      Merb::Authentication.default_strategy_order
    end
  else
    request.session[:authentication_strategies] ||= []
    request.session[:authentication_strategies] << rest
    request.session[:authentication_strategies].flatten!.uniq!
    request.session[:authentication_strategies]
  end

  msg = opts[:message] || error_message
  user = nil
  # This one should find the first one that matches.  It should not run antother
  strategies.detect do |s|
    s = Merb::Authentication.lookup_strategy[s] # Get the strategy from string or class
    unless s.abstract?
      strategy = s.new(request, params)
      user = strategy.run!
      if strategy.halted?
        self.headers, self.status, self.body = [strategy.headers, strategy.status, strategy.body]
        halt!
        return
      end
      user
    end
  end

  # Check after callbacks to make sure the user is still cool
  user = run_after_authentication_callbacks(user, request, params) if user

  # Finally, Raise an error if there is no user found, or set it in the session if there is.
  raise Merb::Controller::Unauthenticated, msg unless user
  session[:authentication_strategies] = nil # clear the session of Failed Strategies if login is successful
  self.user = user
end

#authenticated?TrueClass|FalseClass

Returns true if there is an authenticated user attached to this session

Returns:

  • (TrueClass|FalseClass)


32
33
34
# File 'lib/merb-auth-core/authentication.rb', line 32

def authenticated?
  !!session[:user]
end

#errorsObject



4
5
6
# File 'lib/merb-auth-core/errors.rb', line 4

def errors
  @errors ||= Errors.new
end

#fetch_user(session_contents = ) ⇒ Object

Tells the framework how to reconstitute a user from the data stored by store_user.

You must overwrite this method for user in your projects. Slices and plugins may set this.

Raises:



144
145
146
# File 'lib/merb-auth-core/authentication.rb', line 144

def fetch_user(session_contents = session[:user])
  raise NotImplemented
end

#halt!Object



31
32
33
# File 'lib/merb-auth-core/responses.rb', line 31

def halt!
  @halt = true
end

#halted?Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/merb-auth-core/responses.rb', line 22

def halted?
  !!@halt
end

#headersObject



10
11
12
# File 'lib/merb-auth-core/responses.rb', line 10

def headers
  @headers ||= {}
end

#headers=(headers) ⇒ Object

Raises:

  • (ArgumentError)


26
27
28
29
# File 'lib/merb-auth-core/responses.rb', line 26

def headers=(headers)
  raise ArgumentError, "Need to supply a hash to headers.  Got #{headers.class}" unless headers.kind_of?(Hash)
  @headers = headers
end

#redirected?Boolean

Returns:

  • (Boolean)


6
7
8
# File 'lib/merb-auth-core/responses.rb', line 6

def redirected?
  !!headers["Location"]
end

#statusObject



14
15
16
# File 'lib/merb-auth-core/responses.rb', line 14

def status
  @status ||= 200
end

#status=(sts) ⇒ Object



18
19
20
# File 'lib/merb-auth-core/responses.rb', line 18

def status=(sts)
  @status = sts
end

#store_user(user) ⇒ Object

Tells the framework how to store your user object into the session so that it can be re-created on the next login. You must overwrite this method for use in your projects. Slices and plugins may set this.

Raises:



135
136
137
# File 'lib/merb-auth-core/authentication.rb', line 135

def store_user(user)
  raise NotImplemented
end

#userUser class

This method will retrieve the user object stored in the session or nil if there is no user logged in.

Returns:

  • (User class)

    |NilClass



40
41
42
43
# File 'lib/merb-auth-core/authentication.rb', line 40

def user
  return nil if !session[:user]
  @user ||= fetch_user(session[:user])
end

#user=(user) ⇒ User Class

This method will store the user provided into the session and set the user as the currently logged in user

Returns:

  • (User Class)

    |NilClass



48
49
50
51
52
# File 'lib/merb-auth-core/authentication.rb', line 48

def user=(user)
  session[:user] = nil && return if user.nil?
  session[:user] = store_user(user)
  @user = session[:user] ? user : session[:user]
end

#user_classUser Class Object

This method returns the default user class to use throughout the merb-auth authentication framework. Merb::Authentication.user_class can be used by other plugins, and by default by strategies.

By Default it is set to User class. If you need a different class The intention is that you overwrite this method

Returns:

  • (User Class Object)


22
# File 'lib/merb-auth-core/authentication.rb', line 22

cattr_accessor :user_class