Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement LDAP check integration #94

Merged
merged 24 commits into from
Feb 17, 2025
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ spec/examples.txt

# Ignore other files
/.idea
/spec/fixtures/files/*
/data/*
/app/parsing_files/*
/app/post_prints/*
Expand All @@ -43,3 +42,4 @@ spec/examples.txt
.cache
.bash_history
.envrc
.irb_history
1 change: 1 addition & 0 deletions .rubocop_todo.yml
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ RSpec/AnyInstance:
- 'spec/integration/ai_integration/ldap_integration_spec.rb'
- 'spec/jobs/application_job_spec.rb'
- 'spec/models/post_print_analyzer_spec.rb'
- 'spec/controllers/ldap_check_controller_spec.rb'

# Offense count: 49
# This cop supports unsafe autocorrection (--autocorrect-all).
Expand Down
27 changes: 27 additions & 0 deletions app/controllers/ldap_check_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class LdapCheckController < ApplicationController
def index; end

def create
should_disable = params[:ldap_should_disable] == '1'
data = params[:ldap_check_file]
result = LdapCheck.new(data, should_disable).perform

if result[:error]
flash_error(result[:error])
else
send_data(
result[:output],
filename: 'ldap_check_results.csv',
type: 'text/csv',
disposition: 'attachment'
)
end
end

private

def flash_error(msg)
flash[:error] = msg
# redirect_to ldap_check_path
end
end
35 changes: 35 additions & 0 deletions app/services/ai_disable_client.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# frozen_string_literal: true

require 'httparty'

class AiDisableClient
class ClientError < StandardError; end

include HTTParty
base_uri ENV.fetch('FAMS_WEBSERVICES_BASE_URI', 'https://betawebservices.digitalmeasures.com/login/service/v4')

def initialize(
username = ENV.fetch('FAMS_WEBSERVICES_USERNAME', nil),
password = ENV.fetch('FAMS_WEBSERVICES_PASSWORD', nil)
)
@options = {
basic_auth: {
username:,
password:
},
headers: {
'Accept' => 'text/xml',
'Content-Type' => 'text/xml'
},
timeout: 180
}
end

def user(uid)
self.class.get("/User/USERNAME:#{uid}", @options)
end

def enable_user(uid, value)
self.class.put("/User/USERNAME:#{uid}", @options.merge({ body: "<User enabled=\"#{value}\"/>" }))
end
end
84 changes: 84 additions & 0 deletions app/services/ldap_check.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# frozen_string_literal: true

class LdapCheck
def initialize(csv_data, should_disable)
@csv_data = csv_data
@should_disable = should_disable
end

def perform
uids = extract_usernames

return { error: 'No usernames were found in uploaded CSV. Make sure there is a "Usernames" column.' } if uids.empty?

entries = pull_ldap_data(uids)

if @should_disable
uids_to_disable = entries
.filter { |entry| entry['eduPersonPrimaryAffiliation'].first == 'MEMBER' }
.map { |entry| entry['uid'].first }

disabled_uids = disable_ai_users(uids_to_disable)
output = generate_output(entries, disabled_uids)
else
output = generate_output(entries)
end

{ output: output }
end

private

def extract_usernames()
CSV.parse(@csv_data.read, headers: true)
.filter_map { |row| row['Username'] }
end

def disable_ai_users(uids)
client = AiDisableClient.new

uids.each do |uid|
client.enable_user(uid, false)
end

uids
end

def pull_ldap_data(uids)
conn = Net::LDAP.new(
host: ENV.fetch('CENTRAL_LDAP_HOST', 'test-dirapps.aset.psu.edu'),
port: ENV.fetch('CENTRAL_LDAP_PORT', '389')
)

joined_filter = uids.map { |uid| Net::LDAP::Filter.eq('uid', uid) }.reduce(:|)

conn.search(
base: 'dc=psu,dc=edu',
filter: joined_filter
)
end

def generate_output(entries, disabled_uids = nil)
headers = ['Username', 'Name', 'Primary Affiliation', 'Title', 'Department', 'Campus']
headers.append('Disabled?') if disabled_uids.present?

CSV.generate do |csv|
csv << headers

entries.each do |entry|
uid = entry['uid'].first
row = [
uid,
entry['displayName'].first,
entry['eduPersonPrimaryAffiliation'].first,
entry['title'].first,
entry['psBusinessArea'].first,
entry['psCampus'].first
]
row.append(disabled_uids.include?(uid) ? 'yes' : 'no') if disabled_uids.present?

csv << row
end
end
end
end
3 changes: 3 additions & 0 deletions app/views/layouts/application.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@
<li class="nav-item">
<a class="nav-link" href=<%=post_prints_path%>>Post Prints Analyzer</a>
</li>
<li class="nav-item">
<a class="nav-link" href=<%=ldap_check_path%>>LDAP Check</a>
</li>
</ul>
</div>
</div>
Expand Down
37 changes: 37 additions & 0 deletions app/views/ldap_check/index.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<div class="toolbar">
<div class="container">
<div class="row">
<div class="col">
<h1>LDAP Check</h1>
</div>
</div>
</div>
</div>

<div class="container main-content">
<%= form_with url: ldap_check_path, multipart: true, id: 'ldap-check-form' do |form| %>
<p>
<%= label(:ldap_check_file, text = "Usernames to check") %>
<%= form.file_field :ldap_check_file, required: true %>
</p>

<p>
<%= label(:ldap_should_disable, text = "Disable found users?") %>
<%= form.check_box :ldap_should_disable,
data: { confirm: 'Are you sure you want to do this?' } %>
</p>

<div class="row">
<%= form.submit 'Check LDAP Data', class: 'btn btn-primary mt-3',
data: { disable_with: false } %>
</div>
<% end %>
</div>

<script>
document.getElementById('ldap-check-form').addEventListener('submit', function() {
setTimeout(function() {
window.location.reload();
}, 100);
});
</script>
2 changes: 2 additions & 0 deletions config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,6 @@
get '/destroy', to: 'publication_listings#destroy'
post '/update', to: 'publication_listings#update'
end
get 'ldap_check', to: 'ldap_check#index'
post 'ldap_check', to: 'ldap_check#create'
end
3 changes: 3 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ services:
FAMS_S3_BUCKET_API_KEY: ${FAMS_S3_BUCKET_API_KEY}
FAMS_LP_SFTP_USERNAME: ${FAMS_LP_SFTP_USERNAME}
FAMS_LP_SFTP_HOST: ${FAMS_LP_SFTP_HOST}
FAMS_WEBSERVICES_BASE_URI: ${FAMS_WEBSERVICES_BASE_URI}
CENTRAL_LDAP_HOST: ${CENTRAL_LDAP_HOST}
CENTRAL_LDAP_PORT: ${CENTRAL_LDAP_PORT}
build:
args:
UID: "${UID:-1001}"
Expand Down
3 changes: 3 additions & 0 deletions spec/fixtures/files/bad_userames.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Bad
foo
bar
1 change: 1 addition & 0 deletions spec/fixtures/files/empty_usernames.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Username
2 changes: 2 additions & 0 deletions spec/fixtures/files/usernames.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Username
test123
28 changes: 28 additions & 0 deletions spec/services/ai_disable_client_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
require 'rails_helper'

RSpec.describe AiDisableClient, type: :service do
let(:client) { AiDisableClient.new }
let(:uid) { 'user1' }

before do
stub_request(:get, /betawebservices.digitalmeasures.com/)
Fixed Show fixed Hide fixed
.to_return(status: 200, body: "<User><Username>#{uid}</Username></User>", headers: { 'Content-Type' => 'text/xml' })

stub_request(:put, /betawebservices.digitalmeasures.com/)
Fixed Show fixed Hide fixed
.to_return(status: 200, body: "", headers: { 'Content-Type' => 'text/xml' })
end

describe '#user' do
it 'fetches user data' do
response = client.user(uid)
expect(response.body).to include("<Username>#{uid}</Username>")
end
end

describe '#enable_user' do
it 'sends a request to enable or disable a user' do
response = client.enable_user(uid, false)
expect(response.code).to eq(200)
end
end
end
48 changes: 48 additions & 0 deletions spec/services/ldap_check_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
require 'rails_helper'

RSpec.describe LdapCheck, type: :service do
fixtures :username, :bad_userames, :empty_usernames

let(:should_disable) { true }
let(:ldap_check) { LdapCheck.new(csv_data, should_disable) }
let(:mock_ldap_entries) do
[
{ 'uid' => ['test123'], 'eduPersonPrimaryAffiliation' => ['MEMBER'], 'displayName' => ['Test User'], 'title' => ['Test Title'], 'psBusinessArea' => ['Test Dept'], 'psCampus' => ['Test Campus'] }
]
end

before do
allow(ldap_check).to receive(:pull_ldap_data).and_return(mock_ldap_entries)
allow_any_instance_of(AiDisableClient).to receive(:enable_user)
end

describe '#perform' do
context 'when CSV has valid usernames' do
let(:csv_data) { file_fixture('usernames.csv').open }

it 'returns output with disabled users' do
result = ldap_check.perform
expect(result[:output]).to include('Username,Name,Primary Affiliation,Title,Department,Campus,Disabled?')
expect(result[:output]).to include('test123,Test User,MEMBER,Test Title,Test Dept,Test Campus,yes')
end
end

context 'when CSV has no usernames' do
let(:csv_data) { file_fixture('empty_usernames.csv').open }

it 'returns an error message' do
result = ldap_check.perform
expect(result[:error]).to eq('No usernames were found in uploaded CSV. Make sure there is a "Usernames" column.')
end
end

context 'when CSV has a bad column' do
let(:csv_data) { file_fixture('bad_userames.csv').open }

it 'returns an error message' do
result = ldap_check.perform
expect(result[:error]).to eq('No usernames were found in uploaded CSV. Make sure there is a "Usernames" column.')
end
end
end
end
Empty file removed vendor/.keep
Empty file.
Loading