Sha256: 924083b0624ef68f86eae75006f445003822e665b693aea2f9694ad0dce32be1

Contents?: true

Size: 1.77 KB

Versions: 2

Compression:

Stored size: 1.77 KB

Contents

# frozen_string_literal: true

require "auth0_rs256_jwt_verifier"

module NulogySSO
  class Authenticator
    ACCESS_TOKEN_VERIFIER = Auth0RS256JWTVerifier.new(
      issuer: "#{NulogySSO.sso_config.base_uri}/", # Auth0 requires a backslash on the Issuer
      audience: NulogySSO.sso_config.audience,
      jwks_url: "#{NulogySSO.sso_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

    # Validated the provided JWT, ensuring that an authenticated Auth0 user can be associated to the token and matches an existing app user
    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

2 entries across 2 versions & 1 rubygems

Version Path
nulogy_sso-1.0.0 app/services/nulogy_sso/authenticator.rb
nulogy_sso-0.5.0 app/services/nulogy_sso/authenticator.rb