Skip to content

Commit

Permalink
Merge branch 'dev'
Browse files Browse the repository at this point in the history
  • Loading branch information
guohongze committed Aug 25, 2018
2 parents 505c24a + 08e6171 commit 143d7aa
Show file tree
Hide file tree
Showing 20 changed files with 475 additions and 132 deletions.
22 changes: 22 additions & 0 deletions accounts/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,28 @@ def save(self, commit=True):
return self.user


class ChangeLdapPasswordForm(forms.Form):
new_password1 = forms.CharField(label=u'新密码', error_messages={'required': '请输入新密码'},
widget=forms.PasswordInput(attrs={'class': 'form-control', 'style': 'width:500px;'}))
new_password2 = forms.CharField(label=u'新密码', error_messages={'required': '请重复新输入密码'},
widget=forms.PasswordInput(attrs={'class': 'form-control', 'style': 'width:500px;'}))

def __init__(self, user, *args, **kwargs):
self.user = user
super(ChangeLdapPasswordForm, self).__init__(*args, **kwargs)

def clean_new_password2(self):
password1 = self.cleaned_data.get('new_password1')
password2 = self.cleaned_data.get('new_password2')
if len(password1)<6:
raise forms.ValidationError(u'密码必须大于6位')

if password1 and password2:
if password1 != password2:
raise forms.ValidationError(u'两次密码输入不一致')
return password2


class RoleListForm(forms.ModelForm):
class Meta:
model = RoleList
Expand Down
54 changes: 54 additions & 0 deletions accounts/gldap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#! /usr/bin/env python
# -*- coding: utf-8 -*-

from ldap3 import Server, Connection, SUBTREE
from lib.common import get_dir


class UseLdap:
def __init__(self):
self.port = get_dir("ldap_port")
self.server = get_dir("ldap_server")
self.manager = get_dir("ldap_manager")
self.passwd = get_dir("ldap_password")
self.base = get_dir("base_dn")
self.type = get_dir("ldap_filter")
if self.port:
self.server = self.server + ":" + self.port

def connect(self):
server = Server(self.server)
c = Connection(server, user=self.manager, password=self.passwd)
c.bind()
return c

def get_dn(self, username):
if self.type == "OpenLDAP":
ldap_type = "uid"
else:
ldap_type = "sAMAccountName"
c = self.connect()
c.search(search_base=self.base,
search_filter="(&(objectClass=*)({0}={1}))".format(ldap_type, username),
search_scope=SUBTREE
)
for entry in c.response:
user_dn = entry['dn']
c.unbind()
return user_dn

def change_password(self, username, newpwd):
user_dn = self.get_dn(username)
c = self.connect()
if self.type == "OpenLDAP":
c.extend.standard.modify_password(user_dn, new_password=newpwd)
else:
c.extend.microsoft.modify_password(user_dn, new_password=newpwd)
c.unbind()


def change_ldap_passwd(username, newpwd):
g = UseLdap()
g.change_password(username, newpwd)
return "OK"

3 changes: 2 additions & 1 deletion accounts/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,9 @@ class UserInfo(AbstractBaseUser):
email = models.EmailField(max_length=255)
is_active = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
nickname = models.CharField(max_length=64, null=True)
nickname = models.CharField(max_length=64, null=True, blank=True)
role = models.ForeignKey(RoleList, null=True, blank=True)
ldap_name = models.CharField(max_length=64, blank=True)

objects = UserManager()
USERNAME_FIELD = 'username'
Expand Down
3 changes: 2 additions & 1 deletion accounts/urls.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import url, include
from accounts import user, role, permission
from accounts import user, role, permission, gldap


