Class: SpdJwtAuthorizor::Engine

Inherits:
Object
  • Object
show all
Defined in:
lib/spd_jwt_authorizor.rb

Instance Method Summary collapse

Constructor Details

#initialize(jwt:) ⇒ Engine

Returns a new instance of Engine.



7
8
9
10
# File 'lib/spd_jwt_authorizor.rb', line 7

def initialize(jwt:)
  @jwt = jwt
  check_if_env_set!
end

Instance Method Details

#authorized?(required_permissions:, match: :all) ⇒ Boolean

Returns:

  • (Boolean)


12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/spd_jwt_authorizor.rb', line 12

def authorized?(required_permissions:, match: :all)
  return false unless ok?

  if match == :all
    # JWT should contain all mentioned permissions
    (required_permissions & payload['aud']).count ==
      required_permissions.count
  elsif match == :any
    # JWT should contain AT LEAST ONE of the mentioned permissions
    (required_permissions & payload['aud']).count.positive?
  end
end

#decodable?Boolean

Returns:

  • (Boolean)


47
48
49
50
51
52
53
# File 'lib/spd_jwt_authorizor.rb', line 47

def decodable?
  JWT.decode(@jwt, ENV['JWT_SECRET_KEY'], false)
  true
rescue JWT::DecodeError
  puts 'SapaadJwtAuthorizor: JWT is not decodable!'
  false
end

#expired?Boolean

Returns:

  • (Boolean)


29
30
31
32
33
34
35
# File 'lib/spd_jwt_authorizor.rb', line 29

def expired?
  JWT.decode(@jwt, ENV['JWT_SECRET_KEY'], true)
  false
rescue JWT::ExpiredSignature
  puts 'SapaadJwtAuthorizor: JWT is Expired!'
  true
end

#ok?Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/spd_jwt_authorizor.rb', line 25

def ok?
  decodable? && verified? && !expired?
end

#payloadObject



55
56
57
58
59
60
# File 'lib/spd_jwt_authorizor.rb', line 55

def payload
  JWT.decode(@jwt, ENV['JWT_SECRET_KEY'], false).first
rescue JWT::DecodeError
  puts 'SapaadJwtAuthorizor: JWT is not decodable!'
  nil
end

#verified?Boolean

Returns:

  • (Boolean)


37
38
39
40
41
42
43
44
45
# File 'lib/spd_jwt_authorizor.rb', line 37

def verified?
  JWT.decode(@jwt, ENV['JWT_SECRET_KEY'], true)
  true
rescue JWT::ExpiredSignature
  true
rescue JWT::VerificationError
  puts 'SapaadJwtAuthorizor: JWT is not Verified!'
  false
end