Commit 4099956

mo <mo.khan@gmail.com>
2018-09-09 16:52:04
exchange code for token.
1 parent f8fc829
Changed files (3)
app
config
spec
app/controllers/oauths_controller.rb
@@ -1,6 +1,9 @@
 # frozen_string_literal: true
 
 class OauthsController < ApplicationController
+  skip_before_action :authenticate!, only: [:token]
+  skip_before_action :authenticate_mfa!, only: [:token]
+
   def show
     return render_error(:not_found) unless params[:response_type] == 'code'
     @client = Client.find_by!(uuid: params[:client_id])
@@ -14,4 +17,15 @@ class OauthsController < ApplicationController
       state: params[:state]
     )
   end
+
+  def token
+    response.headers['Cache-Control'] = 'no-store'
+    response.headers['Pragma'] = 'no-cache'
+    render json: {
+      access_token: SecureRandom.hex(20),
+      token_type: 'access',
+      expires_in: 1.hour.to_i,
+      refresh_token: SecureRandom.hex(20)
+    }, status: :ok
+  end
 end
config/routes.rb
@@ -8,6 +8,7 @@ Rails.application.routes.draw do
   resource :session, only: [:new, :create, :destroy]
   resource :oauth, only: [:show, :create] do
     get :authorize, to: "oauths#show"
+    post :token, to: "oauths#token"
   end
 
   resources :registrations, only: [:new, :create]
spec/requests/oauth_spec.rb
@@ -51,4 +51,28 @@ RSpec.describe '/oauth' do
       end
     end
   end
+
+  describe "POST /oauth/token" do
+    context "when exchanging a code for a token" do
+      context "when the code is still valid" do
+        let(:authorization) { create(:authorization, client: client, user: user) }
+        let(:client) { create(:client) }
+        let(:user) { create(:user) }
+        let(:code) { authorization.code }
+
+        before { post '/oauth/token', params: { grant_type: 'authorization_code', code: code } }
+
+        specify { expect(response).to have_http_status(:ok) }
+        specify { expect(response.headers['Content-Type']).to include('application/json') }
+        specify { expect(response.headers['Cache-Control']).to include('no-store') }
+        specify { expect(response.headers['Pragma']).to eql('no-cache') }
+
+        let(:json) { JSON.parse(response.body, symbolize_names: true) }
+        specify { expect(json[:access_token]).to be_present }
+        specify { expect(json[:token_type]).to be_present }
+        specify { expect(json[:expires_in]).to be_present }
+        specify { expect(json[:refresh_token]).to be_present }
+      end
+    end
+  end
 end