Listing all OU's in LDAP with Rails - ruby-on-rails

I am trying to list all Organizational Units (OU) from my LDAP directory. I am using the "devise_ldap_authenticatable" gem to authenticate my users. The LDAP sign in works fine. I am trying to get all the OU's now.
I'm new to LDAP, please let me know if my search query is wrong here.
ldap = Net::LDAP.new
ldap.host = "192.168.0.100"
ldap.port = 389
ldap.auth "cn=admin,dc=company,dc=com", "password"
treebase = "dc=company,dc=com"
filter = Net::LDAP::Filter.eq( "objectClass=organizationalUnit","company.com" )
attrs = ["*"]
ldap.search( :base => treebase, :filter => filter, :attributes => attrs, :return_result => false ) do |entry|
puts entry
end
When I ran this, I got nothing returned. I have two OU's in my LDAP, DevOps and Development. There are 5 test users in each.

I'm not sure if this is the right way to do it, but it got me what I wanted and I'm happy with that.
I just removed the filter and retrieved the ou from the entry directly.
ldap.search( :base => treebase, :attributes => attrs, :return_result => false ) do |entry|
puts entry["ou"]
end

Related

how do i get message list with Gmail Api?

i want to access list of messages
Object:
2.0.0-p481 :008 > g.gmail_api.users.messages.list
=> # < Google::APIClient::Method:0x41c948c ID:gmail.users.messages.list >
i'm new in this API and unable to get how do i use Gmail API.
Thanks
# Google
gem "omniauth-google-oauth2"
gem "google-api-client"
in my model
def query_google( email )
self.refresh_token_from_google if self.expires_at.to_i < Time.now.to_i
#google_api_client = Google::APIClient.new(
application_name: 'Joggle',
application_version: '1.0.0'
)
#google_api_client.authorization.access_token = self.access_key
#gmail = #google_api_client.discovered_api('gmail', "v1")
# https://developers.google.com/gmail/api/v1/reference/users/messages/list
# Now that we instantiated gmail, we can take the category (messages) and the method
# You can also add parameters if you wish to do so:
# #calendar_events = google_api_client.execute(
# :api_method => #calendar.events.list,
# :parameters => {
# "calendarId" => current_user.email,
# 'timeMin' => date.to_s,
# 'timeMax' => max_date.to_s
# # 'items' => [{'id' => current_user.email}]
# },
# :headers => {'Content-Type' => 'application/json'}
# )
#emails = #google_api_client.execute(
api_method: #gmail.users.messages.list,
parameters: {
userId: "me",
# searching messages based on number of queries:
# https://developers.google.com/gmail/api/guides/filtering
q: "from:" + email.to_s
},
headers: {'Content-Type' => 'application/json'}
)
count = #emails.data.messages.count
Rails.logger.error count
{count: count, last_emails: get_three_emails} if count > 0
end
for reference : https://github.com/google/google-api-ruby-client/issues/135
Not a ruby expert but that looks like a method, can you call () it? I imagine you've gone through steps to setup authentication, etc? the messages.list() function should be able to be called without any parameters generally (well, you may need to specify a userId, which you can just use "me" for to get the authenticated user).

Using Ruby Webrick HTTPAuth with LDAP

The app I am writing has the ability to have a login popup appear and it authenticates against a hard coded username/password constant pair. I would like to authenticate against our central LDAP server. the we dont have a base however we do have a bind_dn string of "cn=USERFOO,ou=it,o=corporate". The variables user/pass are passed in through the basic login box.
I am trying to do this through ActiveLdap however I dont mind using any other library as long as I can validate the credentials through a single sign on against our LDAP server using the HTTPAuth since is written completely in Webrick Ruby. Below is a sample of the function I am calling.
Does anyone have any idea how to do this?
Thanks in advance.
def authenticate_ldap(req,res)
authlabel = "LDAP Authentication"
HTTPAuth.basic_auth(req, res, authlabel) { |user, pass|
ActiveLdap::Base.setup_connection(
:host => 'ldap.internalserver.com',
:port => 389,
:bind_dn => "cn=#{user},ou=it,o=corporate",
:password_block => Proc.new { pass },
)
}
return
end
I figured out a solution. The person who manages our LDAP server provided the incorrect ldap connection string, but even with that it still didn't work.
The solution I discovered that did indeed make a connection with very basic validation is something to this effect for anyone else interested in a very simple ldap authentication popup in pure Ruby.
def authenticate(req,res)
authlabel = 'LDAP Authentication'
HTTPAuth.basic_auth(req, res, authlabel) { |user, pass|
if pass.to_s != ''
ldap = Net::LDAP.new
ldap.host = "ldap.serverfoo.com"
ldap.port = 389
result = ldap.bind_as(
:base => "t=basetreefoo",
:filter => "uid=#{user}",
:password => pass
)
if result
ldap = Net::LDAP.new :host => "ldap.serverfoo.com",
:port => "389",
:auth => {
:method => :simple,
:username => "",
:password => ""
}
group_name = Net::LDAP::Filter.eq("cn", "#{user}")
group_type = Net::LDAP::Filter.eq("groupmembership", "cn=infra,ou=IT,o=Corporate")
filter = group_name & group_type
treebase = "t=basetreefoo"
ldap.search(:base => treebase, :filter => filter) do |entry|
if entry.dn.to_s != ""
puts 'success'
return
end
end
end
end
puts 'fail'
}
end

