require 'rails_helper'
require 'webmock/rspec'

RSpec.describe "Discourse SSO", type: :request do

  describe "GET /discourse/connect" do
    let(:user) { create :user, cn: 'jimmy', ou: 'kosmos.org' }

    before do
      Warden.test_mode!
      login_as user, scope: :user
      allow(user).to receive(:display_name).and_return('Jimbo')
      allow(user).to receive(:is_admin?).and_return(false)
    end

    after do
      Warden.test_reset!
    end

    context "with invalid SSO credentials" do
      it "results in a failed signature check" do
        expect {
          get discourse_connect_path(
            sso: "bm9uY2U9ODk2N2NiMmFlZTdlMjdjNzZiZTNkZWQ5ODIwYzMzN2QmcmV0dXJuX3Nzb191cmw9aHR0cCUzQSUyRiUyRmxvY2FsaG9zdCUzQTMwMDAlMkZzZXNzaW9uJTJGc3NvX2xvZ2lu",
            sig: "01fc008ff7b51855217e879b6f14aaddefbbd4df2d128951f7bb70cfde834c2a"
          )
        }.to raise_error(DiscourseApi::SingleSignOn::ParseError)
      end
    end

    context "valid SSO credentials" do
      it "redirects to the Discourse SSO endpoint" do
        get discourse_connect_path(
          sso: "bm9uY2U9YjQwYWZmYzg0YWQ2NWE1ZTk5MjdlZWU1NWEzMjdhMTQmcmV0dXJuX3Nzb191cmw9aHR0cCUzQSUyRiUyRmxvY2FsaG9zdCUzQTMwMDAlMkZzZXNzaW9uJTJGc3NvX2xvZ2lu",
          sig: "b7905c5db612391293249ad5272dac493681efcd255133f6c2aff91ba654a319"
        )
        expect(response).to redirect_to('http://discourse.example.com/session/sso_login?sso=YWRtaW49ZmFsc2UmZW1haWw9amltbXklNDBleGFtcGxlLmNvbSZleHRlcm5hbF9pZD0xJm5hbWU9SmltYm8mbm9uY2U9YjQwYWZmYzg0YWQ2NWE1ZTk5MjdlZWU1NWEzMjdhMTQmcmV0dXJuX3Nzb191cmw9aHR0cCUzQSUyRiUyRmxvY2FsaG9zdCUzQTMwMDAlMkZzZXNzaW9uJTJGc3NvX2xvZ2luJnVzZXJuYW1lPWppbW15&sig=d5f8b1d6db66569bef789fda4a3216119c2d42b84725d043c9a57dde1e528842')
      end
    end
  end
end
