I'm migration a Rails 2.3.8 app to Rails 3.0.20 so I went from using "gem 'geokit' 1.6.0" to "gem "geokit-rails".
I get:
/Users/alextoul/.rvm/gems/ruby-1.9.3-p484#rails3/gems/geokit-rails-2.0.1/lib/geokit-rails/railtie.rb:33:in `block (2 levels) in <class:Railtie>': undefined method `proxy_addr=' for Geokit::Geocoders:Module (NoMethodError)
My geokit_config.rb is:
MyApp::Application.configure do
# These defaults are used in Geokit::Mappable.distance_to and in acts_as_mappable
config.geokit.default_units = :miles
config.geokit.default_formula = :sphere
# This is the timeout value in seconds to be used for calls to the geocoder web
# services. For no timeout at all, comment out the setting. The timeout unit
# is in seconds.
config.geokit.geocoders.request_timeout = 3
# These settings are used if web service calls must be routed through a proxy.
# These setting can be nil if not needed, otherwise, addr and port must be
# filled in at a minimum. If the proxy requires authentication, the username
# and password can be provided as well.
config.geokit.geocoders.proxy_addr = nil
config.geokit.geocoders.proxy_port = nil
config.geokit.geocoders.proxy_user = nil
config.geokit.geocoders.proxy_pass = nil
# This is your yahoo application key for the Yahoo Geocoder.
# See http://developer.yahoo.com/faq/index.html#appid
# and http://developer.yahoo.com/maps/rest/V1/geocode.html
config.geokit.geocoders.yahoo = 'secret'
# This is your Google Maps geocoder key.
# See http://www.google.com/apis/maps/signup.html
# and http://www.google.com/apis/maps/documentation/#Geocoding_Examples
config.geokit.geocoders.google = 'secret'
# You can also set multiple API KEYS for different domains that may be directed to this same application.
# The domain from which the current user is being directed will automatically be updated for Geokit via
# the GeocoderControl class, which gets it's begin filter mixed into the ActionController.
# You define these keys with a Hash as follows:
#config.geokit.geocoders.google = { 'rubyonrails.org' => 'RUBY_ON_RAILS_API_KEY', 'ruby-docs.org' => 'RUBY_DOCS_API_KEY' }
# This is your username and password for geocoder.us.
# To use the free service, the value can be set to nil or false. For
# usage tied to an account, the value should be set to username:password.
# See http://geocoder.us
# and http://geocoder.us/user/signup
config.geokit.geocoders.geocoder_us = false
# This is your authorization key for geocoder.ca.
# To use the free service, the value can be set to nil or false. For
# usage tied to an account, set the value to the key obtained from
# Geocoder.ca.
# See http://geocoder.ca
# and http://geocoder.ca/?register=1
config.geokit.geocoders.geocoder_ca = false
# require "external_geocoder.rb"
# Please see the section "writing your own geocoders" for more information.
# config.geokit.geocoders.external_key = 'REPLACE_WITH_YOUR_API_KEY'
# This is the order in which the geocoders are called in a failover scenario
# If you only want to use a single geocoder, put a single symbol in the array.
# Valid symbols are :google, :yahoo, :us, and :ca.
# Be aware that there are Terms of Use restrictions on how you can use the
# various geocoders. Make sure you read up on relevant Terms of Use for each
# geocoder you are going to use.
config.geokit.geocoders.provider_order = [:google,:us]
# The IP provider order. Valid symbols are :ip,:geo_plugin.
# As before, make sure you read up on relevant Terms of Use for each.
# config.geokit.geocoders.ip_provider_order = [:external,:geo_plugin,:ip]
end
When I delete the geokit_config.rb file, the server starts but I obviously have:
ArgumentError (Unknown key(s): origin, within):
Any idea?
proxy_addr/port/user and pass have been replaced with just proxy
which is a string like:
https://user:password#host:port
So if you had:
config.geokit.geocoders.proxy_addr = nil
config.geokit.geocoders.proxy_port = nil
config.geokit.geocoders.proxy_user = nil
config.geokit.geocoders.proxy_pass = nil
It's now:
config.geokit.geocoders.proxy = nil
PS. You don't need to switch from geokit to geokit-rails, infact they are different. geokit-rails is geokit PLUS some things for rails, like acts_as_mappable.
If you didn't need geokit-rails before the upgrade, you shouldn't need it after. It just adds extra items that are rails specific if you want them.
Related
I implemented steps 1, 2 and 3 from the "Changing the index" section of this page https://flask-appbuilder.readthedocs.io/en/latest/customizing.html?highlight=theme.
I get the following error:
\app__init__.py", line 4, in
from app.index import MyIndexView
ImportError: cannot import name 'MyIndexView'
I have made these changes to a barebone Flask-AppBuilder app.
The code is exactly as is shown on the site.
I expect the example to work as described. But I receive the message I posted above when I run it.
Your index.py should look like this(base version).
# Import flask functions for redirecting and getting user status
from flask import g, url_for, redirect
# Import IndexView class to overwrite files/redirects and expose to expose custom index view
from flask_appbuilder import IndexView, expose
# File to display custom made different views based off if user is signed
class MyIndexView(IndexView):
# Checking user and redirecting for user when user goes to index view
#expose('/')
def index(self):
# Get user status
user = g.user
# Check user
if user.is_anonymous:
# user is not authenticated and gets redirected to New user page
return redirect(url_for('HomeView.new'))
else:
# user is authenticated and has an account redirect to General page
return redirect(url_for('HomeView.general'))
Then in your views.py create a simle view like this
# Views for any home paths
class HomeView(BaseView):
# add route base for views as /home
route_base = "/home"
# Route for new or logged out users
#expose('/new')
def new(self):
return self.render_template('new_user.py')
# Route for signed in users or users who want to just view data
#expose('/general')
def general(self):
return self.render_template('my_index.py')
Also, make sure to add it to your appbuilder object in your init.py
appbuilder = AppBuilder(app, db.session, indexview=MyIndexView)
I'm using alfresco 4.2.c and i'm wondering about LDAP-AD configuration ,
Is it possible to copy the configuration file "ldap-ad-authentication.properties" in the global properties file "alfresco-global.properties" without additional parameters ?
This LDAP-AD conf work perfectly with alfresco community 5.2.0
alfresco-global.properties:
# LDAP
authentication.chain=alfrescoNtlm1:alfrescoNtlm,myldap:ldap-ad
synchronization.sinchronyzeChangesOnly=false
synchronization.syncWhenMissingPeopleLogIn=true
synchronization.syncOnStartup=true
synchronization.import.cron=0 0 18 * * ?
dir.root=C:/alfresco/alf_data2
db.username=alfresco2
db.password=alfresco2
db.name=alfresco2
db.host=localhost
db.port=5432
db.pool.max=40
db.driver=org.postgresql.Driver
db.url=jdbc:postgresql://localhost:5432/alfresco2
ftp.enabled=true
ftp.port=1121
ftp.ipv6.enabled=false
# This flag enables use of this LDAP subsystem for authentication. It may be
# that this subsytem should only be used for synchronization, in which case
# this flag should be set to false.
ldap.authentication.active=true
#
# This properties file brings together the common options for LDAP authentication rather than editing the bean definitions
#
ldap.authentication.allowGuestLogin=false
# How to map the user id entered by the user to taht passed through to LDAP
# In Active Directory, this can either be the user principal name (UPN) or DN.
# UPNs are in the form <sAMAccountName>#domain and are held in the userPrincipalName attribute of a user
ldap.authentication.userNameFormat=%s#tidji.com
# The LDAP context factory to use
ldap.authentication.java.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory
# The URL to connect to the LDAP server
ldap.authentication.java.naming.provider.url=ldap://192.168.2.99:389
# The authentication mechanism to use for password validation
ldap.authentication.java.naming.security.authentication=simple
# Escape commas entered by the user at bind time
# Useful when using simple authentication and the CN is part of the DN and contains commas
ldap.authentication.escapeCommasInBind=false
# Escape commas entered by the user when setting the authenticated user
# Useful when using simple authentication and the CN is part of the DN and contains commas, and the escaped \, is
# pulled in as part of an LDAP sync
# If this option is set to true it will break the default home folder provider as space names can not contain \
ldap.authentication.escapeCommasInUid=false
# Comma separated list of user names who should be considered administrators by default
ldap.authentication.defaultAdministratorUserNames=alfresco
# This flag enables use of this LDAP subsystem for user and group
# synchronization. It may be that this subsytem should only be used for
# authentication, in which case this flag should be set to false.
ldap.synchronization.active=true
# The authentication mechanism to use for synchronization * :) *
ldap.synchronization.java.naming.security.authentication=simple
# The default principal to bind with (only used for LDAP sync). This should be a UPN or DN * :( *
ldap.synchronization.java.naming.security.principal=alfresco#tidji.com
# The password for the default principal (only used for LDAP sync) * :) *
ldap.synchronization.java.naming.security.credentials=*******
# If positive, this property indicates that RFC 2696 paged results should be
# used to split query results into batches of the specified size. This
# overcomes any size limits imposed by the LDAP server. * :( *
ldap.synchronization.queryBatchSize=1000
# If positive, this property indicates that range retrieval should be used to fetch
# multi-valued attributes (such as member) in batches of the specified size.
# Overcomes any size limits imposed by Active Directory. * :( *
ldap.synchronization.attributeBatchSize=1000
# The query to select all objects that represent the groups to import.
ldap.synchronization.groupQuery=(objectclass\=group)
# The query to select objects that represent the groups to import that have changed since a certain time.
ldap.synchronization.groupDifferentialQuery=(&(objectclass\=group)(!(whenChanged<\={0})))
# The query to select all objects that represent the users to import.
ldap.synchronization.personQuery=(&(objectclass\=user)(userAccountControl\:1.2.840.113556.1.4.803\:\=512))
# The query to select objects that represent the users to import that have changed since a certain time.
ldap.synchronization.personDifferentialQuery=(&(objectclass\=user)(userAccountControl\:1.2.840.113556.1.4.803\:\=512)(!(whenChanged<\={0})))
# The group search base restricts the LDAP group query to a sub section of tree on the LDAP server.
ldap.synchronization.groupSearchBase=ou\=User,dc\=tidji,dc\=com
# The user search base restricts the LDAP user query to a sub section of tree on the LDAP server.
ldap.synchronization.userSearchBase=ou\=User,dc\=tidji,dc\=com
# The name of the operational attribute recording the last update time for a group or user.
ldap.synchronization.modifyTimestampAttributeName=whenChanged
# The timestamp format. Unfortunately, this varies between directory servers. * :( *
ldap.synchronization.timestampFormat=yyyyMMddHHmmss'.0Z'
# The attribute name on people objects found in LDAP to use as the uid in Alfresco
ldap.synchronization.userIdAttributeName=sAMAccountName
# The attribute on person objects in LDAP to map to the first name property in Alfresco
ldap.synchronization.userFirstNameAttributeName=givenName
# The attribute on person objects in LDAP to map to the last name property in Alfresco
ldap.synchronization.userLastNameAttributeName=sn
# The attribute on person objects in LDAP to map to the email property in Alfresco
ldap.synchronization.userEmailAttributeName=mail
# The attribute on person objects in LDAP to map to the organizational id property in Alfresco
ldap.synchronization.userOrganizationalIdAttributeName=company
# The default home folder provider to use for people created via LDAP import
ldap.synchronization.defaultHomeFolderProvider=userHomesHomeFolderProvider
# The attribute on LDAP group objects to map to the authority name property in Alfresco
ldap.synchronization.groupIdAttributeName=cn
# The attribute on LDAP group objects to map to the authority display name property in Alfresco
ldap.synchronization.groupDisplayNameAttributeName=displayName
# The group type in LDAP
#ldap.synchronization.groupType=group
# The person type in LDAP
#ldap.synchronization.personType=user
# The attribute in LDAP on group objects that defines the DN for its members
ldap.synchronization.groupMemberAttributeName=member
# If true progress estimation is enabled. When enabled, the user query has to be run twice in order to count entries.
ldap.synchronization.enableProgressEstimation=true
# Requests timeout, in miliseconds, use 0 for none (default)
ldap.authentication.java.naming.read.timeout=0
I'm setting up a (headless) web server that lets people build their own custom time-lapse movies.
Several people want to upload the time-lapse videos they make to YouTube.
Rather than download the video to that person's laptop,
and the that person manually uploads it to YouTube,
is there a way I can write some software on my web server to take that video file on my web server and upload it directly to that user's account on YouTube?
I've been told that asking my users for their YouTube handle and password is the Wrong Thing To Do, and I should be using the YouTube V3 API with Oauth.
I tried the techniques listed at
" I want to upload a video from my web page to youtube by using javascript youtube API ",
which seems to "work", but every time I had to download the video to that person's laptop and then uploading from the laptop to YouTube. Is there a way to tweak that system to upload directly from my server to YouTube?
I found some python code that (after I set up my client_secrets.json) lets me upload videos directly from my server directly to someone's YouTube account after that person did the Oauth authentication.
But the first time some new person tries to upload a video to some new YouTube account that my server has never dealt with before, it either
(a) pops open a web browser on my server, and then if I VNC to the server and type in a YouTube handle and password into that web browser, it gets authenticated -- but I'd rather not do that for every user.
(b) with the "--noauth_local_webserver" option, spits out a URL on the command line and waits. Then if I manually copy that URL and paste it into a web browser, log in to YouTube, copy-and-paste the token back into this application that is still waiting for input on the command line, that person gets authenticated. But I'd rather not do that for every user. I guess that would be OK if I could capture that URL in my cgi-bin script and stick it in a web page, and then later somehow get the authentication response and cram it back into this program, but how? I don't even see that print statement or the raw_input statement in this code.
#!/usr/bin/python
# https://developers.google.com/youtube/v3/code_samples/python#upload_a_video
# which is identical to the code sample at
# https://developers.google.com/youtube/v3/docs/videos/insert
import httplib
import httplib2
import os
import random
import sys
import time
from apiclient.discovery import build
from apiclient.errors import HttpError
from apiclient.http import MediaFileUpload
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow
# Explicitly tell the underlying HTTP transport library not to retry, since
# we are handling retry logic ourselves.
httplib2.RETRIES = 1
# Maximum number of times to retry before giving up.
MAX_RETRIES = 10
# Always retry when these exceptions are raised.
RETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, IOError, httplib.NotConnected,
httplib.IncompleteRead, httplib.ImproperConnectionState,
httplib.CannotSendRequest, httplib.CannotSendHeader,
httplib.ResponseNotReady, httplib.BadStatusLine)
# Always retry when an apiclient.errors.HttpError with one of these status
# codes is raised.
RETRIABLE_STATUS_CODES = [500, 502, 503, 504]
# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains
# the OAuth 2.0 information for this application, including its client_id and
# client_secret. You can acquire an OAuth 2.0 client ID and client secret from
# the Google Developers Console at
# https://console.developers.google.com/.
# Please ensure that you have enabled the YouTube Data API for your project.
# For more information about using OAuth2 to access the YouTube Data API, see:
# https://developers.google.com/youtube/v3/guides/authentication
# For more information about the client_secrets.json file format, see:
# https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
CLIENT_SECRETS_FILE = "client_secrets.json"
# This OAuth 2.0 access scope allows an application to upload files to the
# authenticated user's YouTube channel, but doesn't allow other types of access.
YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube.upload"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
# This variable defines a message to display if the CLIENT_SECRETS_FILE is
# missing.
MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0
To make this sample run you will need to populate the client_secrets.json file
found at:
%s
with information from the Developers Console
https://console.developers.google.com/
For more information about the client_secrets.json file format, please visit:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
CLIENT_SECRETS_FILE))
VALID_PRIVACY_STATUSES = ("public", "private", "unlisted")
def get_authenticated_service(args):
flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
scope=YOUTUBE_UPLOAD_SCOPE,
message=MISSING_CLIENT_SECRETS_MESSAGE)
storage = Storage("%s-oauth2.json" % sys.argv[0])
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = run_flow(flow, storage, args)
return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
http=credentials.authorize(httplib2.Http()))
def initialize_upload(youtube, options):
tags = None
if options.keywords:
tags = options.keywords.split(",")
body=dict(
snippet=dict(
title=options.title,
description=options.description,
tags=tags,
categoryId=options.category
),
status=dict(
privacyStatus=options.privacyStatus
)
)
# Call the API's videos.insert method to create and upload the video.
insert_request = youtube.videos().insert(
part=",".join(body.keys()),
body=body,
# The chunksize parameter specifies the size of each chunk of data, in
# bytes, that will be uploaded at a time. Set a higher value for
# reliable connections as fewer chunks lead to faster uploads. Set a lower
# value for better recovery on less reliable connections.
#
# Setting "chunksize" equal to -1 in the code below means that the entire
# file will be uploaded in a single HTTP request. (If the upload fails,
# it will still be retried where it left off.) This is usually a best
# practice, but if you're using Python older than 2.6 or if you're
# running on App Engine, you should set the chunksize to something like
# 1024 * 1024 (1 megabyte).
media_body=MediaFileUpload(options.file, chunksize=-1, resumable=True)
)
resumable_upload(insert_request)
# This method implements an exponential backoff strategy to resume a
# failed upload.
def resumable_upload(insert_request):
response = None
error = None
retry = 0
while response is None:
try:
print "Uploading file..."
status, response = insert_request.next_chunk()
if 'id' in response:
print "Video id '%s' was successfully uploaded." % response['id']
else:
exit("The upload failed with an unexpected response: %s" % response)
except HttpError, e:
if e.resp.status in RETRIABLE_STATUS_CODES:
error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status,
e.content)
else:
raise
except RETRIABLE_EXCEPTIONS, e:
error = "A retriable error occurred: %s" % e
if error is not None:
print error
retry += 1
if retry > MAX_RETRIES:
exit("No longer attempting to retry.")
max_sleep = 2 ** retry
sleep_seconds = random.random() * max_sleep
print "Sleeping %f seconds and then retrying..." % sleep_seconds
time.sleep(sleep_seconds)
if __name__ == '__main__':
argparser.add_argument("--file", required=True, help="Video file to upload")
argparser.add_argument("--title", help="Video title", default="Test Title")
argparser.add_argument("--description", help="Video description",
default="Test Description")
argparser.add_argument("--category", default="22",
help="Numeric video category. " +
"See https://developers.google.com/youtube/v3/docs/videoCategories/list")
argparser.add_argument("--keywords", help="Video keywords, comma separated",
default="")
argparser.add_argument("--privacyStatus", choices=VALID_PRIVACY_STATUSES,
default=VALID_PRIVACY_STATUSES[0], help="Video privacy status.")
args = argparser.parse_args()
if not os.path.exists(args.file):
exit("Please specify a valid file using the --file= parameter.")
youtube = get_authenticated_service(args)
try:
initialize_upload(youtube, args)
except HttpError, e:
print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
use "client_secrets.json"
configure credentials to generate it
https://console.developers.google.com/apis/credentials
{
"web":
{
"client_id":"xxxxxxxxxxxxxx",
"project_id":"xxxxxxxxxxxxxx",
"auth_uri":"https://accounts.google.com/o/oauth2/auth",
"token_uri":"https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
"client_secret":"xxxxxxxxxxxxxxxx",
"redirect_uris":["http://localhost:8090/","http://localhost:8090/Callback"],
"javascript_origins":["http://localhost"]
}
}
Very useful step-by-step guide about how to get access and fresh tokens and save them for future use using YouTube OAuth API v3. PHP server-side YouTube V3 OAuth API video upload guide.
https://www.domsammut.com/code/php-server-side-youtube-v3-oauth-api-video-upload-guide
I found this great tutorial on Github about how to create a custom mailer from Devise. https://github.com/plataformatec/devise/wiki/How-To:-Use-custom-mailer
I implemented the code and the logic makes complete sense to me however when I deploy, I can't get the code to work when I set my config.mailer = 'MyMailer' in initialize/devise.rb. There are no errors in the terminal and it seems that everything got processed just like normal however the email never makes it to the inbox.
If I change config.mailer = 'Devise::Mailer', the email gets delivered correctly. However since MyMailer inherits from Devise::Mailer, shouldn't it work?
Is anyone else having this issue? Any ideas what I can do to troubleshoot?
Here is my "mailers/my_mailer.rb":
class MyMailer < Devise::Mailer
helper :application # gives access to all helpers defined within `application_helper`.
# helper :devise # gives access to all helpers defined within `devise_helper`.
#include Devise::Controllers # Optional. eg. `confirmation_url`
include Devise::Mailers::Helpers
def invoice_payment_failed_email(user, listing)
#user = user
#listing = listing
#url = 'http://example.com/login'
mail(to: #user.email, subject: 'Payment Failed')
end
end
Here is my "initializers/devise.rb":
Devise.setup do |config|
config.secret_key = ENV["DEVISE_SECRET_KEY"]
# Configure the class responsible to send e-mails.
config.mailer = 'MyMailer'
Here is my call to the deliver the mail:
# email customer
MyMailer.invoice_payment_failed_email(#user, #listing).deliver
*Update:
OMG... after a whole day of racking my brain trying to figure this out, it turns out that the code logic is fine but the problem was that my From: needed to match the Postmark sender accounts. This is why I wasn't getting any terminal errors. The deliver request was being sent correctly to Postmark but since my From address wasn't matching, postmark just never delivered the email!
In case of LDAP authenticaion, what are the parameters that are generally used for authentication. I guess using DN would be a headache for users logging in via ldap because it is too large to remember.
How is the option of using uid or sAMAccountName for authentication where in my implementation, I retrieve the dn of the corresponding uid or sAMAccountName and proceed to authentication.
Am I going the right track?
In LDAP, a connection or session can be authenticated. When an LDAP client makes a new connection to an LDAP directory server, the connection has an authorization state of anonymous. The LDAP client can request that the authorization state be changed by using the BIND request.
A BIND request has two forms: simple and SASL. Simple uses a distinguished name and a password, SASL uses one of a choice of mechanisms, for example, PLAIN, LOGIN, CRAM-MD5, DIGEST-MD5, GSSAPI, and EXTERNAL - all of which except for GSSAPI and EXTERNAL are too weak to use in production scenarios or mission-critical areas.
To Use the simple BIND, construct a BIND request and transmit it to the LDAP directory server. The LDAP directory server will respond with a BIND response in which is contained a result code. The result code is an integer, anything other zero indicates that the BIND request failed. If the result code is zero, the BIND request succeeded and the session authorization state has been changed to that of the distinguished name used in the BIND request.
Each subsequent BIND request on the same connection/session causes the authorization state to be set to anonymous and each successive successful BIND request on the same connection/session causes the authorization state to be set to the authorization state associated with the authentication ID, which is the distinguished name in the case of the simple BIND, but might be something else entirely where SASL is used - modern professional quality servers can map the incoming names to different DNs.
Whichever language is used, construct a BIND request, transmit it to the server, and interpret the response.
Update:
If the distinguished name is not known, or is too cumbersome (often the case with web application users who don't know how they are authenticated and would not care if they did know), the LDAP application should search the directory for the user. A successful search response always contains the distinguished name, which is then used in a simple BIND.
The search contains at a minimum, the following:
base object: a distinguished name superior to the user, for example, dc=example,dc=com
a scope: base level, one level below base, or subtree below base. For example, if users are located subordinate to ou=people,dc=example,dc=com, use base object ou=people,dc=example,dc=com and a scope of one-level. These search parameters find entries like: uid=user1,ou=people,dc=example,dc=com
a filter: narrows down the possible search results returned to the client, for example (objectClass=inetOrgPerson)
a list of requested attributes: the attributes from an entry to return to the client. In this case, use 1.1, which means no attributes and returns on the DN (distinguished name), which is all that is required for the simple BIND.
see also
the links in the about section here
LDAP servers only understand LDAP queries; they don't have "usernames" like you and I are used to.
For LDAP, to authenticate someone, you need to send a distinguished name of that person's (or entity's) entry in LDAP; along with their password.
Since you mentioned sAMAccountName I am assuming you are working with Active Directory. Active Directory allows anonymous binds - this means you can connect to it without providing any credentials; but cannot do any lookups without providing credentials.
If you are using python-ldap and Cython (and not IronPython which has access to the various .NET APIs that make this process very easy); then you follow these steps.
Typically you use a pre-set user that has appropriate rights to the tree, and connect to the directory with that user first, and then use that user's access for the rest of the authentication process; which generally goes like this:
Connect to AD with the pre-set user.
Query active directory with the pre-set user's credentials and search for the distinguished name based on the sAMAccountName that the user will enter as their "username" in your form.
Attempt to connect again to Active Directory using the distinguished name from step 2, and the password that the user entered in their form.
If this connection is successful, then the user is authenticated.
So you need two main things:
The login attribute (this is the "username" that LDAP understands)
A LDAP query that fetches information for your users
Following is some rough code that can do this for you:
AD_USER = 'your super user'
AD_PASSWORD = 'your super user password'
AD_BIND_ATTR = 'userPrincipalName' # this is the "login" for AD
AD_URL = "ldap://your-ad-server"
AD_DN = "DC=DOMAIN,DC=COM"
AD_LOGIN_ATTR = 'sAMAccountName' # this is what you user will enter in the form
# as their "login" name,
# this is what they use to login to Windows
# A listing of attributes you want to fetch for the user
AD_ATTR_SEARCH = ['cn',
'userPrincipalName',
'distinguishedName',
'mail',
'telephoneNumber','sAMAccountName']
def _getbinduser(user):
""" This method returns the bind user string for the user"""
user_dn = AD_DN
login_attr = '(%s=%s)' % (AD_LOGIN_ATTR,user)
attr_search = AD_ATTR_SEARCH
conn = ldap.initialize(AD_URL)
conn.set_option(ldap.OPT_REFERRALS,0)
conn.set_option(ldap.OPT_PROTOCOL_VERSION,3)
try:
conn.bind(AD_USER,AD_PASSWORD)
conn.result()
except:
exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
# Exit the script and print an error telling what happened.
sys.exit("LDAP Error (Bind Super User)\n ->%s" % exceptionValue)
try:
result = conn.search_s(user_dn,
ldap.SCOPE_SUBTREE,
login_attr, attr_search)
except:
exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
# Exit the script and print an error telling what happened.
sys.exit("LDAP Error (Search)\n ->%s" % exceptionValue)
# Return the user's entry from AD, which includes
# their 'distinguished name'
# we use this to authenticate the credentials the
# user has entered in the form
return result[0][1]
def authenticate(user,password):
bind_attr = AD_BIND_ATTR
user_dn = AD_DN
login_attr = '(%s=%s)' % (AD_LOGIN_ATTR,user)
data = _getbinduser(user)
if len(data) == 1:
return None
# Information we want to return from the directory
# for each user, season to taste.
info = {}
info['name'] = data['cn'][0]
info['email'] = data['mail'][0]
try:
info['phone'] = data['telephoneNumber'][0]
except KeyError:
info['phone'] = 'Not Available'
conn = ldap.initialize(Config.AD_URL)
conn.set_option(ldap.OPT_REFERRALS,0)
conn.set_option(ldap.OPT_PROTOCOL_VERSION,3)
try:
# Now we have the "bind attribute" (LDAP username) for our user
# we try and connect to see if LDAP will authenticate
conn.bind(data[bind_attr][0],password)
conn.search(user_dn,ldap.SCOPE_SUBTREE,login_attr,None)
conn.result()
return info
except (ldap.INVALID_CREDENTIALS,ldap.OPERATIONS_ERROR):
return None
One small expansion on Terry's excellent comment. If you store all your users in the same part of the DIT, and use the same attribute to identify them, you can programmatically construct the DN, rather than searching for it.