How to pull Google Analytics stats?

Is Google API Ruby client the best option?
I have a site example.com with users and I want them to see their google analytics stats on example.com, how can I do it ?
I can see the example but I'm not able to figure out how to begin.
I also use the google-api-ruby-client gem and set it up about the same way that is outlined in the link you provided (https://gist.github.com/joost/5344705).
Just follow the steps outlined in the link to set up a Google Analytics client:
# you need to set this according to your situation/needs
SERVICE_ACCOUNT_EMAIL_ADDRESS = '...' # looks like 12345#developer.gserviceaccount.com
PATH_TO_KEY_FILE = '...' # the path to the downloaded .p12 key file
PROFILE = '...' # your GA profile id, looks like 'ga:12345'
require 'google/api_client'
# set up a client instance
client = Google::APIClient.new
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/analytics.readonly',
:issuer => SERVICE_ACCOUNT_EMAIL_ADDRESS,
:signing_key => Google::APIClient::PKCS12.load_key(PATH_TO_KEY_FILE, 'notasecret')
).tap { |auth| auth.fetch_access_token! }
api_method = client.discovered_api('analytics','v3').data.ga.get
# make queries
result = client.execute(:api_method => api_method, :parameters => {
'ids' => PROFILE,
'start-date' => Date.new(1970,1,1).to_s,
'end-date' => Date.today.to_s,
'dimensions' => 'ga:pagePath',
'metrics' => 'ga:pageviews',
'filters' => 'ga:pagePath==/url/to/user'
})
puts result.data.rows.inspect
To display statistics for a user's page in your app, you have to adjust the metrics and filters parameters when making the query. The query above for example will return a result object containing all pageviews for the page with url example.com/url/to/user.
Caveat: this answer was written a long time ago and Google released a new, incompatible version of the gem. Please consult https://github.com/google/google-api-ruby-client/blob/master/MIGRATING.md

HowTo Write tests for Devise & Omniauth in my Rails 3 app?

