首页 > 代码库 > Django使用自定义的authentication登录认证
Django使用自定义的authentication登录认证
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})
Django使用自定义的authentication登录认证
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。