repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
psparrow/attr-gather
|
spec/attr/gather/aggregators_spec.rb
|
# frozen_string_literal: true
module Attr
module Gather
RSpec.describe Aggregators do
describe '.default' do
it 'is the :deep_merge aggregator' do
expect(described_class.default).to be_a(Aggregators::DeepMerge)
end
end
describe '.resolve' do
it 'resolves a named aggregator' do
result = described_class.resolve(:deep_merge)
expect(result).to be_a(Aggregators::DeepMerge)
end
it 'raises a meaningful error when no aggregator is found' do
expect do
described_class.resolve(:invalid)
end.to raise_error(Registrable::NotFoundError)
end
end
end
end
end
|
psparrow/attr-gather
|
lib/attr/gather/filters/result.rb
|
# frozen_string_literal: true
module Attr
module Gather
module Filters
# Result of a filter
#
# @!attribute [r] value
# @return [Hash] the filtered hash
#
# @!attribute [r] filterings
# @return [Array<Attr::Gather::Filtering>] info about filtered items
class Result
attr_reader :value, :filterings
def initialize(value, filterings)
@value = value
@filterings = filterings
end
end
end
end
end
|
psparrow/attr-gather
|
lib/attr/gather/aggregators.rb
|
# frozen_string_literal: true
require 'attr/gather/concerns/registrable'
module Attr
module Gather
# Namespace for aggregators
module Aggregators
extend Registrable
# The default aggregator if none is specified
#
# @return [Attr::Gather::Aggregators::DeepMerge]
def self.default
@default = resolve(:deep_merge)
end
register(:deep_merge) do |*args|
require 'attr/gather/aggregators/deep_merge'
DeepMerge.new(*args)
end
register(:shallow_merge) do |*args|
require 'attr/gather/aggregators/shallow_merge'
ShallowMerge.new(*args)
end
end
end
end
|
psparrow/attr-gather
|
lib/attr-gather.rb
|
<gh_stars>10-100
# frozen_string_literal: true
require 'attr/gather'
|
psparrow/attr-gather
|
lib/attr/gather/filters/filtering.rb
|
# frozen_string_literal: true
module Attr
module Gather
module Filters
# Information about a filtered item
#
# @!attribute [r] path
# @return [Hash] path of the filtered key
#
# @!attribute [r] reason
# @return [String] why the item was filtered
#
# @!attribute [r] input
# @return [String] input value that was filtered
class Filtering
attr_reader :path, :reason, :input
def initialize(path, reason, input)
@path = path
@reason = reason
@input = input
end
end
end
end
end
|
psparrow/attr-gather
|
spec/shared/user_workflow.rb
|
<filename>spec/shared/user_workflow.rb
# frozen_string_literal: true
RSpec.shared_context 'user workflow' do
let(:user_workflow_class) do
workflow_class = Class.new do
include Attr::Gather::Workflow
task :good do |t|
t.depends_on = []
end
task :bad do |t|
t.depends_on = []
end
end
workflow_class.container(user_container)
workflow_class.filter(:contract, user_contract.new)
workflow_class
end
let(:user_contract) do
require 'dry-validation'
Class.new(Dry::Validation::Contract) do
params do
optional(:email).filled(:str?, format?: /@/)
end
end
end
end
|
psparrow/attr-gather
|
lib/attr/gather/workflow/task_executor.rb
|
<filename>lib/attr/gather/workflow/task_executor.rb
# frozen_string_literal: true
require 'concurrent'
require 'attr/gather/workflow/task_execution_result'
module Attr
module Gather
module Workflow
# @api private
class TaskExecutor
attr_reader :batch, :container, :executor
def initialize(batch, container:)
@batch = batch
@container = container
@executor = :immediate
end
def call(input)
batch.map do |task|
task_proc = container.resolve(task.name)
result = Concurrent::Promise.execute(executor: executor) do
task_proc.call(input)
end
TaskExecutionResult.new(task, result)
end
end
end
end
end
end
|
alebian/passman
|
spec/manager_spec.rb
|
<reponame>alebian/passman
require 'spec_helper'
require 'json'
describe Passman::Manager do
subject(:manager) { described_class.new(file_path) }
let(:file_path) { './spec/passman.json' }
let(:account) { 'test_account' }
let(:username) { 'test_username' }
let(:password) { '<PASSWORD>' }
let(:key) { 'test_key' }
let!(:salt) { BCrypt::Engine.generate_salt }
describe '#generate_password' do
let!(:length) { 32 }
let!(:passwords) { 10_000 }
it 'creates correct length passwords' do
expect(subject.generate_password(length).size).to eq(length)
end
it 'creates different passwords' do
passwords_hash = {}
passwords.times do
passwords_hash[subject.generate_password(length)] = ''
end
expect(passwords_hash.size).to eq passwords
end
end
describe '#add' do
it 'stores the data' do
subject.add(account, username, password, key, salt)
json = JSON.parse(File.read(file_path))
expect(json).to eq(
account => {
'username' => username,
'password' => Passman::Crypto.encrypt(password, key, salt: salt)
}
)
end
context 'when the account is empty' do
let(:account) { '' }
it 'fails' do
expect { subject.add(account, username, password, key) }.to raise_error(ArgumentError)
end
end
context 'when the account is nil' do
let(:account) { nil }
it 'fails' do
expect { subject.add(account, username, password, key) }.to raise_error(ArgumentError)
end
end
context 'when the username is empty' do
let(:username) { '' }
it 'fails' do
expect { subject.add(account, username, password, key) }.to raise_error(ArgumentError)
end
end
context 'when the username is nil' do
let(:username) { nil }
it 'fails' do
expect { subject.add(account, username, password, key) }.to raise_error(ArgumentError)
end
end
context 'when the password is empty' do
let(:password) { '' }
it 'fails' do
expect { subject.add(account, username, password, key) }.to raise_error(ArgumentError)
end
end
context 'when the password is nil' do
let(:password) { nil }
it 'fails' do
expect { subject.add(account, username, password, key) }.to raise_error(ArgumentError)
end
end
context 'when the key is empty' do
let(:key) { '' }
it 'fails' do
expect { subject.add(account, username, password, key) }.to raise_error(ArgumentError)
end
end
context 'when the key is nil' do
let(:key) { nil }
it 'fails' do
expect { subject.add(account, username, password, key) }.to raise_error(ArgumentError)
end
end
end
describe '#delete' do
it 'deletes the data' do
subject.add(account, username, password, key)
subject.delete(account)
json = JSON.parse(File.read(file_path))
expect(json).to eq({})
end
context 'when the account is empty' do
let(:account) { '' }
it 'fails' do
expect { subject.delete(account) }.to raise_error(ArgumentError)
end
end
context 'when the account is nil' do
let(:account) { nil }
it 'fails' do
expect { subject.delete(account) }.to raise_error(ArgumentError)
end
end
end
describe '#get' do
it 'retreives the data' do
subject.add(account, username, password, key)
expect(subject.get(account, key)).to eq([account.to_s, { 'username' => username,
'password' => password }])
end
context 'when the account is empty' do
let(:account) { '' }
it 'fails' do
expect { subject.get(account, key) }.to raise_error(ArgumentError)
end
end
context 'when the account is nil' do
let(:account) { nil }
it 'fails' do
expect { subject.get(account, key) }.to raise_error(ArgumentError)
end
end
context 'when the key is empty' do
let(:key) { '' }
it 'fails' do
expect { subject.get(account, key) }.to raise_error(ArgumentError)
end
end
context 'when the key is nil' do
let(:key) { nil }
it 'fails' do
expect { subject.get(account, key) }.to raise_error(ArgumentError)
end
end
end
describe '#exist?' do
it 'returns true when exists' do
subject.add(account, username, password, key)
expect(subject.exist?(account)).to be_truthy
end
it 'returns true when does not exist' do
subject.add(account, username, password, key)
expect(subject.exist?('no_exist')).to be_falsey
end
context 'when the account is empty' do
let(:account) { '' }
it 'fails' do
expect { subject.exist?(account) }.to raise_error(ArgumentError)
end
end
context 'when the account is nil' do
let(:account) { nil }
it 'fails' do
expect { subject.exist?(account) }.to raise_error(ArgumentError)
end
end
end
describe '#list' do
it 'shows the data' do
subject.add(account, username, password, key, salt)
expect(subject.list).to eq(
account => {
'username' => username, 'password' => <PASSWORD>::Crypto.encrypt(password, key, salt: salt)
}
)
end
it 'shows empty hash if no data is stored' do
subject.delete(account)
expect(subject.list).to eq({})
end
end
end
|
alebian/passman
|
spec/crypto_spec.rb
|
require 'spec_helper'
describe Passman::Crypto do
describe 'encrypting data' do
let!(:password) { '<PASSWORD>' }
let!(:key) { 'supermegaarchisecurekeyofmorethan32bitslong' }
it 'encrypts the password correctly' do
expect(described_class.encrypt(password, key)).not_to eq password
end
it 'decrypts the password correctly' do
encrypted = described_class.encrypt(password, key)
expect(described_class.decrypt(encrypted, key)).to eq password
end
context 'when the key is short' do
let(:key) { 'short' }
it 'encrypts the password correctly' do
expect(described_class.encrypt(password, key)).not_to eq password
end
it 'decrypts the password correctly' do
encrypted = described_class.encrypt(password, key)
expect(described_class.decrypt(encrypted, key)).to eq password
end
end
context 'when the key is empty' do
let(:key) { '' }
it 'fails' do
expect { described_class.encrypt(password, key) }.to raise_error(ArgumentError)
end
end
context 'when the key is nil' do
let(:key) { nil }
it 'fails' do
expect { described_class.encrypt(password, key) }.to raise_error(ArgumentError)
end
end
context 'when the key has spaces' do
let(:key) { 'this is a key with spaces' }
it 'encrypts the password correctly' do
expect(described_class.encrypt(password, key)).not_to eq password
end
it 'decrypts the password correctly' do
encrypted = described_class.encrypt(password, key)
expect(described_class.decrypt(encrypted, key)).to eq password
end
end
end
describe '.generate_password' do
context 'when using default values' do
it 'creates the password with correct size' do
expect(described_class.generate_password.size).to eq(described_class::MINIMUM_SIZE_KEY)
end
end
context 'when using options' do
it 'uses the upcase dictionary correctly' do
password = described_class.generate_password(1, minimum_upcase_count: 1)
expect(described_class::UPCASE_DICTIONARY.include?(password)).to be_truthy
end
it 'uses the numbers dictionary correctly' do
password = described_class.generate_password(1, minimum_numbers_count: 1)
expect(described_class::NUMBERS_DICTIONARY.include?(password)).to be_truthy
end
it 'uses the symbols dictionary correctly' do
password = described_class.generate_password(1, minimum_symbols_count: 1)
expect(described_class::SYMBOLS_DICTIONARY.include?(password)).to be_truthy
end
end
end
end
|
alebian/passman
|
lib/passman/crypto.rb
|
<gh_stars>1-10
require 'openssl'
require 'bcrypt'
require 'base64'
module Passman
class Crypto
AVAILABLE_CIPHERS = %w[aes-256-cbc aes-128-gcm aes-256-gcm].freeze
MINIMUM_SIZE_KEY = 32
DOWNCASE_DICTIONARY = ('a'..'z').to_a.freeze
UPCASE_DICTIONARY = ('A'..'Z').to_a.freeze
NUMBERS_DICTIONARY = (0..9).to_a.map(&:to_s).freeze
SYMBOLS_DICTIONARY = %w[! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ ] ^ _ ` { | } ~].freeze
FULL_DICTIONARY = (
DOWNCASE_DICTIONARY + UPCASE_DICTIONARY + NUMBERS_DICTIONARY + SYMBOLS_DICTIONARY
)
class << self
def encrypt(password, key, algorithm: AVAILABLE_CIPHERS[0], salt: nil)
cipher = new_cipher(algorithm)
cipher.encrypt
strong_key, salt = sanitize_key(key, salt)
cipher.key = strong_key
encrypted_password = cipher.update(password) + cipher.final
[salt, Base64.strict_encode64(encrypted_password)].join(' ')
end
def decrypt(encrypted_password, key, algorithm: AVAILABLE_CIPHERS[0])
cipher = new_cipher(algorithm)
cipher.decrypt
salt, enc_password = encrypted_password.split(' ')
strong_key, = sanitize_key(key, salt)
cipher.key = strong_key
decrypted_password = cipher.update(Base64.strict_decode64(enc_password))
decrypted_password << cipher.final
end
def generate_password(
length = MINIMUM_SIZE_KEY,
minimum_upcase_count: 0, minimum_numbers_count: 0, minimum_symbols_count: 0
)
expected_characters =
NUMBERS_DICTIONARY.sample(minimum_numbers_count) +
UPCASE_DICTIONARY.sample(minimum_upcase_count) +
SYMBOLS_DICTIONARY.sample(minimum_symbols_count)
raise ArgumentError if expected_characters.size > length
expected_characters += FULL_DICTIONARY.sample(length - expected_characters.size)
expected_characters.shuffle.join
end
private
def new_cipher(algorithm)
raise ArgumentError, 'Invalid cipher' unless AVAILABLE_CIPHERS.include?(algorithm)
OpenSSL::Cipher.new(algorithm)
end
def sanitize_key(key, salt = nil)
raise ArgumentError, 'No key provided.' if key.nil? || key.empty?
salt = BCrypt::Engine.generate_salt if salt.nil?
password = BCrypt::Password.new(BCrypt::Engine.hash_secret(key, salt))
[password, salt]
end
end
end
end
|
alebian/passman
|
lib/passman.rb
|
require 'passman/crypto'
require 'passman/manager'
require 'passman/version'
module Passman
end
|
alebian/passman
|
spec/spec_helper.rb
|
<filename>spec/spec_helper.rb<gh_stars>1-10
require 'simplecov'
SimpleCov.start
require 'passman'
require 'byebug'
|
alebian/passman
|
lib/passman/manager.rb
|
<gh_stars>1-10
require 'passman/crypto'
require 'json'
module Passman
class Manager
DEFAULT_PATH = 'passman.json'.freeze
def initialize(file = nil)
@file_path = DEFAULT_PATH
@file_path = file unless file.nil?
end
def generate_password(length = 32)
<PASSWORD>man::Crypto.generate_password(length)
end
def add(account, username, password, key, salt = nil)
validate_add_arguments(account, username, password, key)
db = database
db[account.to_s] = {
username: username, password: <PASSWORD>::Crypto.encrypt(password, key, salt: salt)
}
store_data(db)
end
def delete(account)
raise ArgumentError, 'No account provided.' unless valid?(account)
db = database
db.delete(account.to_s)
store_data(db)
end
def get(account, key)
validate_get_arguments(account, key)
data = database[account.to_s]
[account.to_s, { 'username' => data['username'],
'password' => <PASSWORD>::Crypto.decrypt(data['password'], key) }]
end
def exist?(account)
raise ArgumentError, 'No account provided.' unless valid?(account)
!(!database[account.to_s])
end
def list
database
end
private
def validate_add_arguments(account, username, password, key)
raise ArgumentError, 'No account provided.' unless valid?(account)
raise ArgumentError, 'No username provided.' unless valid?(username)
raise ArgumentError, 'No password provided.' unless valid?(password)
raise ArgumentError, 'No key provided.' unless valid?(key)
end
def validate_get_arguments(account, key)
raise ArgumentError, 'No account provided.' unless valid?(account)
raise ArgumentError, 'No key provided.' unless valid?(key)
end
def valid?(argument)
!(argument.nil? || argument.empty?)
end
def database
return JSON.parse(File.read(@file_path)) if File.exist?(@file_path)
{}
end
def store_data(data)
File.delete(@file_path) if File.exist?(@file_path)
file = File.open(@file_path, 'w+')
file.write(JSON.generate(data))
file.close
end
end
end
|
alebian/passman
|
passman.gemspec
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'passman/version'
require 'date'
Gem::Specification.new do |spec|
spec.name = 'passman'
spec.version = Passman::VERSION
spec.authors = ['<NAME>']
spec.email = '<EMAIL>'
spec.date = Date.today
spec.summary = 'Password manager.'
spec.description = "PassMan is a password manager that stores your passwords encrypted, let's you retreive them and create new ones."
spec.platform = Gem::Platform::RUBY
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec)/}) }
spec.require_paths = ['lib']
spec.homepage = 'https://github.com/alebian/passman'
spec.license = 'MIT'
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec)/})
spec.add_dependency 'bcrypt', '~> 3.1'
spec.add_dependency 'colorize', '~> 0.7', '>= 0.7.5'
spec.add_dependency 'clipboard', '~> 1.1', '>= 1.1.0'
spec.add_dependency 'highline', '>= 1.7.8', '< 3.0'
spec.add_development_dependency 'bundler', '>= 1.3.0', '< 3.0'
spec.add_development_dependency 'byebug', '>= 9.0.5', '~> 11.1' if RUBY_VERSION >= '2.0.0'
spec.add_development_dependency 'rubocop', '~> 0.58'
spec.add_development_dependency 'rubocop-rspec', '~> 1.27'
end
|
alebian/passman
|
spec/project_spec.rb
|
<reponame>alebian/passman
require 'spec_helper'
describe 'PassMan Project' do
context 'when checking the gem version' do
let(:version) { Passman::VERSION }
it 'is the correct version' do
expect(version).to eq('0.2.0')
end
end
end
|
ngergo100/carthframie
|
spec/carthframie_spec.rb
|
RSpec.describe Carthframie do
it "has a version number" do
expect(Carthframie::VERSION).not_to be nil
end
it "has frameworks path" do
expect(Carthframie::CarthageCopyFrameworks::CARTHAGE_FRAMEWORKS_PATH).to eq("Carthage/Build/**/*.framework")
end
it "has build phase name" do
expect(Carthframie::CarthageCopyFrameworks::COPY_CARTHAGE_BUILD_PHASE_NAME).to eq("Copy Carthage frameworks")
end
it "has shell script" do
expect(Carthframie::CarthageCopyFrameworks::COPY_CARTHAGE_BUILD_PHASE_SHELL_SCRIPT).to eq("/usr/local/bin/carthage copy-frameworks")
end
it "has source root" do
expect(Carthframie::CarthageCopyFrameworks::SRCROOT).to eq("$(SRCROOT)")
end
it "has .app build path" do
expect(Carthframie::CarthageCopyFrameworks::BUILT_PRODUCTS_DIR_FRAMEWORKS_FOLDER_PATH).to eq("$(BUILT_PRODUCTS_DIR)/$(FRAMEWORKS_FOLDER_PATH)")
end
end
|
ngergo100/carthframie
|
lib/carthframie.rb
|
require "carthframie/version"
require "xcodeproj"
require "thor"
module Carthframie
class CarthageCopyFrameworks
CARTHAGE_FRAMEWORKS_PATH = "Carthage/Build/**/*.framework"
COPY_CARTHAGE_BUILD_PHASE_NAME = "Copy Carthage frameworks"
COPY_CARTHAGE_BUILD_PHASE_SHELL_SCRIPT = "/usr/local/bin/carthage copy-frameworks"
SRCROOT = "$(SRCROOT)"
BUILT_PRODUCTS_DIR_FRAMEWORKS_FOLDER_PATH = "$(BUILT_PRODUCTS_DIR)/$(FRAMEWORKS_FOLDER_PATH)"
def initialize(project_path, choosen_target_name)
puts("ℹ️ Loading #{project_path}...")
@root = File.dirname(project_path)
@project = Xcodeproj::Project.open(project_path)
puts("🎉 #{project_path} has been successfully loaded.")
puts("ℹ️ Looking for #{choosen_target_name} target in your project...")
targets = @project.targets.select { |target| target.name == choosen_target_name }
if targets.count > 1 then
puts("⚠️ Multiple targets found with name '#{choosen_target_name}'. Loaded the first one. Please check your target configuration.")
elsif targets.count == 1 then
puts("🎉 #{choosen_target_name} has been successfully loaded.")
else
puts("❌ Did not find target with the given name. Exiting now...")
exit
end
@target = targets.first
end
## Run function
def run
get_frameworks_built_by_carthage
remove_carthage_copy_frameworks_build_phase_if_needed
add_frameworks_to_frameworks_group_if_needed
add_new_copy_frameworks_build_phase
puts("ℹ️ Saving project...")
@project.save
puts("🎉 Project saved.")
end
## Helper functions
def get_frameworks_built_by_carthage
puts("ℹ️ Looking for frameworks in your project...")
@framework_paths = Dir[CARTHAGE_FRAMEWORKS_PATH] # Finds '.framework' files recursively
if @framework_paths.count > 0 then
@framework_names = @framework_paths.map { |file| File.basename(file) }
puts("🎉 Found #{@framework_names.count} frameworks:\n - 📦 #{@framework_names.join("\n - 📦 ")}")
else
puts("❌️ Did not find any files with '.framework' extension. Exiting now...")
exit
end
end
def remove_carthage_copy_frameworks_build_phase_if_needed
puts("ℹ️ Checking existing build phases...")
carthage_build_phases = @target.shell_script_build_phases.select { |build_phase|
build_phase.shell_script.include? " copy-frameworks" and build_phase.name.include? "Carthage"
}
carthage_build_phases.each { |carthage_build_phase|
puts("⚠️ Removing existing build phase with name '#{carthage_build_phase.name}'...")
carthage_build_phase.remove_from_project
}
end
def add_frameworks_to_frameworks_group_if_needed
puts("ℹ️ Checking existing file references in the project...")
project_file_paths = @project.files.map { |file| file.path }
linked_frameworks_build_phase = @target.frameworks_build_phase.files_references.map { |file_reference| file_reference.path }
@framework_paths.each { |framework_path|
if !project_file_paths.include? framework_path then
new_reference = @project.new_file(framework_path)
new_reference.move(@project.frameworks_group)
puts("🎉 New file created at path: #{new_reference.path}")
else
puts("ℹ️ Framework at path '#{framework_path}' is already added to the project")
end
if !linked_frameworks_build_phase.include? framework_path then
existing_reference = @project.files.select { |file| file.path == framework_path }
if existing_reference.count > 0 then # By now framework should be added to the file references
@target.frameworks_build_phase.add_file_reference(existing_reference.first, true)
puts("🎉 New framework has sucessfully linked to the target")
else
puts("❌️ Some error happened during adding existing framework to your linked binearies phase, check your framework configurations!")
end
else
puts("ℹ️ Framework at path '#{framework_path}' is already linked to the target")
end
}
end
def add_new_copy_frameworks_build_phase
puts("ℹ️ Creating '#{COPY_CARTHAGE_BUILD_PHASE_NAME}' build phase...")
newBuildPhase = @target.new_shell_script_build_phase(COPY_CARTHAGE_BUILD_PHASE_NAME)
newBuildPhase.shell_script = COPY_CARTHAGE_BUILD_PHASE_SHELL_SCRIPT
newBuildPhase.input_paths = @framework_paths.map { |framework_path| "#{SRCROOT}/#{framework_path}" }
newBuildPhase.output_paths = @framework_names.map { |framework_name| "#{BUILT_PRODUCTS_DIR_FRAMEWORKS_FOLDER_PATH}/#{framework_name}" }
puts("🎉 Successfully added new copy build phase to #{@target.name} target.")
end
end
class Cli < Thor
desc 'add_frameworks Example.xcodeproj Example', 'Adds carthage framework to Example target of Example.xcodeproj'
def add_frameworks(project, target)
CarthageCopyFrameworks.new(project, target).run
end
end
end
|
pcg79/nfl_api
|
spec/nfl_api/models/roster_spec.rb
|
<reponame>pcg79/nfl_api<filename>spec/nfl_api/models/roster_spec.rb
require 'spec_helper'
describe NFLApi::Roster do
let(:teams_current_season_endpoint) { File.join(File.dirname(__FILE__), "..", "..", "fixtures", "nfl_teams.json") }
let(:roster_current_season_endpoint) { File.join(File.dirname(__FILE__), "..", "..", "fixtures", "nfl_roster_redskins_2019.json") }
let(:teams_season_specific_endpoint) { File.join(File.dirname(__FILE__), "..", "..", "fixtures", "nfl_teams_2018.json") }
let(:roster_season_specific_endpoint) { File.join(File.dirname(__FILE__), "..", "..", "fixtures", "nfl_roster_redskins_2018.json") }
context ".by_team" do
it "gets the current season roster by team name" do
expect(NFLApi::Team).to receive(:endpoint).and_return(teams_current_season_endpoint)
expect(NFLApi::Roster).to receive(:endpoint).and_return(roster_current_season_endpoint)
roster = described_class.by_team("<NAME>")
expect(roster.season).to eq 2019
expect(roster.team.id).to eq 5110
expect(roster.team_players.count).to be > 1
expect(roster.team_players.first.nfl_id).not_to be_nil
end
it "gets the current season roster by team id" do
expect(NFLApi::Team).to receive(:endpoint).and_return(teams_current_season_endpoint)
expect(NFLApi::Roster).to receive(:endpoint).and_return(roster_current_season_endpoint)
roster = described_class.by_team(5110)
expect(roster.season).to eq 2019
expect(roster.team.full_name).to eq "<NAME>"
expect(roster.team_players.count).to be > 1
end
end
context ".by_team_and_season" do
it "gets the correct season's roster by team name" do
expect(NFLApi::Team).to receive(:season_specific_endpoint).and_return(teams_season_specific_endpoint)
expect(NFLApi::Roster).to receive(:season_specific_endpoint).and_return(roster_season_specific_endpoint)
roster = described_class.by_team_and_season("<NAME>", "2018")
expect(roster.season).to eq 2018
expect(roster.team.id).to eq 5110
expect(roster.team_players.count).to be > 1
expect(roster.team_players.first.nfl_id).not_to be_nil
end
it "gets the correct season's roster by team id" do
end
end
end
|
pcg79/nfl_api
|
lib/nfl_api/models.rb
|
require "nfl_api/models/base"
require "nfl_api/models/team"
require "nfl_api/models/conference"
require "nfl_api/models/division"
require "nfl_api/models/roster"
require "nfl_api/models/player"
|
pcg79/nfl_api
|
lib/nfl_api/models/player.rb
|
module NFLApi
class Player < Base
# "season": 2019,
# "nflId": 2562817,
# "status": "ACT",
# "displayName": "<NAME>",
# "firstName": "B.J.",
# "lastName": "Blunt",
# "esbId": "BLU745149",
# "gsisId": "00-0034923",
# "birthDate": "04/21/1995",
# "homeTown": "",
# "collegeId": 6403,
# "collegeName": "<NAME>",
# "positionGroup": "LB",
# "position": "LB",
# "jerseyNumber": 48,
# "height": "6-1",
# "weight": 220,
# "yearsOfExperience": 0,
# "teamAbbr": "WAS",
# "teamSeq": 1,
# "teamId": "5110",
# "teamFullName": "<NAME>"
attr_reader :season, :nfl_id, :status, :display_name,
:first_name, :last_name, :esb_id, :gsis_id, :birth_date,
:home_town, :college_id, :college_name, :position_group,
:position, :jersey_number, :height, :weight,
:years_of_experience, :team_abbr, :team_seq, :team_id,
:team_full_name
def initialize(params)
@season = params["season"]
@nfl_id = params["nflId"]
@status = params["status"]
@display_name = params["displayName"]
@first_name = params["firstName"]
@last_name = params["lastName"]
@esb_id = params["esbId"]
@gsis_id = params["gsisId"]
@birth_date = params["birthDate"]
@home_town = params["homeTown"]
@college_id = params["collegeId"]
@college_name = params["collegeName"]
@position_group = params["positionGroup"]
@position = params["position"]
@jersey_number = params["jerseyNumber"]
@height = params["height"]
@weight = params["weight"]
@years_of_experience = params["yearsOfExperience"]
@team_abbr = params["teamAbbr"]
@team_seq = params["teamSeq"]
@team_id = params["teamId"]
@team_full_name = params["teamFullName"]
end
end
end
|
pcg79/nfl_api
|
spec/nfl_api/models/team_spec.rb
|
require 'spec_helper'
describe NFLApi::Team do
let(:current_season_endpoint) { File.join(File.dirname(__FILE__), "..", "..", "fixtures", "nfl_teams.json") }
let(:season_specific_endpoint) { File.join(File.dirname(__FILE__), "..", "..", "fixtures", "nfl_teams_2018.json") }
context ".all" do
it "returns the correct number of teams" do
expect(described_class).to receive(:endpoint).and_return(current_season_endpoint)
teams = 32
pro_bowl_teams = 2
total_teams = teams + pro_bowl_teams
expect(described_class.all.count).to eq total_teams
end
it "returns the current season" do
expect(described_class).to receive(:endpoint).and_return(current_season_endpoint)
expect(described_class.all.first.season).to eq 2019
end
end
context ".season" do
it "returns nil if nil is passed in" do
expect(described_class.by_season(nil)).to be_nil
end
it "returns nil if no data is received from the API" do
expect(described_class).to receive(:parse_json).with("http://www.nfl.com/feeds-rs/teams/1938.json").and_return(nil)
expect(described_class.by_season(1938)).to be_nil
end
it "returns the correct number of teams for a prior season" do
expect(described_class).to receive(:season_specific_endpoint).and_return(season_specific_endpoint)
teams = 32
pro_bowl_teams = 2
total_teams = teams + pro_bowl_teams
expect(described_class.by_season(2018).count).to eq total_teams
end
it "returns the correct season for a prior season" do
expect(described_class).to receive(:season_specific_endpoint).and_return(season_specific_endpoint)
expect(described_class.by_season(2018).first.season).to eq 2018
end
end
context ".by_team" do
context "with team name" do
it "returns the correct team" do
expect(described_class).to receive(:endpoint).and_return(current_season_endpoint)
expect(described_class.by_team("<NAME>").id).to eq 5110
end
end
context "with team id" do
it "returns the correct team" do
expect(described_class).to receive(:endpoint).and_return(current_season_endpoint)
expect(described_class.by_team(5110).full_name).to eq "<NAME>"
end
end
end
context ".by_team_and_season" do
context "with team name and season year" do
it "returns the correct team" do
expect(described_class).to receive(:season_specific_endpoint).and_return(season_specific_endpoint)
team = described_class.by_team_and_season("<NAME>", 2018)
expect(team.id).to eq 5110
expect(team.season).to eq 2018
end
end
context "with team id and season year" do
it "returns the correct team" do
expect(described_class).to receive(:season_specific_endpoint).and_return(season_specific_endpoint)
team = described_class.by_team_and_season(5110, 2018)
expect(team.full_name).to eq "<NAME>"
expect(team.season).to eq 2018
end
end
end
end
|
pcg79/nfl_api
|
lib/nfl_api.rb
|
require "nfl_api/version"
require "nfl_api/models"
module NFLApi
NFL_START_YEAR = 1920
end
|
pcg79/nfl_api
|
lib/nfl_api/models/division.rb
|
<reponame>pcg79/nfl_api<gh_stars>0
module NFLApi
class Division
# "division":{"id":"0018",
# "abbr":"NCW",
# "fullName":"NFC West Division"},
attr_reader :id, :abbr, :full_name
def initialize(params)
@id = params["id"]
@abbr = params["abbr"]
@full_name = params["fullName"]
end
end
end
|
pcg79/nfl_api
|
lib/nfl_api/models/team.rb
|
<filename>lib/nfl_api/models/team.rb
module NFLApi
class Team < Base
# {"season":2019,
# "teamId":"3800",
# "abbr":"ARI",
# "cityState":"Arizona",
# "fullName":"<NAME>",
# "nick":"Cardinals",
# "teamType":"TEAM",
# "conferenceAbbr":"NFC",
# "divisionAbbr":"NCW",
# "conference":{"id":"0015",
# "abbr":"NFC",
# "fullName":"National Football Conference"},
# "division":{"id":"0018",
# "abbr":"NCW",
# "fullName":"NFC West Division"},
# "yearFound":1920,
# "stadiumName":"State Farm Stadium",
# "ticketPhoneNumber":"602-379-0102",
# "teamSiteUrl":"http://www.azcardinals.com/",
# "teamSiteTicketUrl":"http://www.azcardinals.com/tickets/"},
attr_reader :season, :id, :abbr, :city_state, :full_name,
:nick, :team_type, :conference_abbr, :division_abbr, :conference,
:division, :year_found, :stadium_name, :ticket_phone_number,
:team_site_url, :team_site_ticket_url
def initialize(params)
@season = params["season"]
@id = params["teamId"].to_i
@abbr = params["abbr"]
@city_state = params["cityState"]
@full_name = params["fullName"]
@nick = params["nick"]
@team_type = params["teamType"]
@conference_abbr = params["conferenceAbbr"]
@division_abbr = params["divisionAbbr"]
set_conference(params["conference"])
set_division(params["division"])
@year_found = params["yearFound"]
@stadium_name = params["stadiumName"]
@ticket_phone_number = params["ticketPhoneNumber"]
@team_site_url = params["teamSiteUrl"]
@team_site_ticket_url = params["teamSiteTicketUrl"]
end
def self.all
teams = parse_json(endpoint)["teams"]
teams.map do |team_data|
Team.new(team_data)
end
end
def self.by_team(name_or_id)
all.detect { |t| [t.id, t.full_name].include? name_or_id }
end
def self.by_season(season_number)
return nil if season_number.to_i < NFLApi::NFL_START_YEAR
json_data = parse_json(season_specific_endpoint(season_number))
return nil unless json_data
teams = json_data["teams"]
teams.map do |team_data|
Team.new(team_data)
end
end
def self.by_team_and_season(name_or_id, season_number)
by_season(season_number).detect { |t| [t.id, t.full_name].include? name_or_id }
end
private
def set_conference(conference_params)
conference_id = conference_params["id"]
if Team.conferences[conference_id]
@conference = Team.conferences[conference_id]
else
@conference = Conference.new(conference_params)
end
Team.conferences[conference_id] = @conference
end
def set_division(division_params)
if division_params
division_id = division_params["id"]
if Team.divisions[division_id]
@division = Team.divisions[division_id]
else
@division = Division.new(division_params)
end
end
Team.divisions[division_id] = @division
end
def self.conferences
@conferences ||= {}
end
def self.divisions
@divisions ||= {}
end
def self.endpoint
"http://www.nfl.com/feeds-rs/teams.json"
end
def self.season_specific_endpoint(season_number)
"http://www.nfl.com/feeds-rs/teams/#{season_number}.json"
end
end
end
|
pcg79/nfl_api
|
lib/nfl_api/models/base.rb
|
<reponame>pcg79/nfl_api
require 'open-uri'
require 'json'
module NFLApi
class Base
def self.parse_json(endpoint)
JSON.load(open(endpoint))
end
end
end
|
pcg79/nfl_api
|
spec/spec_helper.rb
|
<reponame>pcg79/nfl_api
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..'))
require 'webmock/rspec'
require 'pry-byebug'
require 'nfl_api'
|
pcg79/nfl_api
|
lib/nfl_api/models/conference.rb
|
module NFLApi
class Conference
# "conference":{"id":"0015",
# "abbr":"NFC",
# "fullName":"National Football Conference"},
attr_reader :id, :abbr, :full_name
def initialize(params)
@id = params["id"]
@abbr = params["abbr"]
@full_name = params["fullName"]
end
end
end
|
pcg79/nfl_api
|
lib/nfl_api/models/roster.rb
|
module NFLApi
class Roster < Base
# {
# "season": 2019,
# "team": {
# "season": 2019,
# "teamId": "5110",
# "abbr": "WAS",
# "cityState": "Washington",
# "fullName": "<NAME>",
# "nick": "Redskins",
# "teamType": "TEAM",
# "conferenceAbbr": "NFC",
# "divisionAbbr": "NCE"
# },
# "teamPlayers": [{
# },
attr_reader :season, :team, :team_players
def initialize(season, team, team_players)
@season = season
@team = team
@team_players = team_players
end
# We need the team id to get their roster. So theoretically if we
# receive a team id we shouldn't need to do an extra API call to
# get the team. But the /roster endpoint returns an abbreviated
# version of the Team. So we'll just get the team from the
# /team endpoint in both cases so we have the full team data.
#
def self.by_team(team_id_or_name)
team = Team.by_team(team_id_or_name)
json_data = parse_json(endpoint(team.id))
season = json_data["season"]
team_players = player_array(json_data["teamPlayers"])
new season, team, team_players
end
def self.by_team_and_season(team_id_or_name, season_year)
return nil if season_year.to_i < NFLApi::NFL_START_YEAR
team = Team.by_team_and_season(team_id_or_name, season_year)
json_data = parse_json(season_specific_endpoint(team.id, season_year))
season = json_data["season"]
team_players = player_array(json_data["teamPlayers"])
new season, team, team_players
end
private
def self.player_array(team_players_data)
team_players_data.map do |team_player|
Player.new(team_player)
end
end
def self.endpoint(team_id)
"http://www.nfl.com/feeds-rs/roster/#{team_id}.json"
end
def self.season_specific_endpoint(team_id, season_year)
"http://www.nfl.com/feeds-rs/roster/#{team_id}/#{season_year}.json"
end
end
end
|
pcg79/nfl_api
|
spec/nfl_api_test.rb
|
require "spec_helper"
describe NFLApiTest
def test_that_it_has_a_version_number
refute_nil ::NFLApi::VERSION
end
end
|
jskyzero/design.jskyzero.com
|
_plugins/time_checker.rb
|
<filename>_plugins/time_checker.rb
# # does not work
# # unhappy
# module Jekyll
# module TimeFilter
# private
# def compare(posted_time, modified_time)
# # checker = DateTime.new(2021, 10, 1, 0, 0, 0, now.zone).to_s
# # posted_time > checker
# false
# end
# def sort_post_filter(posts)
# posts.select { |post|
# posted_time = post.data['date'].to_datetime.to_s
# modified_time = post.data['last_modified_at'].to_datetime.to_s
# compare(posted_time, modified_time)
# }
# end
# def default_post_filter(posts)
# posts.select { |post|
# posted_time = post.data['date'].to_datetime.to_s
# modified_time = post.data['last_modified_at'].to_datetime.to_s
# not compare(posted_time, modified_time)
# }
# end
# end
# end
# Liquid::Template.register_filter(Jekyll::TimeFilter)
|
jskyzero/design.jskyzero.com
|
_plugins/post-data-last-modified-at.rb
|
# frozen_string_literal: true
require 'fileutils'
require 'pathname'
require 'jekyll-last-modified-at'
module Recents
# Generate change information for all markdown pages
class Generator < Jekyll::Generator
def generate(site)
items = site.posts.docs.select { |p| p.path.end_with? '.md' }
items.each do |page|
modified_time = Jekyll::LastModifiedAt::Determinator.new(site.source, page.path, '%FT%T%:z').to_s
check_time = Time.new(2021,10).strftime('%FT%T%:z')
if modified_time > check_time
page.data['last_modified_at_str'] = modified_time
page.data['use_modified'] = true
else
page.data['last_modified_at_str'] = check_time
page.data['use_modified'] = false
end
end
puts("FINISH: post-data-last-modified-at")
end
end
end
|
work-furukawa/ruboty-whatday
|
lib/ruboty/whatday/actions/whatday.rb
|
require 'wikipedia'
require 'date'
module Ruboty
module Whatday
module Actions
class Whatday < Ruboty::Actions::Base
WIKIPEDIA_DOMAIN_JP = 'ja.wikipedia.org'
WIKI_API_PARAMS = {
format: 'json',
action: 'query',
prop: 'revisions',
rvprop: 'content',
titles: '',
}
SECTION = {
event: 'できごと',
birthday: '誕生日',
death: '忌日',
anniversary: '記念日',
ceremony: '行事',
other: 'その他'
}
def call
message.reply(whatday)
end
private
def whatday
Wikipedia.configure {
domain WIKIPEDIA_DOMAIN_JP
path 'w/api.php'
}
yymm = to_search_keyword(message[:mmdd])
if yymm.nil?
message.reply '日付けが不正です。'
return
end
puts yymm
page = Wikipedia.find(yymm)
if page.summary.nil?
msg = "みつかりませんでした。"
else
content_h = parse_content(page.content)
sections = target_sections(message[:keyword].chomp)
pickup_content_h = pickup_content(content_h, sections)
msg = format_msg(pickup_content_h)
end
message.reply msg
end
private
def to_search_keyword(input_yymm)
valid_date_str =
case input_yymm
when /\A[0-9]{4}\z/
"2000-#{input_yymm[0...2]}-#{input_yymm[2...4]}"
when /\A[0-9]{1,2}\/[0-9]{1,2}\z/
"2000/#{input_yymm}"
when /\A[0-9]{1,2}-[0-9]{1,2}\z/
"2000-#{input_yymm}"
else
nil
end
Date.parse(valid_date_str).strftime('%-m月%-d日') rescue nil
end
def parse_content(content)
h = {}
key = ""
content.each_line do |line|
line.chomp!
next if line.empty?
if line.start_with?('==') && line.end_with?('==')
key = line
h[key] = []
else
h[key] << line if !key.empty? && line.start_with?('*')
end
end
h
end
def target_sections(keyword)
SECTION.select { |k,v| k.to_s.start_with?(keyword) }
end
def pickup_content(content_h, sections)
return content_h if sections.empty?
content_h.select { |k, _| sections.values.any? { |v| k.include?(v) } }
end
def format_msg(content_h)
content_h.flatten.join("\n")
end
end
end
end
end
|
work-furukawa/ruboty-whatday
|
lib/ruboty/whatday/version.rb
|
module Ruboty
module Whatday
VERSION = "0.1.0"
end
end
|
work-furukawa/ruboty-whatday
|
lib/ruboty/whatday.rb
|
<gh_stars>0
require "ruboty/whatday/version"
require 'ruboty/handlers/whatday'
module Ruboty
module Whatday
class Error < StandardError; end
# Your code goes here...
end
end
|
work-furukawa/ruboty-whatday
|
lib/ruboty/handlers/whatday.rb
|
require "ruboty/whatday/actions/whatday"
module Ruboty
module Handlers
class Whatday < Base
on(
/(date) (?<mmdd>.+) (?<keyword>.+)*/,
name: 'whatday',
description: 'output what day'
)
def whatday(message)
Ruboty::Whatday::Actions::Whatday.new(message).call
end
end
end
end
|
eggc/gc_dm
|
lib/gc_dm.rb
|
<reponame>eggc/gc_dm<filename>lib/gc_dm.rb
require "gc_dm/version"
require "gc_dm/room"
require "gc_dm/rooms"
require "gc_dm/room_html_parser"
require "gc_dm/rooms_html_parser"
require "gc_dm/cache_manager"
module GcDm
class Error < StandardError; end
# Your code goes here...
end
|
eggc/gc_dm
|
lib/gc_dm/rooms.rb
|
<gh_stars>0
module GcDm
class Rooms
def initialize(rooms = [])
@rooms = rooms
end
def load
parser = RoomsHtmlParser.new
@rooms = parser.get_rooms
@rooms.each do |room|
parser = RoomHtmlParser.new(room.href)
room.rank = parser.get_rank
recipe = parser.get_recipe
room.materials = recipe.map do |material_name|
find(material_name)
end
sleep(1)
end
self
end
def find(name)
@rooms.find { |room| room.name == name } || raise("#{name} is not found")
end
def filter_by(rank:)
items = @rooms.select {|room| room.rank == rank }
Rooms.new(items)
end
def to_s
@rooms.map(&:to_s)
end
end
end
|
eggc/gc_dm
|
lib/gc_dm/cache_manager.rb
|
module GcDm
class CacheManager
CACHE_PATH = "/tmp/gcdm-cache"
def self.load
cache = File.read(CACHE_PATH)
Marshal.load(cache)
end
def self.save(object)
File.open(CACHE_PATH, "wb") do |f|
f.write(Marshal.dump(object))
end
end
end
end
|
eggc/gc_dm
|
lib/gc_dm/rooms_html_parser.rb
|
<gh_stars>0
require "open-uri"
require "open-uri/cached"
require "nokogiri"
module GcDm
class RoomsHtmlParser
URL = "https://wikiwiki.jp/duma/%E3%83%80%E3%83%B3%E3%82%B8%E3%83%A7%E3%83%B3%E3%81%AE%E9%83%A8%E5%B1%8B"
def initialize
html = open(URL).read
@doc = Nokogiri::HTML.parse(html)
remove_elements
end
def get_rooms
list = @doc.css("table.style_table tr").map do |tr|
columns = tr.css("td.style_td")
name_column = columns[1]
next unless name_column
next if name_column.text.start_with?("[")
next if name_column.text.empty?
href = columns[1].at_css("a").get_attribute("href")
Room.new(name_column.text.strip, columns[2].text.strip, href)
end
list.compact!
list
end
private
# Remove needless table tags from `@doc`
def remove_elements
marker = false
@doc.at_css("#body").children.each do |child|
if child.get_attribute("id") == "h3_content_1_7"
marker = true
end
if marker
child.remove
end
end
end
end
end
|
eggc/gc_dm
|
lib/gc_dm/room.rb
|
module GcDm
class Room < Struct.new(:name, :description, :href, :materials, :rank)
# この部屋を作成するのに必要なアトムの総数を返す
# @return [Hash] キーがアトムの名前、値が部屋の数
def atoms
if materials && !materials.empty?
materials.each_with_object({}) do |material, result|
material.atoms.each do |k, v|
result[k] = result[k].to_i + v
end
end
else
{ self.name => 1 }
end
end
end
end
|
eggc/gc_dm
|
lib/gc_dm/room_html_parser.rb
|
<reponame>eggc/gc_dm
require "open-uri"
require "open-uri/cached"
require "nokogiri"
module GcDm
class RoomHtmlParser
HOST = "https://wikiwiki.jp/"
def initialize(path)
url = HOST + path
html = open(url).read
@doc = Nokogiri::HTML.parse(html)
end
def get_recipe
@doc.css("table.style_table tr").each_cons(2) do |tr, next_tr|
if tr.children[0].text.match("作成レシピ")
recipe = next_tr.children[0].text.strip[0..-2]
room_names = recipe.split("+").map(&:strip)
room_names.each { |n| n[0] = "疫" if n == "役病" }
return room_names
end
end
return []
end
def get_rank
@doc.css("td.style_td").each do |td|
if td.text.match("★")
return td.text.count("★") + 5
elsif td.text.match("☆")
return td.text.count("☆")
end
end
raise "Rank not found"
end
end
end
|
eggc/gc_dm
|
lib/gc_dm/version.rb
|
module GcDm
VERSION = "0.1.0"
end
|
iCentris/ias_active_directory
|
spec/ias_active_directory/field_type/date_spec.rb
|
<filename>spec/ias_active_directory/field_type/date_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe ::IasActiveDirectory::FieldType::Date do
describe 'concerning .encode' do
it 'can encode' do
time = Time.now
expect(described_class.encode(time)).to eq(time.strftime('%Y%m%d%H%M%S.0Z'))
end
end
describe 'concerning .decode' do
it 'can decode' do
expect(described_class.decode('20170920132127.0Z')).to eq(Time.parse('20170920132127.0Z'))
end
end
end
|
iCentris/ias_active_directory
|
lib/ias_active_directory/field_type/date.rb
|
# frozen_string_literal: true
# IasActiveDirectory namespace
module IasActiveDirectory
# FieldType Namespace
module FieldType
# Date Field Type
class Date
# Converts a time object into an ISO8601 format compatable with Active Directory
def self.encode(local_time)
local_time.strftime('%Y%m%d%H%M%S.0Z')
end
# Decodes an Active Directory date when stored as ISO8601
def self.decode(remote_time)
Time.parse(remote_time)
end
end
end
end
|
iCentris/ias_active_directory
|
lib/ias_active_directory/member.rb
|
# frozen_string_literal: true
# IasActiveDirectory namespace
module IasActiveDirectory
# Member module for Users/Groups
module Member
# Returns true if this member (User or Group) is a member of
# the passed Group object.
def member?(usergroup)
group_dns = memberOf
return false if group_dns.nil? || group_dns.empty?
group_dns.map(&:dn).include?(usergroup.dn)
end
end
end
|
iCentris/ias_active_directory
|
lib/ias_active_directory/attributes/group_type.rb
|
# frozen_string_literal: true
# IasActiveDirectory namespace
module IasActiveDirectory
# Group Type Constants
module GroupType
# Local Group Mask
BUILTIN_LOCAL_GROUP = 0x00000001
# Account Group Mask
ACCOUNT_GROUP = 0x00000002
# Resource Group Mask
RESSOURCE_GROUP = 0x00000004
# Universal Group Mask
UNIVERSAL_GROUP = 0x00000008
# App Basic Group Mask
APP_BASIC_GROUP = 0x00000010
# App Query Group Mask
APP_QUERY_GROUP = 0x00000020
# Security Enabled Mask
SECURITY_ENABLED = 0x80000000
end
end
|
iCentris/ias_active_directory
|
lib/ias_active_directory/sid.rb
|
<gh_stars>0
# frozen_string_literal: true
# IasActiveDirectory Namespace
module IasActiveDirectory
# @!attribute revision
# Revision Number
# @!attribute dashes
# Dashes number
# @!attribute nt_authority
# NT Authority
# @!attribute nt_non_unique
# NT Non Unique
# @!attribute uuids
# Array of UUIDS
# Create a SID from the binary string in the directory
class SID < BinData::Record
endian :little
uint8 :revision
uint8 :dashes
uint48be :nt_authority
uint32 :nt_non_unique
array :uuids, type: :uint32, initial_length: -> { dashes - 1 }
# String representation of the SID
def to_s
['S', revision, nt_authority, nt_non_unique, uuids].join('-')
end
end
end
|
iCentris/ias_active_directory
|
lib/ias_active_directory/version.rb
|
# frozen_string_literal: true
# IasActiveDirectory namespace
module IasActiveDirectory
# Our current Version
VERSION = '0.1.0'
end
|
iCentris/ias_active_directory
|
spec/ias_active_directory/base_spec.rb
|
# frozen_string_literal: true
RSpec.describe IasActiveDirectory::Base do
describe 'concerning constant' do
context 'NIL_FILTER' do
it 'knows the NIL_FILTER class' do
expect(described_class::NIL_FILTER).to be_a(Net::LDAP::Filter)
end
it 'knows the @left attribute' do
expect(described_class::NIL_FILTER.instance_variable_get(:@left)).to eql('cn')
end
end
end
end
|
iCentris/ias_active_directory
|
lib/ias_active_directory/attributes/sam_account_type.rb
|
# frozen_string_literal: true
# IasActiveDirectory namespace
module IasActiveDirectory
# SAM Account Type constants
module SamAccountType
# Domain Object Mask
DOMAIN_OBJECT = 0x0
# Group Object Mask
GROUP_OBJECT = 0x10000000
# Non Security Group Object Mask
NON_SECURITY_GROUP_OBJECT = 0x10000001
# Alias Object Mask
ALIAS_OBJECT = 0x20000000
# Non Security Alias object Mask
NON_SECURITY_ALIAS_OBJECT = 0x20000001
# User Object Mask
USER_OBJECT = 0x30000000
# Normal User Account Mask
NORMAL_USER_ACCOUNT = 0x30000000
# Machine Account Mask
MACHINE_ACCOUNT = 0x30000001
# Trust Account Mask
TRUST_ACCOUNT = 0x30000002
# App Basic Group Mask
APP_BASIC_GROUP = 0x40000000
# App Query Group Mask
APP_QUERY_GROUP = 0x40000001
# Account Type Max Mask
ACCOUNT_TYPE_MAX = 0x7fffffff
end
end
|
iCentris/ias_active_directory
|
lib/ias_active_directory/container.rb
|
<filename>lib/ias_active_directory/container.rb
# frozen_string_literal: true
# IasActiveDirectory namespace
module IasActiveDirectory
#
# The ::IasActiveDirectory::Container class represents a more malleable way
# of dealing with LDAP Distinguished Names (dn), like
# "cn=UserName,ou=Users,dc=example,dc=org".
#
# The following two representations of the above dn are identical:
#
# dn = "cn=UserName,ou=Users,dc=example,dc=org"
# dn = ::IasActiveDirectory::Container.dc('org').dc('example').ou('Users').cn('UserName').to_s
#
class Container
attr_reader :type
attr_reader :name
attr_reader :parent
def initialize(type, name, node = nil) #:nodoc:
@type = type
@name = name
@node = node
end
# Creates a starting OU (Organizational Unit) dn part.
#
# # ou_part = "ou=OrganizationalUnit"
# ou_part = ::IasActiveDirectory::Container.ou('OrganizationalUnit').to_s
def self.ou(name)
new(:ou, name, nil)
end
# Creates a starting DC (Domain Component) dn part.
#
# # dc_part = "dc=net"
# dc_part = ::IasActiveDirectory::Container.dc('net').to_s
def self.dc(name)
new(:dc, name, nil)
end
# Creates a starting CN (Canonical Name) dn part.
#
# # cn_part = "cn=CanonicalName"
# cn_part = ::IasActiveDirectory::Container.cn('CanonicalName').to_s
def self.cn(name)
new(:cn, name, nil)
end
# Appends an OU (Organizational Unit) dn part to another Container.
#
# # ou = "ou=InfoTech,dc=net"
# ou = ::IasActiveDirectory::Container.dc("net").ou("InfoTech").to_s
def ou(name)
self.class.new(:ou, name, self)
end
# Appends a DC (Domain Component) dn part to another Container.
#
# # base = "dc=example,dc=net"
# base = ::IasActiveDirectory::Container.dc("net").dc("example").to_s
def dc(name)
self.class.new(:dc, name, self)
end
# Appends a CN (Canonical Name) dn part to another Container.
#
# # user = "cn=UID,ou=Users"
# user = ::IasActiveDirectory::Container.ou("Users").cn("UID")
def cn(name)
self.class.new(:cn, name, self)
end
# Converts the Container object to its String representation.
def to_s
@node ? "#{@type}=#{name},#{@node}" : "#{@type}=#{name}"
end
def ==(other) #:nodoc:
to_s.casecmp(other.to_s.downcase).zero?
end
end
end
|
iCentris/ias_active_directory
|
lib/ias_active_directory/group.rb
|
# frozen_string_literal: true
require 'ias_active_directory/attributes'
# IasActiveDirectory namespace
module IasActiveDirectory
# ActiveDirectory Group Object
class Group < Base
include Member
def self.filter # :nodoc:
Net::LDAP::Filter.eq(:objectClass, 'group')
end
def self.required_attributes # :nodoc:
{ objectClass: %w[top group] }
end
def reload # :nodoc:
@member_users_non_r = nil
@member_users_r = nil
@member_groups_non_r = nil
@member_groups_r = nil
@groups = nil
super
end
# Returns true if the passed User or Group object belongs to
# this group. For performance reasons, the check is handled
# by the User or Group object passed.
def member?(user)
user.member?(self)
end
# Returns an array of all User objects that belong to this group.
#
# If the recursive argument is passed as false, then only Users who
# belong explicitly to this Group are returned.
#
# If the recursive argument is passed as true, then all Users who
# belong to this Group, or any of its subgroups, are returned.
def member_users(recursive = false)
@member_users = User.find(:all, distinguishedname: @entry[:member]).delete_if(&:nil?)
if recursive
member_groups.each do |group|
@member_users.concat(group.member_users(true))
end
end
@member_users
end
# Returns an array of all Group objects that belong to this group.
#
# If the recursive argument is passed as false, then only Groups that
# belong explicitly to this Group are returned.
#
# If the recursive argument is passed as true, then all Groups that
# belong to this Group, or any of its subgroups, are returned.
def member_groups(recursive = false)
@member_groups ||= Group.find(:all, distinguishedname: @entry[:member]).delete_if(&:nil?)
if recursive
member_groups.each do |group|
@member_groups.concat(group.member_groups(true))
end
end
@member_groups
end
# Returns an array of Group objects that this Group belongs to.
def groups
return [] if memberOf.nil?
@groups ||= Group.find(:all, distinguishedname: @entry.memberOf).delete_if(&:nil?)
end
end
end
|
iCentris/ias_active_directory
|
spec/ias_active_directory/attributes/group_type_spec.rb
|
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe ::IasActiveDirectory::GroupType do
describe 'concerning constants' do
it 'knows BUILTIN_LOCAL_GROUP' do
expect(described_class::BUILTIN_LOCAL_GROUP).to eql(0x00000001)
end
it 'knows ACCOUNT_GROUP' do
expect(described_class::ACCOUNT_GROUP).to eql(0x00000002)
end
it 'knows RESSOURCE_GROUP' do
expect(described_class::RESSOURCE_GROUP).to eql(0x00000004)
end
it 'knows UNIVERSAL_GROUP' do
expect(described_class::UNIVERSAL_GROUP).to eql(0x00000008)
end
it 'knows APP_BASIC_GROUP' do
expect(described_class::APP_BASIC_GROUP).to eql(0x00000010)
end
it 'knows APP_QUERY_GROUP' do
expect(described_class::APP_QUERY_GROUP).to eql(0x00000020)
end
it 'knows SECURITY_ENABLED' do
expect(described_class::SECURITY_ENABLED).to eql(0x80000000)
end
end
end
|
iCentris/ias_active_directory
|
lib/ias_active_directory/user.rb
|
# frozen_string_literal: true
# IasActiveDirectory namespace
module IasActiveDirectory
# Users in ActiveDirectory
class User < Base
include Member
UAC_ACCOUNT_DISABLED = 0x0002 # User Account Control Account Disabled Mask
UAC_NORMAL_ACCOUNT = 0x0200 # 512
UAC_PASSWORD_NEVER_EXPIRES = 0x10000 # 65536
def self.filter # :nodoc:
Net::LDAP::Filter.eq(:objectClass, 'user') & ~Net::LDAP::Filter.eq(:objectClass, 'computer')
end
def self.required_attributes #:nodoc:
{ objectClass: %w[top organizationalPerson person user] }
end
# Try to authenticate the current User against Active Directory
# using the supplied password. Returns false upon failure.
#
# Authenticate can fail for a variety of reasons, primarily:
#
# * The password is wrong
# * The account is locked
# * The account is disabled
#
# User#locked? and User#disabled? can be used to identify the
# latter two cases, and if the account is enabled and unlocked,
# Athe password is probably invalid.
def authenticate(password)
return false if password.to_s.empty?
@@ldap.dup.bind_as(
filter: "(sAMAccountName=#{sAMAccountName})",
password: password
)
end
# Returns an array of Group objects that this User belongs to.
# Only the immediate parent groups are returned, so if the user
# Sally is in a group called Sales, and Sales is in a group
# called Marketting, this method would only return the Sales group.
def groups
@groups ||= Group.find(:all, distinguishedname: @entry[:memberOf])
end
# Returns true if this account has been locked out
# (usually because of too many invalid authentication attempts).
#
# Locked accounts can be unlocked with the User#unlock! method.
def locked?
!lockout_time.nil? && lockout_time.to_i != 0
end
# Returns true if this account has been disabled.
def disabled?
userAccountControl.to_i & UAC_ACCOUNT_DISABLED != 0
end
# Returns true if this account is expired.
def expired?
!lockout_time.nil? && lockout_time.to_i != 0
end
# Returns true if this account has a password that does not expire.
def password_never_expires?
userAccountControl.to_i & UAC_PASSWORD_NEVER_EXPIRES != 0
end
# Returns true if the user should be able to log in with a correct
# password (essentially, their account is not disabled or locked
# out).
def can_login?
!disabled? && !locked?
end
# This isn't always set in the LDAP entry but we want to default it to something safe.
def lockout_time
if valid_attribute? :lockouttime
get_attr('lockouttime').presence
else
'0'
end
end
end
end
|
iCentris/ias_active_directory
|
lib/ias_active_directory/field_type/binary.rb
|
# frozen_string_literal: true
# IasActiveDirectory namespace
module IasActiveDirectory
# FieldType Namespace
module FieldType
# Binary Field Type
class Binary
# Encodes a hex string into a GUID
def self.encode(hex_string)
[hex_string].pack('H*')
end
# Decodes a binary GUID as a hex string
def self.decode(guid)
guid.unpack('H*').first.to_s
end
end
end
end
|
iCentris/ias_active_directory
|
lib/ias_active_directory/field_type/password.rb
|
<gh_stars>0
# frozen_string_literal: true
# IasActiveDirectory namespace
module IasActiveDirectory
# FieldType Namespace
module FieldType
# Password Field Type
class Password
# Encodes an unencrypted password into an encrypted password
# that the Active Directory server will understand.
def self.encode(password)
("\"#{password}\"".split(//).collect { |c| "#{c}\000" }).join
end
# Always returns nil, since you can't decrypt the User's encrypted
# password.
def self.decode(_hashed)
nil
end
end
end
end
|
iCentris/ias_active_directory
|
lib/ias_active_directory/base.rb
|
<reponame>iCentris/ias_active_directory
# frozen_string_literal: true
# IasActiveDirectory Namespace
module IasActiveDirectory
# Base ancestor for AD Objects
# @!attribute ldap
# The LDAP Connection object
# @!attribute ldap_connected
# Determines if LDAP is connected
# @!attribute caching
# Determines if caching is enabled
# @!attribute cache
# The cache store, if enabled.
# @!attribute settings
# The connection settings established in setup method
# @!attribute types
# The types of objects
class Base
# Class Variables, available to ALL subclasses
@@ldap = nil
@@ldap_connected = false
@@caching = false
@@cache = {}
# Class Instance variable, private to Base
@types = {}
# A Net::LDAP::Filter object that doesn't do any filtering
# (outside of check that the CN attribute is present. This
# is used internally for specifying a 'no filter' condition
# for methods that require a filter object.
NIL_FILTER = Net::LDAP::Filter.pres('cn')
# Configures the connection for the Ruby/ActiveDirectory library.
#
# For example:
#
# ::IasActiveDirectory::Base.setup(
# host: 'domain_controller1.example.org',
# port: 389,
# base: 'dc=example,dc=org',
# auth: {
# method: :simple,
# username: '<EMAIL>',
# password: '<PASSWORD>'
# }
# )
#
# This will configure Ruby/ActiveDirectory to connect to the domain
# controller at domain_controller1.example.org, using port 389. The
# domain's base LDAP dn is expected to be 'dc=example,dc=org', and
# Ruby/ActiveDirectory will try to bind as the
# <EMAIL> user, using the supplied password.
#
# Currently, there can be only one active connection per
# execution context.
#
# For more advanced options, refer to the Net::LDAP.new
# documentation.
#
# @param settings [Hash] The ActiveDirectory configuration hash
def self.configure(settings)
@@settings = settings
@@ldap_connected = false
@@ldap = ::Net::LDAP.new(settings)
end
# ==============================================================================================
# Error Handling
# ==============================================================================================
# Retrieve the Errors
def self.error
"#{@@ldap.get_operation_result.code}: #{@@ldap.get_operation_result.message}"
end
# Return the last errorcode that ldap generated
def self.error_code
@@ldap.get_operation_result.code
end
# Check to see if the last query produced an error
# Note: Invalid username/password combinations will not
# produce errors
def self.error?
@@ldap.nil? ? false : @@ldap.get_operation_result.code != 0
end
# ==============================================================================================
# Boolean Attributes and Methods
# ==============================================================================================
# Check to see if we are connected to the LDAP server
# This method will try to connect, if we haven't already
def self.connected?
@@ldap_connected ||= @@ldap.bind unless @@ldap.nil?
@@ldap_connected
rescue ::Net::LDAP::LdapError
false
end
# Check to see if result caching is enabled
def self.cache?
@@caching
end
# Clears the cache
def self.clear_cache
@@cache = {}
end
# Enable caching for queries against the DN only
# This is to prevent membership lookups from hitting the AD unnecessarily
def self.enable_cache
@@caching = true
end
# Disable caching
def self.disable_cache
@@caching = false
end
# ==============================================================================================
def self.filter # :nodoc:
NIL_FILTER
end
def self.required_attributes # :nodoc:
{}
end
# Check to see if any entries matching the passed criteria exists.
#
# Filters should be passed as a hash of
# attribute_name => expected_value, like:
#
# User.exists?(
# sn: 'Hunt',
# givenName: 'James'
# )
#
# which will return true if one or more User entries have an
# sn (surname) of exactly 'Hunt' and a givenName (first name)
# of exactly 'James'.
#
# Partial attribute matches are available. For instance,
#
# Group.exists?(
# description: 'OldGroup_*'
# )
#
# would return true if there are any Group objects in
# Active Directory whose descriptions start with OldGroup_,
# like OldGroup_Reporting, or OldGroup_Admins.
#
# Note that the * wildcard matches zero or more characters,
# so the above query would also return true if a group named
# 'OldGroup_' exists.
def self.exists?(filter_as_hash)
criteria = make_filter_from_hash(filter_as_hash) & filter
@@ldap.search(filter: criteria).!empty?
end
def self.make_filter_from_hash(hash) # :nodoc:
return NIL_FILTER if hash.nil? || hash.empty?
filter = NIL_FILTER
hash.each do |key, value|
filter &= make_filter(key, value)
end
filter
end
# Retrieve the record based on the DN
def self.from_dn(dn)
ldap_result = @@ldap.search(filter: '(objectClass=*)', base: dn)
return nil unless ldap_result
ad_obj = new(ldap_result[0])
@@cache[ad_obj.dn] = ad_obj unless ad_obj.instance_of?(Base)
ad_obj
end
# Performs a search on the Active Directory store, with similar
# syntax to the Rails ActiveRecord#find method.
#
# The first argument passed should be
# either :first or :all, to indicate that we want only one
# (:first) or all (:all) results back from the resultant set.
#
# The second argument should be a hash of attribute_name =>
# expected_value pairs.
#
# User.find(:all, sn: 'Hunt')
#
# would find all of the User objects in Active Directory that
# have a surname of exactly 'Hunt'. As with the Base.exists?
# method, partial searches are allowed.
#
# This method always returns an array if the caller specifies
# :all for the search e (first argument). If no results
# are found, the array will be empty.
#
# If you call find(:first, ...), you will either get an object
# (a User or a Group) back, or nil, if there were no entries
# matching your filter.
def self.find(*args)
return false unless connected?
options = {
filter: args[1].nil? ? NIL_FILTER : args[1],
in: args[1].nil? ? '' : (args[1][:in] || '')
}
options[:filter].delete(:in)
cached_results = find_cached_results(args[1])
return cached_results if cached_results || cached_results.nil?
options[:in] = [options[:in].to_s, @@settings[:base]].delete_if(&:empty?).join(',')
if options[:filter].is_a? Hash
options[:filter] = make_filter_from_hash(options[:filter])
end
options[:filter] = options[:filter] & filter unless filter == NIL_FILTER
if args.first == :all
find_all(options)
elsif args.first == :first
find_first(options)
else
raise ArgumentError, 'Invalid specifier (not :all, and not :first) passed to find()'
end
end
# Searches the cache and returns the result
# Returns false on failure, nil on wrong object type
def self.find_cached_results(filters)
return false unless cache?
# Check to see if we're only looking for :distinguishedname
return false unless filters.is_a?(Hash) && filters.keys == [:distinguishedname]
# Find keys we're looking up
dns = filters[:distinguishedname]
if dns.is_a? Array
result = []
dns.each do |dn|
entry = @@cache[dn]
# If the object isn't in the cache just run the query
return false if entry.nil?
# Only permit objects of the type we're looking for
result << entry if entry.is_a? self
end
return result
else
return false unless @@cache.key? dns
return @@cache[dns] if @@cache[dns].is_a? self
end
end
# Find all records based on the options
def self.find_all(options)
results = []
ldap_objs = @@ldap.search(filter: options[:filter], base: options[:in]) || []
ldap_objs.each do |entry|
ad_obj = new(entry)
@@cache[entry.dn] = ad_obj unless ad_obj.instance_of? Base
results << ad_obj
end
results
end
# Find the first record based on options
def self.find_first(options)
ldap_result = @@ldap.search(filter: options[:filter], base: options[:in])
return nil if ldap_result.empty?
ad_obj = new(ldap_result[0])
@@cache[ad_obj.dn] = ad_obj unless ad_obj.instance_of? Base
ad_obj
end
def self.method_missing(name, *args) # :nodoc:
name = name.to_s
if name[0, 5] == 'find_'
find_spec, attribute_spec = parse_finder_spec(name)
raise ArgumentError, "find: Wrong number of arguments (#{args.size} for #{attribute_spec.size})" unless args.size == attribute_spec.size
filters = {}
[attribute_spec, args].transpose.each { |pr| filters[pr[0]] = pr[1] }
find(find_spec, filter: filters)
else
super name.to_sym, args
end
end
def self.parse_finder_spec(method_name) # :nodoc:
# FIXME: This is a prime candidate for a
# first-class object, FinderSpec
method_name = method_name.gsub(/^find_/, '').gsub(/^by_/, 'first_by_')
find_spec, attribute_spec = *method_name.split('_by_')
find_spec = find_spec.to_sym
attribute_spec = attribute_spec.split('_and_').collect(&:to_sym)
[find_spec, attribute_spec]
end
def ==(other) # :nodoc:
return false if other.nil?
other[:objectguid] == get_attr(:objectguid)
end
# Returns true if this entry does not yet exist in Active Directory.
def new_record?
@entry.nil?
end
# Refreshes the attributes for the entry with updated data from the
# domain controller.
def reload
return false if new_record?
@entry = @@ldap.search(filter: Net::LDAP::Filter.eq('distinguishedName', distinguishedName))[0]
!@entry.nil?
end
# Updates a single attribute (name) with one or more values
# (value), by immediately contacting the Active Directory
# server and initiating the update remotely.
#
# Entries are always reloaded (via Base.reload) after calling
# this method.
def update_attribute(name, value)
update_attributes(name.to_s => value)
end
# TODO: Redact this!
# Updates multiple attributes, like ActiveRecord#update_attributes.
# The updates are immediately sent to the server for processing,
# and the entry is reloaded after the update (if all went well).
def update_attributes(attributes_to_update)
return true if attributes_to_update.empty?
rename = false
operations = []
attributes_to_update.each do |attribute, values|
if attribute == :cn
rename = true
else
if values.nil? || values.empty?
operations << [:delete, attribute, nil]
else
values = [values] unless values.is_a? Array
values = values.collect(&:to_s)
current_value = begin
@entry[attribute]
rescue NoMethodError
nil
end
operations << [(current_value.nil? ? :add : :replace), attribute, values]
end
end
end
unless operations.empty?
@@ldap.modify(
dn: distinguishedName,
operations: operations
)
end
if rename
@@ldap.modify(
dn: distinguishedName,
operations: [[(name.nil? ? :add : :replace), 'samaccountname', attributes_to_update[:cn]]]
)
@@ldap.rename(olddn: distinguishedName, newrdn: 'cn=' + attributes_to_update[:cn], delete_attributes: true)
end
reload
end
# FIXME: Need to document the Base::new
def initialize(attributes = {}) # :nodoc:
if attributes.is_a? Net::LDAP::Entry
@entry = attributes
@attributes = {}
else
@entry = nil
@attributes = attributes
end
end
# Pull the class we're in
# This isn't quite right, as extending the object does funny things to how we
# lookup objects
def self.class_name
@klass ||= (name.include?('::') ? name[/.*::(.*)/, 1] : name)
end
# Grabs the field type depending on the class it is called from
# Takes the field name as a parameter
def self.get_field_type(name)
# Extract class name
throw 'Invalid field name' if name.nil?
type = ::IasActiveDirectory.special_fields[class_name.to_sym][name.to_s.downcase.to_sym]
type.to_s unless type.nil?
end
def self.decode_field(name, value) # :nodoc:
type = get_field_type(name)
if !type.nil? && ::IasActiveDirectory::FieldType.const_defined?(type)
return ::IasActiveDirectory::FieldType.const_get(type).decode(value)
end
value
end
def self.encode_field(name, value) # :nodoc:
type = get_field_type name
if !type.nil? && ::IasActiveDirectory::FieldType.const_defined?(type)
return ::IasActiveDirectory::FieldType.const_get(type).encode(value)
end
value
end
# See if this is a valid attribute for method_missing
def valid_attribute?(name)
@attributes.key?(name) || @entry.attribute_names.include?(name)
end
# Reteive an Attribute
def get_attr(name)
name = name.to_s.downcase
return self.class.decode_field(name, @attributes[name.to_sym]) if @attributes.key?(name.to_sym)
value = @entry[name.to_sym]
if @entry.attribute_names.include? name.to_sym
value = value.first if value.is_a?(Array) && value.size == 1
value = value.to_s if value.nil? || value.size == 1
value = nil.to_s if value.empty?
# Check the binary fields
::IasActiveDirectory.known_binary_fields.include?(name.downcase.to_sym) ? value : self.class.decode_field(name, value)
end
end
# Reads the array of values for the provided attribute. The attribute name
# is canonicalized prior to reading. Returns an empty array if the
# attribute does not exist.
alias [] get_attr
# Weird fluke with flattening, probably because of above attribute
def to_ary; end
# Return the SID
def sid
unless @sid
raise 'Object has no sid' unless valid_attribute? :objectsid
# SID is stored as a binary in the directory
# however, Net::LDAP returns an hex string
#
# As per [1], there seems to be 2 ways to get back binary data.
#
# [str].pack("H*")
# str.gsub(/../) { |b| b.hex.chr }
#
# [1] :
# http://stackoverflow.com/questions/22957688/convert-string-with-hex-ascii-codes-to-characters
#
@sid = SID.read([get_attr(:objectsid)].pack('H*'))
end
@sid.to_s
end
def method_missing(name, args = []) # :nodoc:
name = name.to_s.downcase
return set_attr(name.chop, args) if name[-1] == '='
if valid_attribute? name.to_sym
get_attr(name)
else
super
end
end
# Private Class Methods
class << self
private
# Makes a single filter from a given key and value
# It will try to encode an array if there is a process for it
# Otherwise, it will treat it as an or condition
def make_filter(key, value)
# Join arrays using OR condition
if value.is_a? Array
filter = ~NIL_FILTER
value.each do |v|
filter |= Net::LDAP::Filter.eq(key, encode_field(key, v).to_s)
end
else
filter = Net::LDAP::Filter.eq(key, encode_field(key, value).to_s)
end
filter
end
end
# TODO: Port missing parts here
end # end Base
end # end IasActiveDirectory namespace
|
iCentris/ias_active_directory
|
spec/ias_active_directory_spec.rb
|
# frozen_string_literal: true
RSpec.describe IasActiveDirectory do
describe 'concerning versioning' do
it 'has a version number' do
expect(IasActiveDirectory::VERSION).to eql('0.1.0')
end
end
describe 'concerning module attributes' do
it 'has an attribute for @special_fields' do
expect { IasActiveDirectory.special_fields }.not_to raise_error
end
it 'does not set the special fields to nil' do
expect(IasActiveDirectory.special_fields).not_to be_nil
end
it 'returns the special fields as a hash' do
expect(IasActiveDirectory.special_fields).to be_a(Hash)
end
it 'should have keys for the appropriate base classes' do
%i[Base User Group Computer].each do |k|
expect(IasActiveDirectory.special_fields).to have_key(k)
end
end
# Base
context 'concerning Base special fields' do
it 'should have all the right keys' do
%i[objectguid whencreated whenchanged memberof].each do |k|
expect(IasActiveDirectory.special_fields[:Base]).to have_key(k)
end
end
end
# User
context 'concerning User special fields' do
it 'should have all the right keys' do
%i[objectguid whencreated whenchanged objectsid msexchmailboxguid msexchmailboxsecuritydescriptor lastlogontimestamp pwdlastset accountexpires memberof].each do |k|
expect(IasActiveDirectory.special_fields[:User]).to have_key(k)
end
end
end
# User
context 'concerning User special fields' do
it 'should have all the right keys' do
%i[objectguid whencreated whenchanged objectsid msexchmailboxguid msexchmailboxsecuritydescriptor lastlogontimestamp pwdlastset accountexpires memberof].each do |k|
expect(IasActiveDirectory.special_fields[:User]).to have_key(k)
end
end
end
# Group
context 'concerning Group special fields' do
it 'should have all the right keys' do
%i[objectguid whencreate whenchanged objectsid memberof member].each do |k|
expect(IasActiveDirectory.special_fields[:Group]).to have_key(k)
end
end
end
# Computer
context 'concerning Computer special fields' do
it 'should have all the right keys' do
%i[objectguid whencreated whenchanged objectsid memberof member].each do |k|
expect(IasActiveDirectory.special_fields[:Computer]).to have_key(k)
end
end
end
end
describe 'concerning known_binary_fields' do
it 'knows the known_binary_fields from special_fields' do
expect(IasActiveDirectory.known_binary_fields).to match_array(%i[msexchmailboxguid msexchmailboxsecuritydescriptor objectguid objectsid])
end
end
end
|
iCentris/ias_active_directory
|
spec/ias_active_directory/field_type/binary_spec.rb
|
<filename>spec/ias_active_directory/field_type/binary_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe ::IasActiveDirectory::FieldType::Binary do
describe 'concerning .encode' do
it 'can encode to string to hex (high nibble first)' do
expect(described_class.encode('DEADBEEF')).to eq(['DEADBEEF'].pack('H*'))
end
end
describe 'concerning .decode' do
it 'can decode a hex binary string to normal' do
expect(described_class.decode('\xDE\xAD\xBE\xEF')).to eq('\xDE\xAD\xBE\xEF'.unpack('H*').first.to_s)
end
end
end
|
iCentris/ias_active_directory
|
lib/ias_active_directory/attributes.rb
|
# frozen_string_literal: true
%w[sam_account_type group_type].each do |file_name|
require 'ias_active_directory/attributes/' + file_name
end
|
iCentris/ias_active_directory
|
lib/ias_active_directory.rb
|
# frozen_string_literal: true
require 'ias_active_directory/version'
# External Gem Dependencies
require 'net/ldap'
require 'bindata'
require 'time'
require 'ias_active_directory/sid'
require 'ias_active_directory/base'
require 'ias_active_directory/container'
require 'ias_active_directory/member'
require 'ias_active_directory/user'
require 'ias_active_directory/group'
# Include all our specified field types
%w[
password
binary
date
timestamp
dn_array
user_dn_array
group_dn_array
member_dn_array
].each do |field_type|
require "ias_active_directory/field_type/#{field_type}"
end
# ==================================================================================================
# Monkey Patches
# ==================================================================================================
Net::LDAP::Entry.class_eval do
# If you ever see a value that is contained in this array, is is Binary, so auto decode it for us.
def []=(name, value)
@myhash[self.class.attribute_name(name)] =
if ::IasActiveDirectory.known_binary_fields.include?(name.downcase.to_sym)
[value.first.unpack('H*').first.to_s]
else
Kernel::Array(value)
end
end
end
# ==================================================================================================
# IasActiveDirectory namespace
# @!attribute special_fields
# A hash of the fields in ActiveDirectory that need to be handled as special cases
# @!attribute known_binary_fields
# An array of the known special_fields which are of the Binary type
module IasActiveDirectory
class << self
attr_accessor :special_fields, :known_binary_fields
end
# Return the special fields module variable
def self.special_fields
@special_fields
end
# @param new_fields [Hash] Set the special fields attribute to the value of new_fields
def self.special_fields=(new_fields = {})
@special_fields = new_fields
end
# Default our special fields
self.special_fields = {
# All objects in the AD
Base: {
objectguid: :Binary,
whencreated: :Date,
whenchanged: :Date,
memberof: :DnArray
},
# User objects
User: {
objectguid: :Binary,
objectsid: :Binary,
msexchmailboxguid: :Binary,
msexchmailboxsecuritydescriptor: :Binary,
whencreated: :Date,
whenchanged: :Date,
lastlogontimestamp: :Timestamp,
pwdlastset: :Timestamp,
accountexpires: :Timestamp,
memberof: :MemberDnArray
},
# Group objects
Group: {
objectguid: :Binary,
objectsid: :Binary,
whencreate: :Date,
whenchanged: :Date,
memberof: :GroupDnArray,
member: :MemberDnArray
},
# Computer objects
Computer: {
objectguid: :Binary,
objectsid: :Binary,
whencreated: :Date,
whenchanged: :Date,
memberof: :GroupDnArray,
member: :MemberDnArray
}
}
# Returns all the special fields that are marked as Binary
def self.known_binary_fields
@known_binary_fields ||= @special_fields.values.flat_map { |k| k.select { |_p, q| q == :Binary }.keys }.uniq.sort
end
end
|
iCentris/ias_active_directory
|
lib/ias_active_directory/field_type/user_dn_array.rb
|
# frozen_string_literal: true
# IasActiveDirectory namespace
module IasActiveDirectory
# FieldType Namespace
module FieldType
# User DN Array Field Type
class UserDnArray
# Encodes an array of objects into a list of dns
def self.encode(obj_array)
obj_array.collect(&:dn)
end
# Decodes a list of DNs into the objects that they are
def self.decode(dn_array)
# How to do user or group?
User.find(:all, distinguishedname: dn_array)
end
end
end
end
|
iCentris/ias_active_directory
|
spec/ias_active_directory/attributes/sam_account_type_spec.rb
|
<reponame>iCentris/ias_active_directory
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe ::IasActiveDirectory::SamAccountType do
describe 'concerning constants' do
it 'knows DOMAIN_OBJECT' do
expect(described_class::DOMAIN_OBJECT).to eql(0x0)
end
it 'knows GROUP_OBJECT' do
expect(described_class::GROUP_OBJECT).to eql(0x10000000)
end
it 'knows NON_SECURITY_GROUP_OBJECT' do
expect(described_class::NON_SECURITY_GROUP_OBJECT).to eql(0x10000001)
end
it 'knows ALIAS_OBJECT' do
expect(described_class::ALIAS_OBJECT).to eql(0x20000000)
end
it 'knows NON_SECURITY_ALIAS_OBJECT' do
expect(described_class::NON_SECURITY_ALIAS_OBJECT).to eql(0x20000001)
end
it 'knows USER_OBJECT' do
expect(described_class::USER_OBJECT).to eql(0x30000000)
end
it 'knows NORMAL_USER_ACCOUNT' do
expect(described_class::NORMAL_USER_ACCOUNT).to eql(0x30000000)
end
it 'knows MACHINE_ACCOUNT' do
expect(described_class::MACHINE_ACCOUNT).to eql(0x30000001)
end
it 'knows TRUST_ACCOUNT' do
expect(described_class::TRUST_ACCOUNT).to eql(0x30000002)
end
it 'knows APP_BASIC_GROUP' do
expect(described_class::APP_BASIC_GROUP).to eql(0x40000000)
end
it 'knows APP_QUERY_GROUP' do
expect(described_class::APP_QUERY_GROUP).to eql(0x40000001)
end
it 'knows ACCOUNT_TYPE_MAX' do
expect(described_class::ACCOUNT_TYPE_MAX).to eql(0x7fffffff)
end
end
end
|
iCentris/ias_active_directory
|
lib/ias_active_directory/field_type/member_dn_array.rb
|
# frozen_string_literal: true
# IasActiveDirectory namespace
module IasActiveDirectory
# FieldType Namespace
module FieldType
# Member DN Array Field Type
class MemberDnArray
# Encodes an array of objects into a list of dns
def self.encode(obj_array)
obj_array.collect(&:dn)
end
# Decodes a list of DNs into the objects that they are
def self.decode(dn_array)
# Ensures that the objects are cast correctly
users = User.find(:all, distinguishedname: dn_array)
groups = Group.find(:all, distinguishedname: dn_array)
arr = []
arr << users unless users.nil?
arr << groups unless groups.nil?
arr.flatten
end
end
end
end
|
ABAgile/kata-game-of-life
|
test/game_test.rb
|
<gh_stars>0
require 'minitest/autorun'
require 'minitest/pride'
require_relative '../lib/game'
describe Game do
end
|
ABAgile/kata-game-of-life
|
lib/game.rb
|
# class for Game-of-life simulation
class Game
end
|
TDAF/ansible-consul-template
|
test/integration/default/serverspec/consul_template_spec.rb
|
require 'spec_helper'
describe 'Consul Template' do
describe service('consul-template') do
it { should be_enabled }
end
describe file('/opt/consul-template/bin/consul-template') do
it { should be_file }
it { should be_executable }
end
describe file('/opt/consul-template/config/consul-template.cfg') do
it { should be_file }
end
describe command('/opt/consul-template/bin/consul-template -v') do
its(:exit_status) { should eq 0 }
its(:stderr) { should match /v0\.12\.0/ }
end
end
|
markdrehmann/Hoop-It-Up
|
app/models/roster.rb
|
class Roster < ApplicationRecord
has_many :player_rosters
has_many :players, through: :player_rosters
has_many :games
has_many :courts, through: :games
end
|
markdrehmann/Hoop-It-Up
|
app/controllers/rosters_controller.rb
|
<gh_stars>1-10
class RostersController < ApplicationController
def edit
roster = Roster.find(params[:id])
if roster.players.include?(current_player)
flash[:error] = "You're already in that game, sucka"
redirect_to games_path
else
roster.players << current_player
flash[:alert] = "You're in!"
redirect_to player_path(current_player)
end
end
def leave
roster = Roster.find(params[:id])
roster.players.delete(current_player)
flash[:alert] = "You've left a game"
redirect_to player_path(current_player)
end
def show
@roster = Roster.find(params[:id])
end
end
|
markdrehmann/Hoop-It-Up
|
config/routes.rb
|
Rails.application.routes.draw do
root 'welcome#home'
resources :players, only: [:new, :create, :show]
resources :games, only: [:new, :create, :index, :show]
resources :rosters, only: [:show, :edit]
resources :courts do
resources :games, only: [:new, :index]
end
get '/auth/github/callback' => 'sessions#create'
get '/login', to: 'sessions#login'
post '/login', to: 'sessions#create'
get '/logout', to: 'sessions#logout'
get '/leave/:id', to: 'rosters#leave'
end
|
markdrehmann/Hoop-It-Up
|
db/migrate/20210213150148_change_day_to_date_time_from_games.rb
|
<reponame>markdrehmann/Hoop-It-Up
class ChangeDayToDateTimeFromGames < ActiveRecord::Migration[6.1]
def change
change_column :games, :time, :datetime
end
end
|
markdrehmann/Hoop-It-Up
|
app/controllers/games_controller.rb
|
<gh_stars>1-10
class GamesController < ApplicationController
def index
if params[:court_id]
@court = Court.find(params[:court_id])
@upcoming_games = Game.upcoming.where(court: @court)
@past_games = Game.past.where(court: @court)
else
@upcoming_games = Game.upcoming
@past_games = Game.past
end
end
def new
@game = Game.new
end
def create
@game = Game.new(game_params)
roster = Roster.create
roster.players << current_player
@game.roster = roster
if @game.save
flash[:alert] = "New Game Created!"
redirect_to player_path(current_player)
else
flash[:error] = @game.errors.full_messages.to_sentence
render :new
end
end
private
def game_params
params.require(:game).permit(:court_id, :time, :roster_id)
end
end
|
markdrehmann/Hoop-It-Up
|
db/schema.rb
|
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `bin/rails
# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2021_02_13_162019) do
create_table "courts", force: :cascade do |t|
t.string "name"
t.string "address"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "games", force: :cascade do |t|
t.datetime "time"
t.integer "court_id", null: false
t.integer "roster_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["court_id"], name: "index_games_on_court_id"
t.index ["roster_id"], name: "index_games_on_roster_id"
end
create_table "player_rosters", force: :cascade do |t|
t.integer "player_id", null: false
t.integer "roster_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["player_id"], name: "index_player_rosters_on_player_id"
t.index ["roster_id"], name: "index_player_rosters_on_roster_id"
end
create_table "players", force: :cascade do |t|
t.string "name"
t.string "email"
t.string "password_digest"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "rosters", force: :cascade do |t|
t.string "name"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
add_foreign_key "games", "courts"
add_foreign_key "games", "rosters"
add_foreign_key "player_rosters", "players"
add_foreign_key "player_rosters", "rosters"
end
|
markdrehmann/Hoop-It-Up
|
app/controllers/courts_controller.rb
|
class CourtsController < ApplicationController
def index
@courts = Court.all
# @court = Game.court_with_most_games
end
def new
@court = Court.new
end
def create
@court = Court.new(court_params)
if @court.save
flash[:alert] = "New Court Added"
redirect_to courts_path
else
flash[:error] = "oops"
render new_court_path
end
end
private
def court_params
params.require(:court).permit(:name, :address)
end
end
|
markdrehmann/Hoop-It-Up
|
app/controllers/welcome_controller.rb
|
class WelcomeController < ApplicationController
def home
if logged_in?
redirect_to player_path(current_player)
end
end
end
|
markdrehmann/Hoop-It-Up
|
app/models/player.rb
|
class Player < ApplicationRecord
has_secure_password
has_many :player_rosters
has_many :rosters, through: :player_rosters
validates :email, uniqueness: true, presence: true
validates :password, presence: true
validates :name, presence: true
def games
game_array = []
self.rosters.each do |r|
r.games.each do |g|
game_array << g
end
end
game_array
end
def upcoming_games
games.select { |g| g.time > DateTime.now }.sort_by(&:time)
end
def past_games
games.select { |g| g.time < DateTime.now }.sort_by(&:time)
end
end
|
markdrehmann/Hoop-It-Up
|
config/initializers/time_formats.rb
|
Time::DATE_FORMATS[:gametime] = '%A, %b %e at %l:%M %P'
|
markdrehmann/Hoop-It-Up
|
app/models/game.rb
|
class Game < ApplicationRecord
belongs_to :court
belongs_to :roster
validates :court_id, presence: true
validates :roster_id, presence: true
validates :time, presence: true
scope :upcoming, -> { where("time > ?", Time.current).order(:time) }
scope :past, -> { where("time < ?", Time.current).order(:time) }
def gametime
time.to_formatted_s(:gametime)
end
# def self.court_with_most_games
# group(:court).count.max_by{|k,v| v}.first
# end
end
|
markdrehmann/Hoop-It-Up
|
app/models/court.rb
|
<gh_stars>1-10
class Court < ApplicationRecord
has_many :games
has_many :rosters, through: :games
validates :name, presence: true
validates :address, presence: true
end
|
markdrehmann/Hoop-It-Up
|
app/models/player_roster.rb
|
class PlayerRoster < ApplicationRecord
belongs_to :player
belongs_to :roster
end
|
markdrehmann/Hoop-It-Up
|
app/controllers/players_controller.rb
|
<reponame>markdrehmann/Hoop-It-Up
class PlayersController < ApplicationController
def new
@player = Player.new
end
def create
@player = Player.new(player_params)
if @player.save
session[:player_id] = @player.id
flash[:alert] = "Player Created!"
redirect_to player_path(@player)
else
render :new
end
end
def show
@player = current_player
end
private
def player_params
params.require(:player).permit(:name, :email, :password)
end
end
|
markdrehmann/Hoop-It-Up
|
app/controllers/sessions_controller.rb
|
class SessionsController < ApplicationController
def login
@player = Player.new
end
def create
auth_hash = request.env["omniauth.auth"]
auth_hash ? login_with_auth(auth_hash) : login
end
def logout
session.clear
redirect_to root_path
end
private
def login_with_auth(auth_hash)
player = Player.find_by(email: auth_hash.uid)
player ||= Player.create(email: auth_hash.uid, name: auth_hash[:info][:nickname], password: <PASSWORD>)
session[:player_id] = player.id
redirect_to player_path(player)
end
def login
player = Player.find_by(email: params[:email])
if player && player.authenticate(params[:password])
session[:player_id] = player.id
flash[:alert] = "Logged in as #{player.name}!"
redirect_to player_path(player)
else
flash[:error] = "Invalid Login!"
redirect_to :login
end
end
end
|
markdrehmann/Hoop-It-Up
|
db/migrate/20210213162019_remove_day_from_games.rb
|
class RemoveDayFromGames < ActiveRecord::Migration[6.1]
def change
remove_column :games, :day, :string
end
end
|
markdrehmann/Hoop-It-Up
|
app/controllers/application_controller.rb
|
<filename>app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
helper_method :current_player
def current_player
Player.find(session[:player_id]) if logged_in?
end
helper_method :logged_in?
def logged_in?
session[:player_id].present?
end
end
|
michenriksen/nmunch
|
spec/lib/nmunch/mac_oui_lookup_spec.rb
|
require 'spec_helper'
describe Nmunch::MacOuiLookup do
context 'when given an Apple mac address' do
it 'returns Apple' do
Nmunch::MacOuiLookup.instance.lookup('58:b0:35:31:33:73').should == 'Apple'
end
end
context 'when given a Cisco mac address' do
it 'returns Cisco Systems' do
Nmunch::MacOuiLookup.instance.lookup('00:01:63:42:42:42').should == 'Cisco Systems'
end
end
context 'when given a mac address with an unknown prefix' do
it 'returns Unknown' do
Nmunch::MacOuiLookup.instance.lookup('de:ad:be:ef:de:ad').should == 'Unknown'
end
end
end
|
michenriksen/nmunch
|
spec/lib/nmunch/node_spec.rb
|
<filename>spec/lib/nmunch/node_spec.rb
require 'spec_helper'
describe Nmunch::Node do
subject { Nmunch::Node.new(ip_address: '192.168.0.1', mac_address: 'de:ad:be:ef:de:ad') }
describe '#ip_address' do
it 'returns correct IP address' do
subject.ip_address.should == '192.168.0.1'
end
end
describe '#mac_address' do
it 'returns correct MAC address' do
subject.mac_address.should == 'de:ad:be:ef:de:ad'
end
end
describe '#meta_address?' do
context 'when IP is not a meta address' do
it 'returns false' do
subject.should_not be_meta_address
end
end
context 'when IP is a meta address' do
it 'returns true' do
subject.stub(:ip_address).and_return('0.0.0.0')
subject.should be_meta_address
end
end
end
describe '.create_from_dissector' do
let(:dissector) do
dissector = stub
dissector.stub(:ip_address).and_return('192.168.0.1')
dissector.stub(:mac_address).and_return('de:ad:be:ef:de:ad')
dissector
end
subject { Nmunch::Node.create_from_dissector(dissector) }
it 'returns a node' do
subject.should be_a(Nmunch::Node)
end
it 'has correct IP address' do
subject.ip_address.should == '192.168.0.1'
end
it 'has correct MAC address' do
subject.mac_address.should == 'de:ad:be:ef:de:ad'
end
end
end
|
michenriksen/nmunch
|
nmunch.gemspec
|
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/nmunch/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["<NAME>"]
gem.email = ["<EMAIL>"]
gem.description = %q{Nmunch is a passive network discovery tool that finds live network nodes by analyzing ARP and broadcast packets.}
gem.summary = %q{OM NOM NOM NOM}
gem.homepage = "https://github.com/michenriksen/nmunch"
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "nmunch"
gem.require_paths = ["lib"]
gem.version = Nmunch::VERSION
gem.add_development_dependency('rspec')
gem.add_development_dependency('rake', '>= 0.9.2')
gem.add_dependency('methadone', '~> 1.2.3')
gem.add_dependency('pcap', '~> 0.7.7')
gem.add_dependency('paint')
end
|
michenriksen/nmunch
|
lib/nmunch/subscribers/base.rb
|
<filename>lib/nmunch/subscribers/base.rb
module Nmunch
module Subscribers
# Public: Base subscriber class
class Base
attr_reader :options
# Public: Initializer
#
# options - A hash of command line options
#
# Returns nothing
def initialize(options)
@options = options
end
end
end
end
|
michenriksen/nmunch
|
spec/lib/nmunch/report_spec.rb
|
<filename>spec/lib/nmunch/report_spec.rb
require 'spec_helper'
class TestSubscriber
def process(node); end
end
describe Nmunch::Report do
let(:node) { Nmunch::Node.new(ip_address: '192.168.0.1', mac_address: 'de:ad:be:ef:de:ad') }
let(:options) { {interface: 'en1'} }
let(:subscriber) { TestSubscriber.new }
subject { Nmunch::Report.new(options) }
describe '#publish_node' do
before(:each) do
subject.register_subscriber(subscriber)
end
it 'delegates the node to the subscriber' do
subscriber.should_receive(:process).with(node)
subject.publish_node(node)
end
context 'when node has a meta address' do
it 'does not delegate node to subscribers' do
node.stub(:ip_address).and_return('0.0.0.0')
subscriber.should_not_receive(:process)
subject.publish_node(node)
end
end
context 'when node is already discovered' do
it 'does not delegate node to subscribers' do
subject.publish_node(node)
subscriber.should_not_receive(:process)
subject.publish_node(node)
end
end
end
end
|
michenriksen/nmunch
|
spec/lib/nmunch/subscribers/stdout_spec.rb
|
<gh_stars>10-100
require 'spec_helper'
describe Nmunch::Subscribers::Stdout do
let(:node) { Nmunch::Node.new(ip_address: '192.168.0.1', mac_address: 'de:ad:be:ef:de:ad') }
let(:options) { {interface: 'en1'} }
subject { Nmunch::Subscribers::Stdout.new(options) }
describe '#process' do
it 'prints node details to STDOUT' do
output = capture_stdout { subject.process(node) }
output.should include('192.168.0.1')
output.should include('de:ad:be:ef:de:ad')
output.should include('Unknown')
end
context 'when --no-prefix-lookup option is set' do
it 'does not look up mac address prefix' do
options['no-prefix-lookup'] = true
output = capture_stdout { subject.process(node) }
output.should include('192.168.0.1')
output.should include('de:ad:be:ef:de:ad')
output.should_not include('Unknown')
end
end
end
end
|
michenriksen/nmunch
|
lib/nmunch/subscribers/stdout.rb
|
<gh_stars>10-100
module Nmunch
module Subscribers
# Public: Node subscriber to output node details to STDOUT
#
# This subscriber is default and will always be registered
class Stdout < Nmunch::Subscribers::Base
# Public: Process a new node
#
# node - An instance of Nmunch::Node
#
# Prints node information to STDOUT
#
# Returns nothing
def process(node)
output = " #{node.ip_address}\t\t#{node.mac_address}"
output << "\t#{Nmunch::MacOuiLookup.instance.lookup(node.mac_address)}" unless options.include?("no-prefix-lookup")
puts Paint[output, :green]
end
end
end
end
|
michenriksen/nmunch
|
spec/lib/nmunch/subscribers/base_spec.rb
|
require 'spec_helper'
describe Nmunch::Subscribers::Base do
let(:options) { {interface: 'en1'} }
subject { Nmunch::Subscribers::Base.new(options) }
describe '.initialize' do
it 'assigns options to instance variable' do
subject.options.should == options
end
end
end
|
michenriksen/nmunch
|
lib/nmunch/mac_oui_lookup.rb
|
require 'singleton'
module Nmunch
# Public: A utility class to look up a MAC address prefix to get the organizational name.
class MacOuiLookup
include Singleton
# Public: Get organizational name for a MAC address
#
# mac_address - A MAC address with format: hh:hh:hh:hh:hh:hh
#
# Example:
#
# Nmunch::MacOuiLookup.instance.lookup('58:b0:35:31:33:73')
# # => Apple
#
# Returns name of organization or Unknown if prefix can't be found
def lookup(mac_address)
load_prefix_file! if @prefixes.nil?
oui = mac_address[0..7].upcase.gsub(':', '').to_sym
@prefixes[oui] || 'Unknown'
end
private
# Internal: Load the file with prefixes
#
# Returns nothing
def load_prefix_file!
@prefixes = {}
File.open("#{File.dirname(__FILE__)}/../../mac-prefixes.txt", 'r').each_line do |line|
line.strip!
next if line.empty? || line.start_with?('#', '//')
oui, organization = line.split(' ', 2)
@prefixes[oui.to_sym] = organization
end
end
end
end
|
michenriksen/nmunch
|
spec/lib/nmunch/dissectors/base_spec.rb
|
<filename>spec/lib/nmunch/dissectors/base_spec.rb
require 'spec_helper'
describe Nmunch::Dissectors::Base do
let(:arp_pcap_packet) do
packet = stub(Pcap::Packet)
packet.stub(:raw_data).and_return(ARP_PACKET_DATA)
packet.stub(:ip?).and_return(false)
packet
end
let(:ip_pcap_packet) do
packet = stub(Pcap::Packet)
packet.stub(:raw_data).and_return(IP_PACKET_DATA)
packet.stub(:ip?).and_return(true)
packet
end
subject { Nmunch::Dissectors::Base.new(arp_pcap_packet) }
describe '#pcap_packet' do
it 'returns pcap packet given in initializer' do
subject.pcap_packet.should == arp_pcap_packet
end
end
describe '#raw_data' do
it 'returns an array of bytes represented in HEX' do
subject.raw_data.should == ARP_PACKET_DATA.unpack('H*').first.scan(/.{2}/)
end
end
describe '.factory' do
context 'when given ARP packet' do
it 'returns an ARP dissector' do
Nmunch::Dissectors::Base.factory(arp_pcap_packet).should be_a(Nmunch::Dissectors::Arp)
end
end
context 'when given an IP packet' do
it 'returns an IP dissector' do
Nmunch::Dissectors::Base.factory(ip_pcap_packet).should be_a(Nmunch::Dissectors::Ip)
end
end
end
end
|
michenriksen/nmunch
|
lib/nmunch/dissectors/arp.rb
|
<filename>lib/nmunch/dissectors/arp.rb
module Nmunch
module Dissectors
# Public: Address Resolution Protocol dissector
#
# Extracts IP and MAC address from an ARP packet
#
# See http://en.wikipedia.org/wiki/Address_Resolution_Protocol for protocol details
class Arp < Nmunch::Dissectors::Base
# Public: Get sender IP address from ARP packet
#
# Returns IP address
def ip_address
@ip_address ||= IPAddr.new(raw_data[28..31].join.hex, Socket::AF_INET).to_s
end
# Public: Get sender MAC address from ARP packet
#
# Returns MAC address
def mac_address
@mac_address ||= raw_data[22..27].join(':')
end
end
end
end
|
michenriksen/nmunch
|
spec/lib/nmunch/dissectors/ip_spec.rb
|
require 'spec_helper'
describe Nmunch::Dissectors::Ip do
let(:ip_pcap_packet) do
packet = stub(Pcap::Packet)
packet.stub(:raw_data).and_return(IP_PACKET_DATA)
packet.stub(:ip?).and_return(true)
packet
end
subject { Nmunch::Dissectors::Ip.new(ip_pcap_packet) }
describe '#ip_address' do
it 'returns correct IP address' do
ip_pcap_packet.should_receive(:ip_src).and_return('192.168.0.125')
subject.ip_address.should == '192.168.0.125'
end
end
describe '#mac_address' do
it 'returns correct MAC address' do
subject.mac_address.should == 'de:ad:be:ef:de:ad'
end
end
end
|
michenriksen/nmunch
|
spec/lib/nmunch_spec.rb
|
require 'spec_helper'
describe Nmunch do
describe 'PCAP filter expression' do
it 'allows only ARP and broadcast packets' do
Nmunch::CAPTURE_FILTER.should == 'arp or broadcast'
end
end
end
|
michenriksen/nmunch
|
lib/nmunch.rb
|
require "nmunch/version"
require "nmunch/dissectors/base"
require "nmunch/dissectors/ip"
require "nmunch/dissectors/arp"
require "nmunch/subscribers/base"
require "nmunch/subscribers/stdout"
require "nmunch/node"
require "nmunch/report"
require "nmunch/mac_oui_lookup"
# Public: Main Nmunch module
#
# Acts as a facade in front of the ruby-pcap gem and abstracts away the packet analysis.
module Nmunch
# Internal: PCAP filter expression to only get ARP and broadcast packets
CAPTURE_FILTER = 'arp or broadcast'
# Public: Start munching on packets on interface or from PCAP file
#
# options - Hash of command line options
#
# Yields an Nmunch::Node with IP and MAC address information
def self.munch!(options)
create_capture_object(options).each_packet do |packet|
dissector = Nmunch::Dissectors::Base.factory(packet)
yield Nmunch::Node.create_from_dissector(dissector)
end
end
# Internal: Get the awesome Nmunch ASCII banner
#
# Returns ASCII banner
def self.banner
banner = <<EOB
88b 88 8b d8 88 88 88b 88 dP""b8 88 88
88Yb88 88b d88 88 88 88Yb88 dP `" 88 88
88 Y88 88YbdP88 Y8 8P 88 Y88 Yb 888888
88 Y8 88 YY 88 `YbodP' 88 Y8 YboodP 88 88
EOB
end
private
# Internal: Create a capture object from options
#
# options - Hash of command line options
#
# Returns a Pcap::Capture object on interface or a PCAP file
def self.create_capture_object(options)
if options[:interface]
capture = Pcap::Capture.open_live(options[:interface])
else
capture = Pcap::Capture.open_offline(options[:file])
end
capture.setfilter(CAPTURE_FILTER)
capture
end
end
|
michenriksen/nmunch
|
lib/nmunch/report.rb
|
<gh_stars>10-100
module Nmunch
# Public: Nmunch report class
#
# Keeps track of discovered nodes and publishes nodes to registered subscribers
class Report
attr_reader :options
# Public: Initialize a new report
#
# options - Hash of command line options
def initialize(options)
@options = options
@subscribers = []
@discovered_nodes = []
end
# Public: Register a new subscriber
#
# subscriber - An object that responds to #process(node)
#
# All subscribers will be notified of new nodes and it is up to each subscriber
# to do something meaningful with the node.
#
# Returns nothing
def register_subscriber(subscriber)
@subscribers << subscriber
end
# Public: Publish a new node to all registered subscribers
#
# node - An instance of Nmunch::Node
#
# Already discovered nodes or nodes with meta addresses (e.g. DHCP requests)
# will be ignored.
#
# Returns nothing
def publish_node(node)
if !node.meta_address? && !@discovered_nodes.include?(node)
@subscribers.each { |s| s.process(node) }
@discovered_nodes << node
end
end
# Public: Get a summary
#
# Returns a simple summary telling how many live nodes were discovered
# TODO: Make the summary more detailed
def summary
" Discovered #{@discovered_nodes.count} live node(s)"
end
end
end
|
michenriksen/nmunch
|
lib/nmunch/dissectors/base.rb
|
<filename>lib/nmunch/dissectors/base.rb
module Nmunch
module Dissectors
# Public: Base dissector class
class Base
attr_reader :pcap_packet, :raw_data
# Public: Initializer
#
# pcap_packet - An instance of Pcap::Packet
#
# Stores the packet and extracts to raw packet data in a way that makes
# it easy to dissect
#
# Returns nothing
def initialize(pcap_packet)
@pcap_packet = pcap_packet
extract_raw_packet_data
end
# Public: Dissector factory
#
# pcap_packet - An instance of Pcap::Packet
#
# Returns an instance of a dissector
def self.factory(pcap_packet)
if pcap_packet.ip?
Nmunch::Dissectors::Ip.new(pcap_packet)
else
Nmunch::Dissectors::Arp.new(pcap_packet)
end
end
private
# Internal: Extract raw packet data and store it in @raw_data
#
# Unpacks data to HEX and splits it into an array of bytes
#
# Returns nothing
def extract_raw_packet_data
@raw_data = pcap_packet.raw_data.unpack('H*').first.scan(/.{2}/)
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.