Class: Authenticate::Session

Inherits:
Object
  • Object
show all
Includes:
Debug
Defined in:
lib/authenticate/session.rb

Overview

Represents an Authenticate session.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Debug

#debug

Constructor Details

#initialize(request, cookies) ⇒ Session

Returns a new instance of Session.


11
12
13
14
15
16
# File 'lib/authenticate/session.rb', line 11

def initialize(request, cookies)
  @request = request # trackable module accesses request
  @cookies = cookies
  @session_token = @cookies[cookie_name]
  debug 'SESSION initialize: @session_token: ' + @session_token.inspect
end

Instance Attribute Details

#requestObject

Returns the value of attribute request


9
10
11
# File 'lib/authenticate/session.rb', line 9

def request
  @request
end

Instance Method Details

#authenticated?Boolean

Has this session successfully authenticated?

Returns:

  • (Boolean)

56
57
58
59
# File 'lib/authenticate/session.rb', line 56

def authenticated?
  debug 'session.authenticated?'
  current_user.present?
end

#current_userUser

Get the user represented by this session.

Returns:


47
48
49
50
51
# File 'lib/authenticate/session.rb', line 47

def current_user
  debug 'session.current_user'
  @current_user ||= load_user_from_session_token if @session_token.present?
  @current_user
end

#deauthenticatevoid

This method returns an undefined value.

Invalidate the session token, unset the current user and remove the cookie.


64
65
66
67
68
69
70
71
72
73
# File 'lib/authenticate/session.rb', line 64

def deauthenticate
  # nuke session_token in db
  current_user.reset_session_token! if current_user.present?

  # nuke notion of current_user
  @current_user = nil

  # # nuke cookie
  @cookies.delete cookie_name
end

#login(user) {|status| ... } ⇒ User

Finish user login process, after the user has been authenticated. Called when user creates an account or signs back into the app. Runs all callbacks checking for any login failure. If a login failure occurs, user is NOT logged in.

Yields:

  • (status)

Returns:


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/authenticate/session.rb', line 24

def (user)
  @current_user = user
  @current_user.generate_session_token if user.present?

  message = catch(:failure) do
    Authenticate.lifecycle.run_callbacks(:after_set_user, @current_user, self, event: :authentication)
    Authenticate.lifecycle.run_callbacks(:after_authentication, @current_user, self, event: :authentication)
  end

  status = message.present? ? Failure.new(message) : Success.new
  if status.success?
    @current_user.save
    write_cookie if @current_user.session_token
  else
    @current_user = nil
  end

  yield(status) if block_given?
end