Module: AtomicTenant::JwtToken

Included in:
CurrentApplicationInstanceMiddleware
Defined in:
lib/atomic_tenant/jwt_token.rb

Defined Under Namespace

Classes: InvalidTokenError

Constant Summary collapse

ALGORITHM =
"HS512".freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.decode(token, algorithm = ALGORITHM) ⇒ Object

Raises:



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/atomic_tenant/jwt_token.rb', line 7

def self.decode(token,  algorithm = ALGORITHM)
  decoded_token = JWT.decode(
    token,
    AtomicTenant.jwt_secret,
    true,
    { algorithm: algorithm },
  )
  raise InvalidTokenError if AtomicTenant.jwt_aud != decoded_token[0]["aud"]

  decoded_token
end

.valid?(token, algorithm = ALGORITHM) ⇒ Boolean

Returns:

  • (Boolean)


19
20
21
# File 'lib/atomic_tenant/jwt_token.rb', line 19

def self.valid?(token, algorithm = ALGORITHM)
  decode(token, algorithm)
end

Instance Method Details

#decoded_jwt_token(req) ⇒ Object

Raises:



23
24
25
26
27
28
29
# File 'lib/atomic_tenant/jwt_token.rb', line 23

def decoded_jwt_token(req)
  token = valid?(encoded_token(req))
  raise InvalidTokenError, 'Unable to decode jwt token' if token.blank?
  raise InvalidTokenError, 'Invalid token payload' if token.empty?

  token[0]
end

#encoded_token(req) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/atomic_tenant/jwt_token.rb', line 51

def encoded_token(req)
  return req.params[:jwt] if req.params[:jwt]

  if header = req.headers['Authorization'] || req.headers[:authorization]
    header.split(' ').last
  end
end

#encoded_token!(req) ⇒ Object

Raises:



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/atomic_tenant/jwt_token.rb', line 39

def encoded_token!(req)
  return req.params[:jwt] if req.params[:jwt]

  header = req.headers['Authorization'] || req.headers[:authorization]
  raise InvalidTokenError, 'No authorization header found' if header.nil?

  token = header.split(' ').last
  raise InvalidTokenError, 'Invalid authorization header string' if token.nil?

  token
end

#validate_token_with_secret(aud, secret, req = request) ⇒ Object



31
32
33
34
35
36
37
# File 'lib/atomic_tenant/jwt_token.rb', line 31

def validate_token_with_secret(aud, secret, req = request)
  token = decoded_jwt_token(req, secret)
  raise InvalidTokenError if aud != token['aud']
rescue JWT::DecodeError, InvalidTokenError => e
  Rails.logger.error "JWT Error occured: #{e.inspect}"
  render json: { error: 'Unauthorized: Invalid token.' }, status: :unauthorized
end