Commit 37bfba1

mo <mo.khan@gmail.com>
2018-09-18 21:50:54
do not allow refresh, revoked or expired tokens to authenticate.
1 parent c8e8e0e
Changed files (2)
app
models
spec
app/models/user.rb
@@ -45,10 +45,14 @@ class User < ApplicationRecord
       nil
     end
 
-    def authenticate_token(token)
-      token = BearerToken.new.decode(token)
-      return if token.empty?
-      User.find_by(uuid: token[:sub])
+    def authenticate_token(jwt)
+      claims = BearerToken.new.decode(jwt)
+      return if claims.empty?
+
+      token = Token.find_by!(uuid: claims[:jti])
+      return if token.refresh? || token.revoked?
+
+      token.subject
     end
   end
 
spec/models/user_spec.rb
@@ -0,0 +1,31 @@
+require 'rails_helper'
+
+RSpec.describe User do
+  describe ".authenticate_token" do
+    subject { described_class }
+
+    context "when the access_token is active" do
+      let(:token) { create(:access_token) }
+
+      specify { expect(subject.authenticate_token(token.to_jwt)).to eql(token.subject) }
+    end
+
+    context "when the token is a refresh token" do
+      let(:token) { create(:refresh_token) }
+
+      specify { expect(subject.authenticate_token(token.to_jwt)).to be_nil }
+    end
+
+    context "when the access token has been revoked" do
+      let(:token) { create(:access_token, :revoked) }
+
+      specify { expect(subject.authenticate_token(token.to_jwt)).to be_nil }
+    end
+
+    context "when the access token is expired" do
+      let(:token) { create(:access_token, :expired) }
+
+      specify { expect(subject.authenticate_token(token.to_jwt)).to be_nil }
+    end
+  end
+end