Skip to content

Commit

Permalink
变更数据库为mysql
Browse files Browse the repository at this point in the history
新增accounts认证login loginout
拆分header状态栏
  • Loading branch information
guohongze committed Mar 7, 2017
1 parent f77f0df commit 0269360
Show file tree
Hide file tree
Showing 50 changed files with 1,148 additions and 1,453 deletions.
2 changes: 2 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1,076 changes: 643 additions & 433 deletions .idea/workspace.xml

Large diffs are not rendered by default.

Empty file added accounts/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions accounts/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
7 changes: 7 additions & 0 deletions accounts/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from __future__ import unicode_literals

from django.apps import AppConfig


class AccountsConfig(AppConfig):
name = 'accounts'
33 changes: 33 additions & 0 deletions accounts/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from django import forms
from django.contrib import auth


class LoginUserForm(forms.Form):
username = forms.CharField(label=u'账 号', error_messages={'required': u'账号不能为空'},
widget=forms.TextInput(attrs={'class': 'form-control'}))
password = forms.CharField(label=u'密 码', error_messages={'required': u'密码不能为空'},
widget=forms.PasswordInput(attrs={'class': 'form-control'}))

def __init__(self, request=None, *args, **kwargs):
self.request = request
self.user_cache = None

super(LoginUserForm, self).__init__(*args, **kwargs)

def clean_password(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')

if username and password:
self.user_cache = auth.authenticate(username=username,password=password)
if self.user_cache is None:
raise forms.ValidationError(u'账号密码不匹配')
elif not self.user_cache.is_active:
raise forms.ValidationError(u'此账号已被禁用')
return self.cleaned_data

def get_user(self):
return self.user_cache

Empty file added accounts/migrations/__init__.py
Empty file.
60 changes: 60 additions & 0 deletions accounts/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
# Create your models here.


class PermissionList(models.Model):
name = models.CharField(max_length=64)
url = models.CharField(max_length=255)

def __unicode__(self):
return '%s(%s)' % (self.name, self.url)


class RoleList(models.Model):
name = models.CharField(max_length=64)
permission = models.ManyToManyField(PermissionList, null=True, blank=True)

def __unicode__(self):
return self.name


class UserManager(BaseUserManager):
def create_user(self,email,username,password=None):
if not email:
raise ValueError('Users must have an email address')

user = self.model(
email=self.normalize_email(email),
username=username,
)

user.set_password(password)
user.save(using=self._db)
return user

def create_superuser(self, email, username, password):
user = self.create_user(email,
username=username,
password=password,
)

user.is_active = True
user.is_superuser = True
user.save(using=self._db)
return user


class UserInfo(AbstractBaseUser):
username = models.CharField(max_length=40, unique=True, db_index=True)
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)
role = models.ForeignKey(RoleList,null=True,blank=True)

def has_perm(self, perm, obj=None):
if self.is_active and self.is_superuser:
return True
3 changes: 3 additions & 0 deletions accounts/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
11 changes: 11 additions & 0 deletions accounts/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import url, include
from accounts import views


urlpatterns = [
url(r'^$', views.index, name='accounts'),
url(r'^login/$', views.login, name='loginurl'),
url(r'^loginout/$', views.loginout, name='loginout'),
]
46 changes: 46 additions & 0 deletions accounts/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from django.shortcuts import render

# Create your views here.

from django.shortcuts import render_to_response, redirect, HttpResponse, HttpResponseRedirect, RequestContext
from django.contrib.auth.decorators import login_required
from hashlib import sha1
from django.contrib import auth
from forms import LoginUserForm


@login_required()
def index(request):
return HttpResponse("ok")


def login(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/')

if request.method == 'GET' and request.GET.has_key('next'):
next = request.GET['next']
else:
next = '/'

if request.method == "POST":
form = LoginUserForm(request, data=request.POST)
if form.is_valid():
auth.login(request, form.get_user())
return HttpResponseRedirect(request.POST['next'])
else:
form = LoginUserForm(request)

kwvars = {
'request': request,
'form': form,
'next': next,
}

return render_to_response('accounts/login.html', kwvars, RequestContext(request))


@login_required
def loginout(request):
auth.logout(request)
return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
8 changes: 8 additions & 0 deletions adminset.conf
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,12 @@ roles_path = /etc/ansible/roles/
playbook_path = /etc/ansible/playbook/
scripts_path = /etc/ansible/scripts/

[db]
engine = mysql
host = 127.0.0.1
port = 3306
user = root
password =
database = adminset


47 changes: 42 additions & 5 deletions adminset/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"""

import os
import ConfigParser


# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Expand All @@ -37,6 +39,7 @@
'cmdb',
'config',
'auser',
'accounts',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
Expand Down Expand Up @@ -81,12 +84,46 @@
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
config = ConfigParser.ConfigParser()
config.read(os.path.join(BASE_DIR, 'adminset.conf'))

DATABASES = {}
if config.get('db', 'engine') == 'mysql':
DB_HOST = config.get('db', 'host')
DB_PORT = config.getint('db', 'port')
DB_USER = config.get('db', 'user')
DB_PASSWORD = config.get('db', 'password')
DB_DATABASE = config.get('db', 'database')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': DB_DATABASE,
'USER': DB_USER,
'PASSWORD': DB_PASSWORD,
'HOST': DB_HOST,
'PORT': DB_PORT,
}
}
elif config.get('db', 'engine') == 'sqlite':
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': config.get('db', 'database'),
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
}


# Password validation
Expand Down
Binary file modified adminset/settings.pyc
Binary file not shown.
3 changes: 2 additions & 1 deletion adminset/urls.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from django.conf.urls import include,url
from django.contrib import admin
from django.conf import settings
from . import views
from navi import views

urlpatterns = [
url(r'^$', views.index, name='index'),
Expand All @@ -11,4 +11,5 @@
url(r'^setup/', include('setup.urls')),
url(r'^auser/', include('auser.urls')),
url(r'^config/', include('config.urls')),
url(r'^accounts/', include('accounts.urls')),
]
1 change: 0 additions & 1 deletion auser/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ def login(request):
is_auth = SysUser.objects.filter(username=user, password=pwd).count()
if is_auth == 1:
request.session['is_login'] = {'user': user}
print request.user
return redirect('/auser/')
else:
ret['status'] = 'user or password error!'
Expand Down
3 changes: 2 additions & 1 deletion cmdb/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

try:
import json
except ImportError,e:
except ImportError, e:
import simplejson as json


Expand Down Expand Up @@ -78,6 +78,7 @@ def pages(post_objects, request):
# 所有对象, 分页器, 本页对象, 所有页码, 本页页码,是否显示第一页,是否显示最后一页
return post_objects, paginator, page_objects, page_range, current_page, show_first, show_end


def collect(request):
req = request
if req.POST:
Expand Down
Loading

0 comments on commit 0269360

Please sign in to comment.