From c222f37187702eca868eec297747d17ecebab2d2 Mon Sep 17 00:00:00 2001 From: Bogdanov Anton Date: Sun, 15 Dec 2024 19:47:33 +0300 Subject: [PATCH] add method #pkce_valid? for validating pkce --- .DS_Store | Bin 0 -> 6148 bytes README.md | 5 +++++ lib/pkce_challenge.rb | 19 +++++++++++++++++++ lib/pkce_challenge/challenge.rb | 8 ++++++-- spec/pkce_challenge_spec.rb | 12 ++++++++++++ 5 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5008ddfcf53c02e82d7eee2e57c38e5672ef89f6 GIT binary patch literal 6148 zcmeH~Jr2S!425mzP>H1@V-^m;4Wg<&0T*E43hX&L&p$$qDprKhvt+--jT7}7np#A3 zem<@ulZcFPQ@L2!n>{z**++&mCkOWA81W14cNZlEfg7;MkzE(HCqgga^y>{tEnwC%0;vJ&^%eQ zLs35+`xjp>T0> PkceChallenge.pkce_valid?(code_verifier: '', code_challenge: '') + # => true + # + # == Parameters: + # code_verifier:: + # A String containing code_verifier + # code_challenge:: + # A String containing code_challenge + # + # == Returns: + # An instance of Bool + # + def self.pkce_valid?(code_verifier:, code_challenge:) + PkceChallenge::Challenge.new.pkce_valid?(code_verifier: code_verifier, code_challenge: code_challenge) + end end diff --git a/lib/pkce_challenge/challenge.rb b/lib/pkce_challenge/challenge.rb index 6f07c33..a68bfe4 100644 --- a/lib/pkce_challenge/challenge.rb +++ b/lib/pkce_challenge/challenge.rb @@ -19,6 +19,10 @@ def code_challenge @code_challenge ||= generate_pkce_challenge end + def pkce_valid?(code_verifier:, code_challenge:) + code_challenge == generate_pkce_challenge(code_verifier) + end + # constants definition CHAR_LENGTH = { @@ -39,8 +43,8 @@ def generate_code_verifier urlsafe_base64(SecureRandom.base64((length * 3) / 4)) end - def generate_pkce_challenge - urlsafe_base64(Digest::SHA256.base64digest(code_verifier)) + def generate_pkce_challenge(verifier=nil) + urlsafe_base64(Digest::SHA256.base64digest(verifier || code_verifier)) end def urlsafe_base64(base64_str) diff --git a/spec/pkce_challenge_spec.rb b/spec/pkce_challenge_spec.rb index 0d589dd..df2c963 100644 --- a/spec/pkce_challenge_spec.rb +++ b/spec/pkce_challenge_spec.rb @@ -28,4 +28,16 @@ expect { invalid.code_verifier }.to raise_error(PkceChallenge::LengthOutOfRangeError) end end + + describe "#pkce_valid?" do + let(:challenge) { PkceChallenge.challenge } + + it "should returns true/false based on provided data" do + code_challenge = challenge.code_challenge + code_verifier = challenge.verifier + + expect(PkceChallenge.pkce_valid?(code_verifier: code_verifier, code_challenge: code_challenge)).to be_truthy + expect(PkceChallenge.pkce_valid?(code_verifier: code_verifier, code_challenge: 'random')).to be_falsy + end + end end