Sha256: 590b08f158a3597fedf25ab6db53b2f1f574d94788ae4165efaa8ec355cb8dd4

Contents?: true

Size: 1.85 KB

Versions: 1

Compression:

Stored size: 1.85 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,
        validate_user: NulogySSO.validate_user
    )
      @verifier = verifier
      @find_user_by_email = find_user_by_email
      @validate_user = validate_user
    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? || !validate_user.call(user)

      on_success.call(access_token)
    end

    # Returns the authenticated user that matches the provided JWT, or nil if the user cannot be authenticated
    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, :validate_user

    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

1 entries across 1 versions & 1 rubygems

Version Path
nulogy_sso-0.2.0 app/services/nulogy_sso/authenticator.rb