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 included from ApplicationHelper

#authorized?, #get_user

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.

A Repia::Errors::Unauthorized is thrown if user is not verified.



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

def create
  @user = User.find_by_username(session_params[:username])
  if (@user && @user.authenticate(session_params[:password])) || get_user()
    raise Repia::Errors::Unauthorized 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.



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

def destroy
  if @session.destroy
    render body: "", status: 204
  else 
    # :nocov:
    render_error 400, @session.errors.full_messages
    # :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.



63
64
65
# File 'app/controllers/rails_identity/sessions_controller.rb', line 63

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