Sha256: 6ec55ceb1baeb4ed4891d6b51aec109b7ba39ae5b6be7e6d8f2dd48039c3577c

Contents?: true

Size: 1.73 KB

Versions: 4

Compression:

Stored size: 1.73 KB

Contents

# frozen_string_literal: true

require "auth0_rs256_jwt_verifier"

module NulogySSO
  class Authenticator
    ACCESS_TOKEN_VERIFIER = Auth0RS256JWTVerifier.new(
      issuer: "#{NulogySSO.auth_config.base_uri}/", # Auth0 requires a backslash on the Issuer
      audience: NulogySSO.auth_config.audience,
      jwks_url: "#{NulogySSO.auth_config.base_uri}/.well-known/jwks.json"
    )

    def initialize(verifier: ACCESS_TOKEN_VERIFIER, find_user_by_email: NulogySSO.find_user_by_email)
      @verifier = verifier
      @find_user_by_email = find_user_by_email
    end

    # Authorizes the provided JWT, ensuring that a valid user can be associated to the token
    def validate_token(raw_access_token, on_success:, on_invalid_token:)
      access_token = decoded_validated_access_token(raw_access_token)

      return on_invalid_token.call if access_token.nil?

      user = fetch_user(access_token)
      return on_invalid_token.call if user.blank?

      on_success.call(access_token)
    end

    # Returns the authenticated user that matches the provided JWT, or nil if the token is invalid
    # or no such user can be found.
    def authenticated_user(raw_access_token)
      access_token = decoded_validated_access_token(raw_access_token)

      return nil if access_token.nil?

      fetch_user(access_token)
    end

    private

    attr_reader :verifier, :find_user_by_email

    def decoded_validated_access_token(raw_access_token)
      if raw_access_token.present? && verifier.verify(raw_access_token).valid?
        return JSON::JWT.decode(raw_access_token, :skip_verification)
      end

      nil
    end

    def fetch_user(access_token)
      email = access_token.fetch(NulogySSO::JWT_EMAIL_KEY)
      find_user_by_email.call(email)
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
nulogy_sso-0.4.0 app/services/nulogy_sso/authenticator.rb
nulogy_sso-0.3.3 app/services/nulogy_sso/authenticator.rb
nulogy_sso-0.3.1 app/services/nulogy_sso/authenticator.rb
nulogy_sso-0.3.0 app/services/nulogy_sso/authenticator.rb