diff --git a/app/models/dsi_user.rb b/app/models/dsi_user.rb index 15a08cf7..38f801e5 100644 --- a/app/models/dsi_user.rb +++ b/app/models/dsi_user.rb @@ -3,8 +3,9 @@ class DsiUser < ApplicationRecord encrypts :first_name, :last_name has_many :search_logs + has_many :dsi_user_sessions, dependent: :destroy - def self.create_or_update_from_dsi(dsi_payload) + def self.create_or_update_from_dsi(dsi_payload, role = nil) dsi_user = find_or_initialize_by(email: dsi_payload.info.fetch(:email)) dsi_user.update!( @@ -13,6 +14,15 @@ def self.create_or_update_from_dsi(dsi_payload) uid: dsi_payload.uid ) + if role.present? + dsi_user.dsi_user_sessions.create!( + role_id: role["id"], + role_code: role["code"], + organisation_id: dsi_payload.extra.raw_info.organisation.id, + organisation_name: dsi_payload.extra.raw_info.organisation.name, + ) + end + dsi_user end end diff --git a/app/models/dsi_user_session.rb b/app/models/dsi_user_session.rb new file mode 100644 index 00000000..e72d6423 --- /dev/null +++ b/app/models/dsi_user_session.rb @@ -0,0 +1,3 @@ +class DsiUserSession < ApplicationRecord + belongs_to :dsi_user +end diff --git a/spec/models/dsi_user_spec.rb b/spec/models/dsi_user_spec.rb index 3ce82659..873f878c 100644 --- a/spec/models/dsi_user_spec.rb +++ b/spec/models/dsi_user_spec.rb @@ -3,7 +3,18 @@ RSpec.describe DsiUser, type: :model do describe ".create_or_update_from_dsi" do let(:dsi_payload) do - OmniAuth::AuthHash.new(uid: "123456", info: { email:, first_name: "John", last_name: "Doe" }) + OmniAuth::AuthHash.new( + uid: "123456", + info: { email:, first_name: "John", last_name: "Doe" }, + extra: { + raw_info: { + organisation: { + id: "09876", + name: "Test Org", + } + } + } + ) end let(:email) { "test@example.com" } @@ -32,5 +43,19 @@ expect(dsi_user.last_name).to eq dsi_payload.info.last_name end end + + context "when the user has a role" do + it "creates a session record" do + role = { "id" => "123", "code" => "TestRole_code" } + described_class.create_or_update_from_dsi(dsi_payload, role) + + dsi_user_session = DsiUser.first.dsi_user_sessions.first + expect(dsi_user_session).to be_present + expect(dsi_user_session.role_id).to eq "123" + expect(dsi_user_session.role_code).to eq "TestRole_code" + expect(dsi_user_session.organisation_id).to eq "09876" + expect(dsi_user_session.organisation_name).to eq "Test Org" + end + end end end