Sha256: 717af43b53fbd82dd1546d59f0539bd27229e90df0ae255b995f51d1c0b68407

Contents?: true

Size: 1023 Bytes

Versions: 2

Compression:

Stored size: 1023 Bytes

Contents

# frozen_string_literal: true

module AppleAuth
  class UserIdentity
    APPLE_KEY_URL = 'https://appleid.apple.com/auth/keys'

    attr_reader :user_identity, :jwt

    def initialize(user_identity, jwt)
      @user_identity = user_identity
      @jwt = jwt
    end

    def validate!
      token_data = decoded_jwt

      JWTConditions.new(user_identity, token_data).validate!

      token_data.symbolize_keys
    end

    private

    def decoded_jwt
      key_hash = apple_key_hash
      apple_jwk = JWT::JWK.import(key_hash)
      JWT.decode(jwt, apple_jwk.public_key, true, algorithm: key_hash['alg']).first
    end

    def apple_key_hash
      response = Net::HTTP.get(URI.parse(APPLE_KEY_URL))
      certificate = JSON.parse(response)
      matching_key = certificate['keys'].select { |key| key['kid'] == jwt_kid }
      ActiveSupport::HashWithIndifferentAccess.new(matching_key.first)
    end

    def jwt_kid
      header = JSON.parse(Base64.decode64(jwt.split('.').first))
      header['kid']
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
apple_auth-1.0.0 lib/apple_auth/user_identity.rb
apple_auth-0.1.0 lib/apple_auth/user_identity.rb