import ldap
class LDAPMgmt():
def __init__(self):
self.ldap_host = 'xxx'
self.ldap_base_dn = 'ou=xx,dc=xx,dc=xx,dc=xx'
self.root_cn = 'cn=xx,dc=xx,dc=xx'
self.root_pw = 'xx'
self.conn = ldap.initialize(self.ldap_host)
self.conn.set_option(ldap.OPT_REFERRALS, 0)
self.conn.protocol_version = ldap.VERSION3
self.conn.simple_bind_s(self.root_cn, self.root_pw)
def authenticate(self, username,password, scope=ldap.SCOPE_SUBTREE, attr=None):
result = {}
searchFilter = "uid=*" + username + "*"
try:
ldap_result = self.conn.search_s(self.ldap_base_dn, scope, searchFilter, attr)
try:
DN = ldap_result[0][0]
except Exception,e:
print('use %s not exist' %username)
return False
try:
print self.conn.simple_bind_s(DN,password)
return True
except ldap.LDAPError,err:
print err
return False
except ldap.LDAPError, e:
print e
return False
instance = LDAPMgmt()
@defend_attack
def Login(request):
"""登录界面"""
error = ''
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('index'))
if request.method == 'GET':
return render_to_response('login.html')
else:
username = request.POST.get('username')
password = request.POST.get('password')
#print username,password
if username and password:
aa = instance.authenticate(username,password)
#user = authenticate(username=username, password=password,)
if aa:
#user = authenticate(username=username,password=password)
from juser import models as usermodels
user = usermodels.User.objects.filter(name=username)[0]
if user:
user.backend='django.contrib.auth.backends.ModelBackend'
if user.is_active:
login(request, user)
if user.role == 'SU':
request.session['role_id'] = 2
elif user.role == 'GA':
request.session['role_id'] = 1
else:
request.session['role_id'] = 0
return HttpResponseRedirect(request.session.get('pre_url', '/'))
else:
error = '用户未激活'
else:
error = '用户名或密码错误'
else:
error = '用户名或密码错误'
else:
error = '用户名或密码错误'
return render_to_response('login.html', {'error': error})