Commit 1a597f51f9e3469ee41b5bc9a422289c4872b033

Authored by zhuzhenchao
1 parent e11f60ade2
Exists in master

add login token

1 # coding: utf-8
2
3
homepage/models.py
1 # coding: utf-8 1 # coding: utf-8
2 2
3 from django.db import models 3 from django.db import models
4 4
5 from django.contrib.auth.models import AbstractUser 5 from django.contrib.auth.models import AbstractUser
6 6
7 7
8 # 数据库表结构 8 # 数据库表结构
9 class ForumUser(AbstractUser): 9 class ForumUser(AbstractUser):
10 ''' 10 '''
11 django.contrib.auth.models.User 默认User类字段太少,用AbstractUser 11 django.contrib.auth.models.User 默认User类字段太少,用AbstractUser
12 自定义一个User类,增加字段 12 自定义一个User类,增加字段
13 ''' 13 '''
14 nickname = models.CharField(max_length=200, null=True, blank=True) 14 suid = models.IntegerField(u'uid')
15 avatar = models.CharField(max_length=200, null=True, blank=True) # 头像 15 user_name = models.CharField(u'用户名', max_length=20)
16 signature = models.CharField(max_length=500, null=True, blank=True) # 签名 16 level = models.IntegerField(u'level')
17 location = models.CharField(max_length=200, null=True, blank=True) 17 create_time = models.DateTimeField()
18 website = models.URLField(null=True, blank=True) 18 status = models.IntegerField()
19 company = models.CharField(max_length=200, null=True, blank=True) 19 last_login_ip = models.CharField(max_length=20)
20 role = models.IntegerField(null=True, blank=True) # 角色 20 last_login_time = models.DateTimeField()
21 balance = models.IntegerField(null=True, blank=True) # 余额
22 reputation = models.IntegerField(null=True, blank=True) # 声誉
23 self_intro = models.CharField(max_length=500, null=True, blank=True)# 自我介绍
24 updated = models.DateTimeField(null=True, blank=True)
25 twitter = models.CharField(max_length=200, null=True, blank=True)
26 github = models.CharField(max_length=200, null=True, blank=True)
27 douban = models.CharField(max_length=200, null=True, blank=True)
28 21
29 def __unicode__(self): 22 def __unicode__(self):
30 return self.username 23 return self.user_name
31 24
32 class Meta(object): 25 class Meta(object):
33 db_table = 'forum_forumuser' 26 db_table = 'sys_user'
34 verbose_name = verbose_name_plural = u'用户' 27 verbose_name = verbose_name_plural = u'用户'
homepage/views.py
1 1
2 2
3 import json 3 import json
4 import logging 4 import logging
5 import requests
5 from django.contrib import auth 6 from django.contrib import auth
6 from django.contrib.auth import logout 7 from django.contrib.auth import logout
7 from django.contrib.auth.decorators import login_required 8 from django.contrib.auth.decorators import login_required
8 from django.http import HttpResponseRedirect 9 from django.http import HttpResponseRedirect
9 from django.contrib.auth import get_user_model 10 from django.contrib.auth import get_user_model
10 from django.shortcuts import render_to_response 11 from django.shortcuts import render_to_response
11 from django.template import RequestContext 12 from django.template import RequestContext
12 from django.template.context_processors import csrf 13 from django.template.context_processors import csrf
13 from django.conf import settings 14 from django.conf import settings
14 15
15 @login_required 16 @login_required
16 def homepage(request): 17 def homepage(request):
17 18
18 username = request.user.username 19 username = request.user.username
20 import pdb; pdb.set_trace()
19 t = HttpResponseRedirect('/admin/') 21 t = HttpResponseRedirect('/admin/')
20 t.set_cookie('username', username, 864000) 22 t.set_cookie('username', username, 864000)
21 return t 23 return t
22 24
23 25
24 def mylogin(request): 26 def mylogin(request):
25 alert_msg= 0 27 alert_msg= 0
26 if request.method =='GET': 28 if request.method =='GET':
27 cookies_username = request.COOKIES.get('username','') 29 cookies_username = request.COOKIES.get('username','')
28 c = csrf(request) 30 c = csrf(request)
29 c.update({'alert_msg':alert_msg,'cookies_username:':cookies_username}) 31 c.update({'alert_msg':alert_msg,'cookies_username:':cookies_username})
30 return render_to_response('login.html', c) 32 return render_to_response('login.html', c)
31 else: 33 else:
32 postdata = request.POST 34 postdata = request.POST
33 username = postdata.get('username','') 35 username = postdata.get('username','')
34 password = postdata.get('password','') 36 password = postdata.get('password','')
35 post_params = { 37 post_params = {
36 'comefrom': 2, 38 'comefrom': 2,
37 'user_name': username, 39 'user_name': username,
38 'password': password, 40 'password': password,
39 } 41 }
40 resp = request.post(settings.AUTH_DOMAIN, data=post_params, verify=False) 42 resp = requests.post(settings.AUTH_DOMAIN, data=post_params, verify=False)
41 if resp.status_code == 200: 43 if resp.status_code == 200:
42 rst = resp.json() 44 rst = resp.json()
43 if rst.get('status') == 1: 45 if rst.get('status') == 1:
44 data = rst.get('data') 46 data = rst.get('data')
45 token = data.get('token') 47 token = data.get('token')
46 suid = data.get('1000') 48 suid = data.get('1000')
47 t = HttpResponseRedirect('/admin/') 49 t = HttpResponseRedirect('/admin/')
48 t.set_cookie('pu', username, 864000) 50 t.set_cookie('pu', token, 864000)
49 t.set_cookie(('pt'), ) 51 t.set_cookie('pt', suid, 864000)
50 52 t.set_cookie('username', username, 86400)
51 else: 53 return t
52 pass 54
53 if user: 55 t = HttpResponseRedirect('/login/')
54 auth.login(request, user)
55 t = HttpResponseRedirect('/admin/')
56 t.set_cookie('username', username, 864000)
57 return t
58 56
59 57
60 def mylogout(request): 58 def mylogout(request):
middlewares/__init__.py
middlewares/session_middleware.py
1 # coding: utf-8 1 # coding: utf-8
2 2
3 import requests 3 import requests
4 from django.conf import settings 4 from django.conf import settings
5 from django.core.cache import caches 5 from django.core.cache import caches
6 from django.contrib.auth import get_user_model 6 from django.contrib.auth import get_user_model
7 from django.contrib.auth.models import AnonymousUser 7 from django.contrib.auth.models import AnonymousUser
8 8
9 class SessionWithoutLocalUserMiddleware(object): 9 class SessionWithoutLocalUserMiddleware(object):
10 """ 10 """
11 统一权限(认证)中间件,Django系统本地不保存用户的情况使用 11 统一权限(认证)中间件,Django系统本地不保存用户的情况使用
12 """ 12 """
13 13
14 def __init__(self): 14 def __init__(self):
15 self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS 15 self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
16 self.cache = caches[self.cache_alias] 16 self.cache = caches[self.cache_alias]
17 self.UserModel = get_user_model() 17 self.UserModel = get_user_model()
18 18
19 def process_request(self, request): 19 def process_request(self, request):
20 if hasattr(request, "user") and getattr(request.user, "is_superuser", False): 20 if hasattr(request, "user") and getattr(request.user, "is_superuser", False):
21 # 对于Django系统的admin用户,这里不做任何处理 21 # 对于Django系统的admin用户,这里不做任何处理
22 pass 22 pass
23 else: 23 else:
24 pt = request.COOKIES.get('pt') 24 pt = request.COOKIES.get('pt')
25 pu = request.COOKIES.get('pu') 25 pu = request.COOKIES.get('pu')
26 username = request.COOKIES.get('username')
26 if pt and pu: 27 if pt and pu:
27 # 能拿到统一认证session的情况,优先从缓存中拿用户 28 # 查询session状态成功的情况,构造QCCRUser
28 user = self.cache.get(pu) 29 user = XYTUser(username, pu, pt)
29 if not user:
30 # 如果缓存未命中,则直接调用统一权限,查询当前session的状态,构造用户,并存入缓存
31 user_info = ''
32
33 manager = Manager()
34 user_info = manager.get_user_info(request)
35 if user_info is None:
36 # 查询session状态失败的情况,构造匿名用户
37 user = AnonymousUser()
38 else:
39 # 查询session状态成功的情况,构造QCCRUser
40 user = user_info
41 self.cache.set(pt, user, 60)
42 request.user = user 30 request.user = user
43 else: 31 else:
44 # 拿不到统一认证的session,将当前用户设为匿名用户 32 # 拿不到统一认证的session,将当前用户设为匿名用户
45 request.user = AnonymousUser() 33 request.user = AnonymousUser()
46 34
47 35
48 class Manager(object): 36 class Manager(object):
49 37
50 def __init__(self): 38 def __init__(self):
51 self.auth_domain = 'https://api.xiuyetang.com/sys/user/login' 39 self.auth_domain = 'https://api.xiuyetang.com/sys/user/login'
52 40
53 def get_user_info(self, request):
54 pass
41
42 class XYTUser(object):
43 id = None
44 pk = None
45 username = ''
46 sessionId = ''
47 accountNo = ''
48 employeeName = ''
49 employeeId = 0
50 employeeNo = ''
51 employeeTel = ''
52 deptIds = ''
53 email = ''
54 entryTime = ''
55 uid = ''
56 is_staff = False
57 is_active = False
58 is_superuser = False
59 _groups = ''
60 _user_permissions = ''
61
62 def __init__(self, username, pu, pt):
63 self.username = username
64 self.id = pu
65 self.pk = pu
66 self.sessionId = pt
67
68 def __str__(self):
69 return self.username
70
71 def __eq__(self, other):
72 return self.username == other.username
73
74 def __ne__(self, other):
75 return not self.__eq__(other)
76
77 def __hash__(self):
78 return hash(self.username)
79
80 def save(self):
81 raise NotImplementedError("Django doesn't provide a DB representation for QCCRUser. User info in LDAP.")
82
83 def delete(self):
84 raise NotImplementedError("Django doesn't provide a DB representation for QCCRUser. User info in LDAP.")
85
86 def set_password(self, raw_password):
87 raise NotImplementedError("Django doesn't provide a DB representation for QCCRUser. Password in LDAP.")
88
89 def check_password(self, raw_password):
90 raise NotImplementedError("Django doesn't provide a DB representation for QCCRUser. Password in LDAP.")
91
92 def _get_groups(self):
93 return self._groups
94
95 groups = property(_get_groups)
96
97 def _get_user_permissions(self):
98 return self._user_permissions
99
weapp_sys/settings.py
1 """ 1 """
2 Django settings for weapp_sys project. 2 Django settings for weapp_sys project.
3 3
4 Generated by 'django-admin startproject' using Django 1.8. 4 Generated by 'django-admin startproject' using Django 1.8.
5 5
6 For more information on this file, see 6 For more information on this file, see
7 https://docs.djangoproject.com/en/1.8/topics/settings/ 7 https://docs.djangoproject.com/en/1.8/topics/settings/
8 8
9 For the full list of settings and their values, see 9 For the full list of settings and their values, see
10 https://docs.djangoproject.com/en/1.8/ref/settings/ 10 https://docs.djangoproject.com/en/1.8/ref/settings/
11 """ 11 """
12 12
13 # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 13 # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
14 import os 14 import os
15 15
16 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 16 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17 17
18 18
19 # Quick-start development settings - unsuitable for production 19 # Quick-start development settings - unsuitable for production
20 # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ 20 # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
21 21
22 # SECURITY WARNING: keep the secret key used in production secret! 22 # SECURITY WARNING: keep the secret key used in production secret!
23 SECRET_KEY = 'y7m+ekd64@hxa0ej(&w6u!itch2glt)+6imlbr7ob8=_nk%@gi' 23 SECRET_KEY = 'y7m+ekd64@hxa0ej(&w6u!itch2glt)+6imlbr7ob8=_nk%@gi'
24 24
25 # SECURITY WARNING: don't run with debug turned on in production! 25 # SECURITY WARNING: don't run with debug turned on in production!
26 DEBUG = True 26 DEBUG = True
27 27
28 ALLOWED_HOSTS = [] 28 ALLOWED_HOSTS = []
29 29
30 30
31 # Application definition 31 # Application definition
32 32
33 INSTALLED_APPS = ( 33 INSTALLED_APPS = (
34 'django.contrib.admin', 34 'django.contrib.admin',
35 'django.contrib.auth', 35 'django.contrib.auth',
36 'django.contrib.contenttypes', 36 'django.contrib.contenttypes',
37 'django.contrib.sessions', 37 # 'django.contrib.sessions',
38 'django.contrib.messages', 38 'django.contrib.messages',
39 'django.contrib.staticfiles', 39 'django.contrib.staticfiles',
40 'homepage', 40 'homepage',
41 ) 41 )
42 42
43 MIDDLEWARE_CLASSES = ( 43 MIDDLEWARE_CLASSES = (
44 'django.contrib.sessions.middleware.SessionMiddleware', 44 # 'django.contrib.sessions.middleware.SessionMiddleware',
45 'django.middleware.common.CommonMiddleware', 45 'django.middleware.common.CommonMiddleware',
46 'django.middleware.csrf.CsrfViewMiddleware', 46 'django.middleware.csrf.CsrfViewMiddleware',
47 'django.contrib.auth.middleware.AuthenticationMiddleware', 47 # 'django.contrib.auth.middleware.AuthenticationMiddleware',
48 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 48 # 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
49 'django.contrib.messages.middleware.MessageMiddleware', 49 # 'django.contrib.messages.middleware.MessageMiddleware',
50 'django.middleware.clickjacking.XFrameOptionsMiddleware', 50 'django.middleware.clickjacking.XFrameOptionsMiddleware',
51 'django.middleware.security.SecurityMiddleware', 51 'django.middleware.security.SecurityMiddleware',
52 'middlewares.session_middleware.SessionWithoutLocalUserMiddleware',
52 ) 53 )
53 54
54 ROOT_URLCONF = 'weapp_sys.urls' 55 ROOT_URLCONF = 'weapp_sys.urls'
55 56
56 TEMPLATES = [ 57 TEMPLATES = [
57 { 58 {
58 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 'BACKEND': 'django.template.backends.django.DjangoTemplates',
59 'DIRS': [os.path.join(BASE_DIR, 'templates')], 60 'DIRS': [os.path.join(BASE_DIR, 'templates')],
60 'APP_DIRS': True, 61 'APP_DIRS': True,
61 'OPTIONS': { 62 'OPTIONS': {
62 'context_processors': [ 63 'context_processors': [
63 'django.template.context_processors.debug', 64 'django.template.context_processors.debug',
64 'django.template.context_processors.request', 65 'django.template.context_processors.request',
65 'django.contrib.auth.context_processors.auth', 66 'django.contrib.auth.context_processors.auth',
66 'django.contrib.messages.context_processors.messages', 67 'django.contrib.messages.context_processors.messages',
67 ], 68 ],
68 }, 69 },
69 }, 70 },
70 ] 71 ]
71 72
72 73
73 WSGI_APPLICATION = 'weapp_sys.wsgi.application' 74 WSGI_APPLICATION = 'weapp_sys.wsgi.application'
74 75
75 AUTH_USER_MODEL = 'homepage.ForumUser' 76 AUTH_USER_MODEL = 'homepage.ForumUser'
76 77
77 # Database 78 # Database
78 # https://docs.djangoproject.com/en/1.8/ref/settings/#databases 79 # https://docs.djangoproject.com/en/1.8/ref/settings/#databases
79 80
80 DATABASES = { 81 DATABASES = {
81 'default': { 82 'default': {
82 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 83 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
83 'NAME': 'forum', # Or path to database file if using sqlite3. 84 'NAME': 'forum', # Or path to database file if using sqlite3.
84 # The following settings are not used with sqlite3: 85 # The following settings are not used with sqlite3:
85 'USER': 'root', 86 'USER': 'root',
86 'PASSWORD': '', 87 'PASSWORD': 'nineteen',
87 'HOST': '127.0.0.1', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 88 'HOST': '121.40.31.31', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
88 'PORT': '3306', 89 'PORT': '3306',
89 } 90 }
90 } 91 }
91 92
92 93
93 # Internationalization 94 # Internationalization
94 # https://docs.djangoproject.com/en/1.8/topics/i18n/ 95 # https://docs.djangoproject.com/en/1.8/topics/i18n/
95 96
96 LANGUAGE_CODE = 'zh-CN' 97 LANGUAGE_CODE = 'zh-CN'
97 98
98 TIME_ZONE = 'Asia/Shanghai' 99 TIME_ZONE = 'Asia/Shanghai'
99 100
100 USE_I18N = True 101 USE_I18N = True
101 102
102 USE_L10N = True 103 USE_L10N = True
103 104
104 USE_TZ = False 105 USE_TZ = False
105 106
106 DATETIME_FORMAT = 'Y-m-d H:i:s' 107 DATETIME_FORMAT = 'Y-m-d H:i:s'
107 TIME_FORMAT = 'H:i:s' 108 TIME_FORMAT = 'H:i:s'
108 109
109 110
110 STATIC_ROOT = os.path.join(BASE_DIR, 'static') 111 STATIC_ROOT = os.path.join(BASE_DIR, 'static')
111 STATIC_URL = '/static/' 112 STATIC_URL = '/static/'
112 STATICFILES_DIRS = ( 113 STATICFILES_DIRS = (
113 # Put strings here, like "/home/html/static" or "C:/www/django/static". 114 # Put strings here, like "/home/html/static" or "C:/www/django/static".
114 # Always use forward slashes, even on Windows. 115 # Always use forward slashes, even on Windows.
115 # Don't forget to use absolute paths, not relative paths. 116 # Don't forget to use absolute paths, not relative paths.
116 117
117 # ("css", os.path.join(STATIC_ROOT,'css')), 118 # ("css", os.path.join(STATIC_ROOT,'css')),
118 ("js", os.path.join(STATIC_ROOT, 'js')), 119 ("js", os.path.join(STATIC_ROOT, 'js')),
119 ("image", os.path.join(STATIC_ROOT, 'image')), 120 ("image", os.path.join(STATIC_ROOT, 'image')),
120 ("css", os.path.join(STATIC_ROOT, 'css')), 121 ("css", os.path.join(STATIC_ROOT, 'css')),
121 ("dist", os.path.join(STATIC_ROOT, 'dist')), 122 ("dist", os.path.join(STATIC_ROOT, 'dist')),
122 ("plugins", os.path.join(STATIC_ROOT, 'plugins')), 123 ("plugins", os.path.join(STATIC_ROOT, 'plugins')),
123 ("fonts", os.path.join(STATIC_ROOT, 'fonts')), 124 ("fonts", os.path.join(STATIC_ROOT, 'fonts')),
124 ("font-awesome", os.path.join(STATIC_ROOT, 'font-awesome')), 125 ("font-awesome", os.path.join(STATIC_ROOT, 'font-awesome')),
125 ("img", os.path.join(STATIC_ROOT, 'img')), 126 ("img", os.path.join(STATIC_ROOT, 'img')),
126 ("bootstrap", os.path.join(STATIC_ROOT, 'bootstrap')), 127 ("bootstrap", os.path.join(STATIC_ROOT, 'bootstrap')),
127 ("apps/ueditor", os.path.join(STATIC_ROOT, 'ueditor')), 128 ("apps/ueditor", os.path.join(STATIC_ROOT, 'ueditor')),
128 ("echarts", os.path.join(STATIC_ROOT, 'echarts')), 129 ("echarts", os.path.join(STATIC_ROOT, 'echarts')),
129 ("ueditor", os.path.join(STATIC_ROOT, 'ueditor')), 130 ("ueditor", os.path.join(STATIC_ROOT, 'ueditor')),
130 ("ventor", os.path.join(STATIC_ROOT, 'ventor')), 131 ("ventor", os.path.join(STATIC_ROOT, 'ventor')),
131 ) 132 )
132 133
133 134
134 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 135 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
135 MEDIA_ROOT = os.path.join(BASE_DIR, 'media') 136 MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
136 MEDIA_URL = '/media/' 137 MEDIA_URL = '/media/'
137 138
138 LOGIN_URL = '/login/' 139 LOGIN_URL = '/login/'
139 140
140 AUTH_DOMAIN = 'https://api.xiuyetang.com/sys/user/login' 141 AUTH_DOMAIN = 'https://api.xiuyetang.com/sys/user/login'