Module: Securial::Auth::SessionCreator

Extended by:
SessionCreator
Included in:
SessionCreator
Defined in:
lib/securial/auth/session_creator.rb

Overview

Creates and manages user authentication sessions.

This module provides methods to create new authenticated sessions for users, including proper validation of inputs, generation of refresh tokens, and setting up session metadata such as IP addresses and user agents.

Created sessions are automatically set as the current session context and include all necessary tokens and expiration information for secure authentication management.

Instance Method Summary collapse

Instance Method Details

#create_session!(user, request) ⇒ Securial::Session?

Creates a new authenticated session for the given user and request.

Validates the provided user and request objects, then creates a new session record with appropriate metadata and tokens. The newly created session is automatically set as the current session context.

Examples:

Creating a session after successful authentication

user = Securial::User.authenticate(email, password)
if user
  session = SessionCreator.create_session!(user, request)
  # User is now authenticated with active session
end

Handling validation failures

# Invalid user (not persisted)
new_user = Securial::User.new
session = SessionCreator.create_session!(new_user, request)
# => nil

Parameters:

  • user (Securial::User)

    The user object to create a session for

  • request (ActionDispatch::Request)

    The HTTP request object containing metadata

Returns:

  • (Securial::Session, nil)

    The created session object, or nil if validation fails



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/securial/auth/session_creator.rb', line 55

def create_session!(user, request)
  valid_user = user && user.is_a?(Securial::User) && user.persisted?
  valid_request = request.is_a?(ActionDispatch::Request)

  return nil unless valid_user && valid_request

  user.sessions.create!(
    user_agent: request.user_agent,
    ip_address: request.remote_ip,
    refresh_token: Securial::Auth::TokenGenerator.generate_refresh_token,
    last_refreshed_at: Time.current,
    refresh_token_expires_at: 1.week.from_now,
  ).tap do |session|
    Current.session = session
  end
end