Class: CommandTower::Jwt::AuthenticateUser

Inherits:
Object
  • Object
show all
Defined in:
app/services/command_tower/jwt/authenticate_user.rb

Constant Summary collapse

INVALID_TOKEN_MSG =
"Unauthorized Access. Invalid Authorization token"
STALE_TOKEN_MSG =
"Unauthorized Access. Token is no longer valid"
EMAIL_VERIFICATION_MSG =
"Email must be verified to continue"
EMAIL_VERIFICATION_STATUS =
412

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(token:, bypass_email_validation: false, with_reset: false) ⇒ AuthenticateUser

Returns a new instance of AuthenticateUser.



14
15
16
17
18
# File 'app/services/command_tower/jwt/authenticate_user.rb', line 14

def initialize(token:, bypass_email_validation: false, with_reset: false)
  @token = token
  @bypass_email_validation = !!bypass_email_validation
  @with_reset = !!with_reset
end

Class Method Details

.call(token:, bypass_email_validation: false, with_reset: false) ⇒ Object



10
11
12
# File 'app/services/command_tower/jwt/authenticate_user.rb', line 10

def self.call(token:, bypass_email_validation: false, with_reset: false)
  new(token:, bypass_email_validation:, with_reset:).call
end

Instance Method Details

#callObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'app/services/command_tower/jwt/authenticate_user.rb', line 20

def call
  decoded = Decode.(token:)
  return invalid_token if decoded.failure?

  payload = decoded.payload

  expires_at = expires_at_for(generated_at: payload[:generated_at])
  return invalid_token if expires_at.nil?

  user = User.find_by(id: payload[:user_id])
  if user.nil? || user.deleted?
    log_warn("user_id [#{payload[:user_id]}] was not found. Cannot Continue")
    return invalid_token
  end

  unless user.verifier_token == payload[:verifier_token]
    return AuthenticationOutcome.failure(msg: STALE_TOKEN_MSG)
  end

  if email_validation_required?(user:)
    return AuthenticationOutcome.failure(
      msg: EMAIL_VERIFICATION_MSG,
      status: EMAIL_VERIFICATION_STATUS,
      user:
    )
  end

  generated_token = nil
  impersonation_session_id = payload[:impersonation_session_id].presence
  if with_reset
    generated_token = LoginCreate.(user:, impersonation_session_id:).token
    expires_at = CommandTower.config.jwt.ttl.from_now.to_time
  end

  AuthenticationOutcome.success(
    user:,
    expires_at: expires_at.to_s,
    generated_token:,
    impersonation_session_id:
  )
end