urlpatterns = [
Expand All @@ -14,6 +14,7 @@
url(r'^user/edit/(?P<ids>\d+)/$', user.user_edit, name='user_edit'),
url(r'^reset/password/(?P<ids>\d+)/$', user.reset_password, name='reset_password'),
url(r'^change/password/$', user.change_password, name='change_password'),
url(r'^change/ldap/password/$', user.change_ldap, name='change_ldap_password'),
url(r'^role/add/$', role.role_add, name='role_add'),
url(r'^role/list/$', role.role_list, name='role_list'),
url(r'^role/edit/(?P<ids>\d+)/$', role.role_edit, name='role_edit'),
Expand Down
25 changes: 23 additions & 2 deletions accounts/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
from django.shortcuts import render, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib import auth
from accounts.forms import LoginUserForm, EditUserForm, ChangePasswordForm
from accounts.forms import LoginUserForm, EditUserForm, ChangePasswordForm, ChangeLdapPasswordForm
from django.contrib.auth import get_user_model
from accounts.forms import AddUserForm
from django.core.urlresolvers import reverse
from accounts.permission import permission_verify
from accounts.gldap import change_ldap_passwd


def login(request):
Expand Down Expand Up @@ -86,6 +87,7 @@ def user_del(request, ids):
@permission_verify()
def user_edit(request, ids):
user = get_user_model().objects.get(id=ids)
ldap_name = user.ldap_name
if request.method == 'POST':
form = EditUserForm(request.POST, instance=user)
if form.is_valid():
Expand Down Expand Up @@ -121,7 +123,7 @@ def change_password(request):
form = ChangePasswordForm(user=request.user, data=request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('logout'))
return HttpResponseRedirect(reverse('user_list'))
else:
form = ChangePasswordForm(user=request.user)
kwargs = {
Expand All @@ -130,3 +132,22 @@ def change_password(request):
'temp_name': temp_name,
}
return render(request, 'accounts/change_password.html', kwargs)


@login_required
def change_ldap(request):
temp_name = "accounts/accounts-header.html"
if request.method == 'POST':
form = ChangeLdapPasswordForm(user=request.user, data=request.POST)
if form.is_valid():
newpwd = form.clean_new_password2()
change_ldap_passwd(request.user, newpwd)
return HttpResponseRedirect(reverse('user_list'))
else:
form = ChangeLdapPasswordForm(user=request.user)
kwargs = {
'form': form,
'request': request,
'temp_name': temp_name,
}
return render(request, 'accounts/change_ldap_password.html', kwargs)
12 changes: 12 additions & 0 deletions adminset.conf
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,16 @@ redis_port = 6379
redis_password =
redis_db = 0

[ldap]
ldap_enable = False
ldap_server =
ldap_port =
base_dn =
ldap_manager =
ldap_password =
ldap_filter = OpenLDAP
require_group =
nickname =
is_active =
is_superuser =

97 changes: 0 additions & 97 deletions adminset/ldap.py

This file was deleted.

94 changes: 93 additions & 1 deletion adminset/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"""

import os
import ldap
from django_auth_ldap.config import LDAPSearch, GroupOfNamesType, PosixGroupType
try:
import ConfigParser as cp
except ImportError as e:
Expand Down Expand Up @@ -202,4 +204,94 @@
)
}

AUTH_USER_MODEL = 'accounts.UserInfo'
#ldap configurations
ldap_enable = config.get('ldap', 'ldap_enable')
if ldap_enable == "True":
ldap_port = config.get('ldap', 'ldap_port')
if ldap_port:
ldap_server = config.get('ldap', 'ldap_server') + ":" + ldap_port
else:
ldap_server = config.get('ldap', 'ldap_server')
base_dn = config.get('ldap', 'base_dn')
ldap_manager = config.get('ldap', 'ldap_manager')
ldap_password = config.get('ldap', 'ldap_password')
ldap_filter = config.get('ldap', 'ldap_filter')
if ldap_filter == "OpenLDAP":
ldap_filter = '(uid=%(user)s)'
else:
ldap_filter = '(sAMAccountName=%(user)s)'

AUTH_LDAP_SERVER_URI = ldap_server

AUTH_LDAP_BIND_DN = ldap_manager
AUTH_LDAP_BIND_PASSWORD = ldap_password
AUTH_LDAP_USER_SEARCH = LDAPSearch(
base_dn,
ldap.SCOPE_SUBTREE,
ldap_filter,
)
# Or:
# AUTH_LDAP_USER_DN_TEMPLATE = 'uid=%(user)s,ou=users,dc=example,dc=com'

# Set up the basic group parameters.
AUTH_LDAP_GROUP_SEARCH = LDAPSearch(
base_dn,
ldap.SCOPE_SUBTREE,
#'(objectClass=posixGroup)',
'(objectClass=*)',
)
AUTH_LDAP_GROUP_TYPE = PosixGroupType(name_attr='cn')
#
# # Simple group restrictions
require_group = config.get('ldap', 'require_group')
nickname = config.get('ldap', 'nickname')
is_active = config.get('ldap', 'is_active')
is_superuser = config.get('ldap', 'is_superuser')
if require_group:
#AUTH_LDAP_REQUIRE_GROUP = 'cn=enable,ou=scimall,dc=gldap,dc=com'
AUTH_LDAP_REQUIRE_GROUP = require_group
# AUTH_LDAP_DENY_GROUP = 'cn=disabled,ou=django,ou=groups,dc=example,dc=com'

# Populate the Django user from the LDAP directory.
if not nickname:
nickname = 'cn'
AUTH_LDAP_USER_ATTR_MAP = {
# 'first_name': 'givenName',
# 'last_name': 'sn',
'nickname': nickname,
'email': 'mail',
'ldap_name': 'cn',
}

if is_active and not is_superuser:
AUTH_LDAP_USER_FLAGS_BY_GROUP = {
'is_active': is_active,
}
elif is_superuser and not is_active:
AUTH_LDAP_USER_FLAGS_BY_GROUP = {
'is_superuser': is_superuser,
}
elif is_active and is_superuser:
AUTH_LDAP_USER_FLAGS_BY_GROUP = {
'is_active': is_active,
'is_superuser': is_superuser,
}

# This is the default, but I like to be explicit.
AUTH_LDAP_ALWAYS_UPDATE_USER = True

# Use LDAP group membership to calculate group permissions.
# AUTH_LDAP_FIND_GROUP_PERMS = True

# Cache distinguised names and group memberships for an hour to minimize
# LDAP traffic.

AUTH_LDAP_CACHE_TIMEOUT = 60
# Keep ModelBackend around for per-user permissions and maybe a local
# superuser.
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)

AUTH_USER_MODEL = 'accounts.UserInfo'
2 changes: 1 addition & 1 deletion config/tests.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from django.test import TestCase

# Create your tests here.
# Create your tests here.
Loading

0 comments on commit 143d7aa

Please sign in to comment.