Skip to content

Commit

Permalink
Merge pull request #338 from baifendian/fix-session-tpl
Browse files Browse the repository at this point in the history
session问题解决和模版文件优化
  • Loading branch information
qqzxingchen authored Nov 23, 2016
2 parents b6dd268 + 7a9582d commit c0924ea
Show file tree
Hide file tree
Showing 9 changed files with 100 additions and 72 deletions.
3 changes: 2 additions & 1 deletion Aries/Aries/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,8 @@
NAMENODE_PATH = CLIENTHDFS_SETTINGS["NAMENODE_PATH"]

HADOOP_RUN_SCRIPT = "hadoop-run.sh"
SESSION_COOKIE_AGE=60*30
SESSION_COOKIE_AGE = 60*30
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
#kubectl_file
KUBECTL_OSX = os.path.join(BASE_DIR, '../package', 'kubectl_osx_1_2_4')
KUBECTL_LINUX = os.path.join(BASE_DIR, '../package', 'kubectl_linux_1_2_4')
Expand Down
74 changes: 32 additions & 42 deletions Aries/Aries/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,28 @@
import logging
ac_logger = logging.getLogger("access_log")
from django.contrib.auth.models import User
from django.contrib.auth import login as auth_login,logout as auth_logout,authenticate
from django.contrib.auth import login as auth_login, logout as auth_logout, authenticate
from django.shortcuts import render_to_response
import json
from django.http import HttpResponse
from user_auth.models import *
from ldap_client import ldap_get_vaild
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.decorators.csrf import ensure_csrf_cookie, csrf_exempt
from django.conf import settings

def is_admin(account,cur_space_in):
def is_admin(account, cur_space_in):
is_supper = 0
if cur_space_in:
cur_space_1 = Space.objects.filter(name=cur_space_in)
cur_space_1 = Space.objects.filter(name=cur_space_in)
if cur_space_1:
cur_space = cur_space_in
else:
cur_space = ""
else:
else:
cur_space = cur_space_in
flag = True
if account.role.name.upper() in ["SUPERADMIN","ROOT"]:
is_admin =1
if account.role.name.upper() in ["SUPERADMIN", "ROOT"]:
is_admin = 1
is_supper = 1
if not cur_space:
spaces = Space.objects.all()
Expand All @@ -47,7 +47,7 @@ def is_admin(account,cur_space_in):
if spaceUserRole:
if spaceUserRole[0].role.name.upper() in ["SPACEADMIN"]:
is_admin = 1
account.cur_space=spaceUserRole[0].space.name
account.cur_space = spaceUserRole[0].space.name
account.save()
cur_space = account.cur_space
else:
Expand All @@ -57,37 +57,38 @@ def is_admin(account,cur_space_in):
else:
return {"cur_space":"","type":0,"is_supper":is_supper}

#@ensure_csrf_cookie
@csrf_exempt
@ensure_csrf_cookie
def login(request):
if request.method == "POST":
res = {}
username = request.POST.get("username")
password = request.POST.get("password")
email = username + "@baifendian.com"
ldap_user = ldap_get_vaild(username=username,passwd=password)
ldap_user = ldap_get_vaild(username=username, passwd=password)
if ldap_user:
user = authenticate(username=username, password=password)
if not user:
userAdd=User.objects.create_user(username, email, password)
userAdd.is_active=True
userAdd = User.objects.create_user(username, email, password)
userAdd.is_active = True
userAdd.save
user = authenticate(username=username, password=password)
if user:
auth_login(request, user)
account_list = Account.objects.filter(name=username)
if len(account_list) == 1:
account = account_list[0]
data = is_admin(account,account.cur_space)
data = is_admin(account, account.cur_space)
else:
if len(account_list) >1:
if len(account_list) > 1:
for one in account_list[1:]:
one.delete()
data = is_admin(account_list[0],account_list[0].cur_space)
data = is_admin(account_list[0], account_list[0].cur_space)
else:
account = Account(name=username,email=email,is_active=1)
account = Account(name=username, email=email, is_active=1)
account.role = Role.objects.get(name="guest")
account.save()
data = is_admin(account,account.cur_space)
data = is_admin(account, account.cur_space)
ac_logger.info("user:{0}".format(data))
res["code"] = 200
res["data"] = data
Expand All @@ -96,8 +97,6 @@ def login(request):
res["data"] = "username or password is error"
response = HttpResponse(content_type='application/json')
response.write(json.dumps(res))
#response.set_cookie('csrftoken',request.COOKIES.get('csrftoken',"S6ouKsk1kRrp5qsHlmd5fupVJewYitW3"))
response.set_cookie('csrftoken',"S6ouKsk1kRrp5qsHlmd5fupVJewYitW3")
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Methods"] = "POST,GET,PUT, DELETE"
return response
Expand All @@ -117,25 +116,17 @@ def login(request):
try:
account = Account.objects.get(name=username)
user = is_admin(account,account.cur_space)
#if not account.cur_space:
# spaceUserRole = SpaceUserRole.objects.filter(user=account)
# account.cur_space=spaceUserRole[0].space.name
# account.save()
#user = {"name":username,"type":1,"cur_space":account.cur_space}
except Exception,e:
ac_logger.error(e)
user = ""
else:
user = ""
user = json.dumps(user)
ac_logger.info("##########user:%s" %user)
response = render_to_response('index/index.html',locals())
# set default cookie value
#response.set_cookie('csrftoken',request.COOKIES.get('csrftoken','S6ouKsk1kRrp5qsHlmd5fupVJewYitW3'))
response.set_cookie('csrftoken',"S6ouKsk1kRrp5qsHlmd5fupVJewYitW3")
ac_logger.info("##########user:%s" %user)
response = render_to_response('index/index.html', locals())
return response

