Class: RailsIdentity::SessionsController

Inherits:
ApplicationController show all
Defined in:
app/controllers/rails_identity/sessions_controller.rb

Overview

This class is sessions controller that performs CRD on session objects. Note that a token includes its session ID. Use “current” to look up a session in the current context.

Instance Method Summary collapse

Methods inherited from ApplicationController

#options

Methods included from ApplicationHelper

#accept_token, #authorized?, #find_object, #get_user, #render_error, #render_errors, #require_admin_token, #require_token

Instance Method Details

#createObject

This action is essentially the login action. Note that get_user is not triggered for this action because we will look at username first. That would be the “normal” way to login. The alternative would be with the token based authentication. If the latter doesn’t make sense, just use the username and password approach.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'app/controllers/rails_identity/sessions_controller.rb', line 41

def create
  @user = User.find_by_username(session_params[:username])
  if (@user && @user.authenticate(session_params[:password])) || get_user()
    raise Errors::UnauthorizedError unless @user.verified
    @session = Session.new(user: @user)
    if @session.save
      render json: @session, except: [:secret], status: 201
    else
      # :nocov:
      render_errors 400, @session.full_error_messages
      # :nocov:
    end
  else
    render_error 401, "Invalid username or password"
  end
end

#destroyObject

Deletes a session.



68
69
70
71
72
73
74
75
76
# File 'app/controllers/rails_identity/sessions_controller.rb', line 68

def destroy
  if @session.destroy
    render body: "", status: 204
  else 
    # :nocov:
    render_error 500, "Something went wrong. Oops!"
    # :nocov:
  end
end

#indexObject

Lists all sessions that belong to the specified or authenticated user.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'app/controllers/rails_identity/sessions_controller.rb', line 19

def index
  @sessions = Session.where(user: @user)
  expired = []
  active = []
  @sessions.each do |session|
    if session.expired?
      expired << session.uuid
    else
      active << session
    end
  end
  SessionsCleanupJob.perform_later(*expired)
  render json: active, except: [:secret]
end

#showObject

Shows a session information.



61
62
63
# File 'app/controllers/rails_identity/sessions_controller.rb', line 61

def show
  render json: @session, except: [:secret]
end