I have a Rails 3 app with Omniauth and Devise. I haven't been able to find a solid tutorial showing how I should write specs for testing the functionality.
What I want to achieve is to ensure that the Sign Up and Sign In forms are working... meaning users can create accounts. I also want to be sure that the Omniauth FB Connect works as well at all times.
What/how can I write test for these scenarios above?
Thanks
The tests were very useful to test the pretty complex method I have to process authentication from Yahoo, Facebook, Google and AOL. Especially the edge cases.
This should get you started, it is the first of my 10+ scenarios.
.feature file
Feature: Signinin with third party service: Google, Aol, Facebook and Yahoo
In order to use the site
As a User
I want to sign in using my Facebook or Gmail accounts
Before do
OmniAuth.config.test_mode = true
end
After do
OmniAuth.config.test_mode = false
end
Scenario Outline: Sign with valid names and emails
Given that I have a valid "<provider>" account with email "<email>" and name "<name>"
And that I am not signed in
And I go to the sign in page
When I follow image link "<provider>"
Then I should see "You signed in using your <provider> account ("
And I should see "Welcome to Death Star"
Examples: valid name and email variations
| provider | email | name |
| Google | lukeskywaler#gmail.com | luke skywlaker |
| Facebook | darth.vader#aol.com | darth vader |
my_step.rb helper:
Given /^that I have a valid "([^"]*)" account with email "([^"]*)" and name "([^"]*)"$/ do |provider, email, name|
OmniAuth.config.test_mode = true
if provider.downcase == "yahoo" or provider.downcase == "google" or provider.downcase == "aol"
# the symbol passed to mock_auth is the same as the name of the provider set up in the initializer
OmniAuth.config.mock_auth[:open_id] =
{
'provider' => "#{provider}",
'uid' => "#{provider}.com",
'user_info' => { 'email' => "#{email}", 'name' => "#{name}"}
}
else
# the symbol passed to mock_auth is the same as the name of the provider set up in the initializer
OmniAuth.config.mock_auth[:facebook] = {
'provider' => 'facebook',
'uid' => "531564247",
'credentials' => {
'token'=> "18915faketoken22|2.NKt21XnznTNEDTTERDGYXI2UUw__.3600.1302234329200-531564247|Mi0DhWREl6g-T9bMZnL82u7s4MI"
},
'user_info' => {
'nickname' => "profile.php?id=53232564247",
'email' => "#{email}",
'first_name' => "Luke",
'last_name' => "Skywalker",
'name' => "Luke Skywalker",
'image' => "http://graph.facebook.com/5asd54247/picture?type=square",
'urls' => {
'facebook' => "http://www.facebook.com/profile.php?id=5asd54247",
'website' => ""
}
},
'extra' => {
'user_hash' => {
'id' => "5asd54247",
'name' => "#{name}",
'first_name' => "#{name.split(' ')[0]}",
'last_name' => "#{name.split(' ')[1]}",
'link' => "http://www.facebook.com/profile.php?id=5asd54247",
'birthday' => "12/7/1932",
'hometown' => {
'id' => "104048449631599",
'name' => "Menlo Park, California"
},
'location' => {
'id' => "104048449631599",
'name' => "Menlo Park, California"
},
'gender' => "male",
'email' => "#{email}",
'timezone' => "-7",
'locale' => "en_US",
'verified' => true
}
}
}
end
end
Hope this help.

Rails LDAP login using net/ldap

I am trying to get LDAP authentication to work under Rails.
I have chosen net/ldap since it's a native Ruby LDAP library.
I have tried all possible stuff, specially examples from http://net-ldap.rubyforge.org/classes/Net/LDAP.html but still unable to get it work.
Any ideas?
The best solution I managed to reach is a Model with the following:
require 'net/ldap'
class User < ActiveRecord::Base
def after_initialize
#config = YAML.load(ERB.new(File.read("#{Rails.root}/config/ldap.yml")).result)[Rails.env]
end
def ldap_auth(user, pass)
ldap = initialize_ldap_con
result = ldap.bind_as(
:base => #config['base_dn'],
:filter => "(#{#config['attributes']['id']}=#{user})",
:password => pass
)
if result
# fetch user DN
get_user_dn user
sync_ldap_with_db user
end
nil
end
private
def initialize_ldap_con
options = { :host => #config['host'],
:port => #config['port'],
:encryption => (#config['tls'] ? :simple_tls : nil),
:auth => {
:method => :simple,
:username => #config['ldap_user'],
:password => #config['ldap_password']
}
}
Net::LDAP.new options
end
def get_user_dn(user)
ldap = initialize_ldap_con
login_filter = Net::LDAP::Filter.eq #config['attributes']['id'], "#{user}"
object_filter = Net::LDAP::Filter.eq "objectClass", "*"
ldap.search :base => #config['base_dn'],
:filter => object_filter & login_filter,
:attributes => ['dn', #config['attributes']['first_name'], #config['attributes']['last_name'], #config['attributes']['mail']] do |entry|
logger.debug "DN: #{entry.dn}"
entry.each do |attr, values|
values.each do |value|
logger.debug "#{attr} = #{value}"
end
end
end
end
end
I work on a Devise plugin for Rails 3 that uses LDAP for authentication, you can look at the source to get some ideas, it currently uses net-ldap 0.1.1:
http://github.com/cschiewek/devise_ldap_authenticatable
The actual connecting and authenticating to the LDAP sever is done at:
http://github.com/cschiewek/devise_ldap_authenticatable/blob/master/lib/devise_ldap_authenticatable/ldap_adapter.rb
Lastly, you can look at the sample LDAP server config and Rails 3 app I use to run the tests against:
App: http://github.com/cschiewek/devise_ldap_authenticatable/tree/master/test/rails_app/
Server: http://github.com/cschiewek/devise_ldap_authenticatable/tree/master/test/ldap/

Resources