#@ensure_csrf_cookie
@ensure_csrf_cookie
def logout(request):
result = {}
try:
Expand All @@ -148,48 +139,47 @@ def logout(request):
result["data"] = "logout failed."
response = HttpResponse(content_type='application/json')
response.write(json.dumps(result))
response.set_cookie('csrftoken',"S6ouKsk1kRrp5qsHlmd5fupVJewYitW3")
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Methods"] = "POST,GET,PUT, DELETE"
return response

@ensure_csrf_cookie
def index(request):
ac_logger.info("######################cookie: {0}#######".format(request.COOKIES.get('csrftoken')))
#save cur_space
# save cur_space
user = request.user
cur_space = request.GET.get("cur_space","")
cur_space = request.GET.get("cur_space", "")
if user:
username = user.username
try:
account = Account.objects.get(name=username)
user = is_admin(account,cur_space)
except Exception,e:
user = is_admin(account, cur_space)
except Exception, e:
ac_logger.error(e)
user = ""
else:
user = ""
user = json.dumps(user)
return render_to_response('index/index.html',locals())
response = render_to_response('index/index.html', locals())
return response

def permission_check(request):
from django.contrib import admin
from django.conf.urls import patterns,url,include
from django.conf.urls import patterns, url, include
import urls
admin.autodiscover()
if request.META.has_key('HTTP_X_FORWARDED_FOR'):
ip = request.META['HTTP_X_FORWARDED_FOR']
ip = request.META['HTTP_X_FORWARDED_FOR']
else:
ip = request.META['REMOTE_ADDR']
whitelist = settings.WHITELIST_IP
temp = False
for i in whitelist:
#ac_logger.error('\n\n\n ip is :\n %s \n\n\n'%ip)
#ac_logger.error('\n\n\n whitelist ip is :\n %s \n\n\n'%i)
# ac_logger.error('\n\n\n ip is :\n %s \n\n\n'%ip)
# ac_logger.error('\n\n\n whitelist ip is :\n %s \n\n\n'%i)
if ip.startswith(i):
temp = True
break
if temp:
urls.urlpatterns[0] = url(r'^admin/', include(admin.site.urls))
else:
return HttpResponse('<h2>Permission Forbidden!</h2>')
return HttpResponse('<h2>Permission denied!</h2>')
17 changes: 9 additions & 8 deletions Aries/middleware/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,19 @@ def process_request(self, request):
path = request.path
print path
response = HttpResponse()
res = {}
if path.startswith('/static/') or path == "/login":
#static file type or /login
# static file type or /login
return None
if not request.user.is_authenticated():
if path.startswith('/v1/') or path.startswith('/openstack') or path.startswith('/k8s'):
#api type
res = {}
if path.startswith('/v1/'):
# api type
res["code"] = 401
res["data"] = "sesson failure!"
response.write(json.dumps(res))
return response
else:
# other
user = ""
user = json.dumps(user)
return render_to_response('index/index.html',locals())
# other
user = ""
user = json.dumps(user)
return render_to_response('index/index.html', locals())
10 changes: 3 additions & 7 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,15 @@ RUN mkdir -p /opt/bfdhadoop/tmp/data && \
RUN cd $SIRIUS_PATH/package/Aries && \
rm -rf node_modules && \
npm install && \
npm run build && \
cd $SIRIUS_PATH && \
cp -r package/Aries/build/* Aries/static/aries/ && \
rm -rf package/Aries/build && \
chmod +x $SIRIUS_PATH/docker-k8s/script/changejs.sh &&\
sh $SIRIUS_PATH/docker-k8s/script/changejs.sh
sh build.sh

RUN mkdir -p $SIRIUS_PATH/log &&\
mkdir -p $SIRIUS_PATH/download

RUN adduser hadoop && \
adduser bre && \
adduser bae
adduser bae && \
adduser openstack

VOLUME ["/opt/Sirius/log"]
VOLUME ["/opt/Sirius/download"]
Expand Down
23 changes: 23 additions & 0 deletions package/Aries/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#/bin/bash
npm run build
HOME=`dirname $(cd "$(dirname "$0")"; pwd)`
echo $HOME
indexHome="$HOME/../Aries/user_auth/templates/index/"
echo $indexHome
staticHome="$HOME/../Aries/static/aries/"
echo $staticHome
buildHome="$HOME/Aries/build/"
echo $buildHome
echo "rm -rf ${staticHome}/*"
echo ${buildHome}
echo "mv ${buildHome}/* ${staticHome}"
echo "mv ${HOME}/Aries/index.html ${indexHome}"
if [ -n "${staticHome}" ];then
rm -rf ${staticHome}/*
fi
if [ -n "${buildHome}" ];then
mv ${buildHome}/* ${staticHome}
fi
if [ -n "${HOME}" ];then
mv ${HOME}/Aries/index.html ${indexHome}
fi
25 changes: 17 additions & 8 deletions package/Aries/index.tpl
Original file line number Diff line number Diff line change
@@ -1,24 +1,33 @@
<!DOCTYPE html>
<# if (isProduction) { #>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
{% load staticfiles %}
<# } #>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<# if (isProduction) { #>
<link rel="icon" href="{% static 'images/bitbug_favicon_whit.ico' %}" type="image/x-icon">
<# } #>
<# if (isProduction) { #>
<link rel="shortcut icon" href="{% static 'images/bitbug_favicon_whit.ico' %}" type="image/x-icon">
<# } #>
<title>百分点云中心</title>
</head>
<body>
<# if (isProduction) { #>
<script>
// window.user = ${user}
window.user = {
name: 'demo'
}
{% autoescape off %}
window.user = {{user}};
{% endautoescape %}
</script>
<# } #>
<# }#>
<div id="app"></div>
<script src="<#= publicPath #>app<#= isProduction ? '.' + hash : '' #>.js"></script>
<# if (isProduction) { #>
<script src="{% static 'aries/app<#= isProduction ? '.' + hash : '' #>.js' %}"></script>
<# } else{ #>
<script src="<#= publicPath #>app<#= isProduction ? '.' + hash : '' #>.js"></script>
<# } #>
</body>
</html>
12 changes: 9 additions & 3 deletions package/Aries/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,15 @@ xhr.header = {
}
//xhr.baseUrl = 'http://172.24.3.64:10086/v1'
xhr.success = (res, option) => {
if (typeof res !== 'object') {
message.danger(option.url + ': response data should be JSON')
return
console.log(res);
if (typeof res !== 'object' ) {
try{
res = JSON.parse(res);
}catch(err){
console.log(err);
message.danger(option.url + ': response data should be JSON')
return
}
}
switch (res.code) {
case 200:
Expand Down
7 changes: 5 additions & 2 deletions package/Aries/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ var isProduction = option[0] === '-p'

// 删除 build 目录,防止开发模式下读取以及线上模式中的文件累积
rimraf.sync('./build')
//删除index.html文件,防止开发模式下读取
rimraf.sync('./index.html')

var config = {
entry: {
Expand All @@ -23,7 +25,8 @@ var config = {
chunkFilename: '[id]' + (isProduction ? '.[hash]' : '') + '.js',
//静态资源全路径
//publicPath: ((isProduction ? env.basePath : '') + '/build/').replace(/\/\//, '/')
publicPath: ((isProduction ? env.basePath : '') + '/static/aries/').replace(/\/\//, '/')
//publicPath: ((isProduction ? env.basePath : '') + '/static/aries/').replace(/\/\//, '/')
publicPath: isProduction ? (env.basePath+'/static/aries/').replace(/\/\//, '/') : (env.basePath+'/build/').replace(/\/\//, '/')
},
module: {
noParse: [],
Expand Down Expand Up @@ -92,7 +95,7 @@ config.plugins.push(function() {
isProduction: isProduction,
hash: isProduction ? stats.hash : ''
})
fs.writeFileSync(path.join(__dirname, 'index.' + (isProduction ? 'jsp' : 'ejs')), template)
fs.writeFileSync(path.join(__dirname, 'index.' + (isProduction ? 'html' : 'ejs')), template)
})
})

Expand Down
1 change: 0 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ django-bootstrap-tags==1.2.0
Django==1.8.6
djangorestframework-jsonp==1.0.2
requests==2.10.0
uWSGI==0.8
redis==2.10.3
paramiko==1.7.7.1
pycrypto==2.6
Expand Down

0 comments on commit c0924ea

Please sign in to comment.