summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorHongyuan Ma2018-07-08 03:50:28 +0000
committerHongyuan Ma2018-07-08 03:50:28 +0000
commit5cd2cf6cc7e236f4e9f7e63da162d9012eb9e3d1 (patch)
tree925e974753c0aaf4fa5ce9ae3e20d42b38fb7497
parent3c2fc9dfee3f0a6666d4ac67653ab82d3e1f6cca (diff)
add UnauthorizedCode
-rw-r--r--front-end/src/app.jsx2
-rw-r--r--front-end/src/component/nav-top/index.jsx22
-rw-r--r--front-end/src/page/portal/index.jsx16
-rw-r--r--front-end/src/service/user-service.jsx11
-rw-r--r--front-end/src/util/constant.jsx2
-rw-r--r--front-end/src/util/util.jsx48
-rw-r--r--web/apps/test_records/views.py1
-rw-r--r--web/apps/user_operation/views.py25
-rw-r--r--web/apps/util/__init__.py0
-rw-r--r--web/apps/util/exception_handler.py16
-rw-r--r--web/apps/util/response.py38
-rw-r--r--web/pgperffarm/settings.py15
-rw-r--r--web/pgperffarm/urls.py2
13 files changed, 144 insertions, 54 deletions
diff --git a/front-end/src/app.jsx b/front-end/src/app.jsx
index c2f23ec..78443b1 100644
--- a/front-end/src/app.jsx
+++ b/front-end/src/app.jsx
@@ -1,6 +1,6 @@
import React from 'react';
import ReactDom from 'react-dom';
-import {HashRouter as Router, Route, Link, Redirect, Switch} from 'react-router-dom';
+import {BrowserRouter as Router, Route, Link, Redirect, Switch} from 'react-router-dom';
import createHistory from 'history/createHashHistory'
const history = createHistory()
import {spring, AnimatedRoute, AnimatedSwitch} from 'react-router-transition';
diff --git a/front-end/src/component/nav-top/index.jsx b/front-end/src/component/nav-top/index.jsx
index 69157fc..f474075 100644
--- a/front-end/src/component/nav-top/index.jsx
+++ b/front-end/src/component/nav-top/index.jsx
@@ -18,13 +18,9 @@ class NavTop extends React.Component {
}
// logout
- onLogout(){
- _user.logout().then(res => {
- _util.removeStorage('userInfo');
- window.location.href = '/login';
- }, errMsg => {
- _util.errorTips(errMsg);
- });
+ onLogout() {
+ _util.removeStorage('userInfo');
+ window.location.href = '/login';
}
render() {
@@ -34,19 +30,20 @@ class NavTop extends React.Component {
if (isLoggedIn) {
button = <li className="dropdown loggedin">
<a className="dropdown-toggle" data-toggle="dropdown" href="#" aria-expanded="false">
- <img className="img-circle img-thumbnail user-head-pic" src={require('image/slonik.png')} alt="headPic"/>
+ <img className="img-circle img-thumbnail user-head-pic" src={require('image/slonik.png')}
+ alt="headPic"/>
</a>
<ul className="dropdown-menu dropdown-alerts loggedin-ul">
<li>
- <a href="#">
+ <Link to="/portal">
<div>
<i className="fa fa-tasks fa-fw"></i> My machines
</div>
- </a>
+ </Link>
</li>
<li className="divider"></li>
<li>
- <a href="#">
+ <a onClick={() => {this.onLogout()}}>
<div>
<i className="fa fa-upload fa-fw"></i> Log out
</div>
@@ -71,7 +68,8 @@ class NavTop extends React.Component {
Farm</b></a>
</div>
<ul className="nav navbar-top-links navbar-left">
- <li><Link to="/home"> <span className="glyphicon glyphicon-home" aria-hidden="true"></span> Home</Link>
+ <li><Link to="/home"> <span className="glyphicon glyphicon-home" aria-hidden="true"></span>
+ Home</Link>
</li>
<li><Link to="/status"><span className="glyphicon glyphicon-tasks" aria-hidden="true"></span>Status</Link>
</li>
diff --git a/front-end/src/page/portal/index.jsx b/front-end/src/page/portal/index.jsx
index fe4ecfe..3f9b6cb 100644
--- a/front-end/src/page/portal/index.jsx
+++ b/front-end/src/page/portal/index.jsx
@@ -32,7 +32,7 @@ class Portal extends React.Component {
userinfo: res.userinfo,
});
}, errMsg => {
- _mm.errorTips(errMsg);
+ _util.errorTips(errMsg);
});
}
@@ -44,9 +44,19 @@ class Portal extends React.Component {
isLoading: false
});
}, errMsg => {
- _mm.errorTips(errMsg);
+ _util.errorTips(errMsg);
});
}
+ onLogout(){
+ _util.removeStorage('userInfo');
+ window.location.href = '/login';
+ // _user.logout().then(res => {
+ // _util.removeStorage('userInfo');
+ // window.location.href = '/login';
+ // }, errMsg => {
+ // _util.errorTips(errMsg);
+ // });
+ }
render() {
let show = this.state.isLoading ? "none" : "block";
@@ -72,7 +82,7 @@ class Portal extends React.Component {
<a href="\add-machine" className="list-group-item">
<i className="fa fa-globe fa-fw"></i>&nbsp; Add a New Mchine
</a>
- <a href="\logout" className="list-group-item">
+ <a onClick={() => {this.onLogout()}} className="list-group-item">
<i className="fa fa-arrow-left fa-fw"></i>&nbsp; Logout
</a>
</div>
diff --git a/front-end/src/service/user-service.jsx b/front-end/src/service/user-service.jsx
index bbb600e..997632b 100644
--- a/front-end/src/service/user-service.jsx
+++ b/front-end/src/service/user-service.jsx
@@ -37,11 +37,12 @@ class User{
}
// logout
logout(){
- let url = PGConstant.base_url + '/logout';
- return _util.request({
- type : 'post',
- url : url
- });
+ // let url = PGConstant.base_url + '/logout';
+ // return _util.request({
+ // type : 'post',
+ // url : url
+ // });
+ return true;
}
getUserMachineManageList(pageNum){
diff --git a/front-end/src/util/constant.jsx b/front-end/src/util/constant.jsx
index 6e8c9a8..2c0e3fb 100644
--- a/front-end/src/util/constant.jsx
+++ b/front-end/src/util/constant.jsx
@@ -3,7 +3,7 @@ const object = {
name:'好123',
- USER_UNLOGIN_CODE:10,
+ UnauthorizedCode:401,// unlogin
};
export default object; \ No newline at end of file
diff --git a/front-end/src/util/util.jsx b/front-end/src/util/util.jsx
index 3492750..4c69ef9 100644
--- a/front-end/src/util/util.jsx
+++ b/front-end/src/util/util.jsx
@@ -1,50 +1,58 @@
-
import PGConstant from 'util/constant.jsx'
// const _const = new PGConstant();
class PGUtil {
request(param) {
return new Promise((resolve, reject) => {
let user = this.getStorage('userInfo')
+ let beforeSendFunc = (xhr) => {}
+ if (user.token) {
+ beforeSendFunc = (xhr) => xhr.setRequestHeader("Authorization", 'Token ' + user.token);
+ }
$.ajax({
type: param.type || 'get',
url: param.url || '',
dataType: param.dataType || 'json',
data: param.data || null,
- headers:{
- 'Authorization': 'Token ' + user.token
- },
+ // headers: {
+ // 'Authorization': 'Token ' + user.token
+ // },
+ beforeSend: beforeSendFunc,
success: res => {
// request success
-
+ console.dir(res)
typeof resolve === 'function' && resolve(res, res.msg);
if (0 === res.status) {
typeof resolve === 'function' && resolve(res.data, res.msg);
- }
- // nologin force to login
- else if (PGConstant.USER_UNLOGIN_CODE === res.status) {
- this.doLogin();
- }
- else {
+ } else {
typeof reject === 'function' && reject(res.msg || res.data);
}
},
error: err => {
- typeof reject === 'function' && reject(err.statusText);
+ console.log('here is err')
+ console.dir(err.status)
+ // nologin force to login
+ if (PGConstant.UnauthorizedCode === err.status) {
+ this.doLogin();
+ } else {
+ typeof reject === 'function' && reject(err.statusText);
+ }
+
}
});
});
}
// redirect to login
- doLogin(){
+ doLogin() {
window.location.href = '/login?redirect=' + encodeURIComponent(window.location.pathname);
+ // window.location.href = '/login';
}
- getUrlParam(name){
+ getUrlParam(name) {
// param=123&param1=456
let queryString = window.location.search.split('?')[1] || '',
- reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"),
- result = queryString.match(reg);
+ reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"),
+ result = queryString.match(reg);
return result ? decodeURIComponent(result[2]) : null;
}
@@ -93,11 +101,11 @@ class PGUtil {
getDateStr(AddDayCount) {
let dd = new Date();
- dd.setDate(dd.getDate()+AddDayCount);
+ dd.setDate(dd.getDate() + AddDayCount);
let y = dd.getFullYear();
- let m = (dd.getMonth()+1)<10?"0"+(dd.getMonth()+1):(dd.getMonth()+1);
- let d = dd.getDate()<10?"0"+dd.getDate():dd.getDate();
- return y+"-"+m+"-"+d;
+ let m = (dd.getMonth() + 1) < 10 ? "0" + (dd.getMonth() + 1) : (dd.getMonth() + 1);
+ let d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
+ return y + "-" + m + "-" + d;
}
}
diff --git a/web/apps/test_records/views.py b/web/apps/test_records/views.py
index e5fcfa3..10ce25f 100644
--- a/web/apps/test_records/views.py
+++ b/web/apps/test_records/views.py
@@ -36,6 +36,7 @@ class TestRecordListViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
"""
List test records
"""
+
queryset = TestRecord.objects.all().order_by('add_time')
serializer_class = TestRecordListSerializer
pagination_class = StandardResultsSetPagination
diff --git a/web/apps/user_operation/views.py b/web/apps/user_operation/views.py
index fb46d05..6c2d71a 100644
--- a/web/apps/user_operation/views.py
+++ b/web/apps/user_operation/views.py
@@ -2,11 +2,13 @@
from __future__ import unicode_literals
from django.shortcuts import render
-from rest_framework import mixins, viewsets, permissions
+from rest_framework import mixins, viewsets, permissions, status
from rest_framework import authentication
+from rest_framework.response import Response
+from rest_framework.views import APIView
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
-
+from util.response import PGJsonResponse
from models import UserMachine
from serializer import UserMachineManageSerializer
@@ -21,12 +23,25 @@ class UserMachineListViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
serializer_class = UserMachineManageSerializer
# pagination_class = StandardResultsSetPagination
+
+
+# class UserMachineList(APIView):
+# authentication_classes = (JSONWebTokenAuthentication,)
+# permission_classes = (permissions.IsAuthenticated,)
+#
+# def get(self, request, format=None):
+# machines = UserMachine.objects.all().order_by('add_time')
+# serializer = UserMachineManageSerializer(machines, many=True)
+#
+# return PGJsonResponse(data=serializer.data, code=status.HTTP_200_OK, desc='get user machine list success')
+
+
class UserMachinePermission(permissions.BasePermission):
"""
- Machine permission check
+ Machine upload permission check
"""
def has_permission(self, request, view):
secret = request.data.secret
- ret = UserMachine.objects.filter(machine_secret=secret,is_active=1).exists()
- return ret \ No newline at end of file
+ ret = UserMachine.objects.filter(machine_secret=secret, is_active=1).exists()
+ return ret
diff --git a/web/apps/util/__init__.py b/web/apps/util/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/web/apps/util/__init__.py
diff --git a/web/apps/util/exception_handler.py b/web/apps/util/exception_handler.py
new file mode 100644
index 0000000..b5d4e62
--- /dev/null
+++ b/web/apps/util/exception_handler.py
@@ -0,0 +1,16 @@
+from rest_framework.views import exception_handler
+
+
+def custom_exception_handler(exc, context):
+ # Call REST framework's default exception handler first,
+ # to get the standard error response.
+ response = exception_handler(exc, context)
+
+ # Now add the HTTP status code to the response.
+ if response is not None:
+ response.data['code'] = response.status_code
+ response.data['desc'] = response.data['detail']
+ # response.data['data'] = None #可以存在
+ del response.data['detail'] # 删除detail字段
+
+ return response
diff --git a/web/apps/util/response.py b/web/apps/util/response.py
new file mode 100644
index 0000000..c47f41b
--- /dev/null
+++ b/web/apps/util/response.py
@@ -0,0 +1,38 @@
+from django.utils import six
+from rest_framework.response import Response
+from rest_framework.serializers import Serializer
+
+class PGJsonResponse(Response):
+ """
+ An HttpResponse that allows its data to be rendered into
+ arbitrary media types.
+ """
+
+ def __init__(self, data=None, code=None, desc=None,
+ status=None,
+ template_name=None, headers=None,
+ exception=False, content_type=None):
+ """
+ Alters the init arguments slightly.
+ For example, drop 'template_name', and instead use 'data'.
+ Setting 'renderer' and 'media_type' will typically be deferred,
+ For example being set automatically by the `APIView`.
+ """
+ super(Response, self).__init__(None, status=status)
+
+ if isinstance(data, Serializer):
+ msg = (
+ 'You passed a Serializer instance as data, but '
+ 'probably meant to pass serialized `.data` or '
+ '`.error`. representation.'
+ )
+ raise AssertionError(msg)
+
+ self.data = {"code": code, "desc": desc, "data": data}
+ self.template_name = template_name
+ self.exception = exception
+ self.content_type = content_type
+
+ if headers:
+ for name, value in six.iteritems(headers):
+ self[name] = value \ No newline at end of file
diff --git a/web/pgperffarm/settings.py b/web/pgperffarm/settings.py
index 2a62143..d3b5f42 100644
--- a/web/pgperffarm/settings.py
+++ b/web/pgperffarm/settings.py
@@ -132,7 +132,9 @@ REST_FRAMEWORK = {
# ),
# 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
-
+ # 'EXCEPTION_HANDLER': (
+ # 'dataAPI.common.api_exception.custom_exception_handler'
+ # ),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.BasicAuthentication',
@@ -144,9 +146,9 @@ REST_FRAMEWORK = {
}
DB_ENUM = {
- "mode":{
- "simple":1,
- "other":2
+ "mode": {
+ "simple": 1,
+ "other": 2
},
"status": {
"none": -1,
@@ -158,7 +160,6 @@ DB_ENUM = {
APPEND_SLAS = False
-
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
@@ -192,7 +193,7 @@ ALLOWED_HOSTS = ['*']
JWT_AUTH = {
'JWT_RESPONSE_PAYLOAD_HANDLER':
- 'users.jwt_handler.jwt_response_payload_handler',
+ 'users.jwt_handler.jwt_response_payload_handler',
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=7200),
'JWT_AUTH_HEADER_PREFIX': 'Token',
-} \ No newline at end of file
+}
diff --git a/web/pgperffarm/urls.py b/web/pgperffarm/urls.py
index e3b3d52..e9a659d 100644
--- a/web/pgperffarm/urls.py
+++ b/web/pgperffarm/urls.py
@@ -58,6 +58,8 @@ urlpatterns = [
# url(r'status/$', TestListView.as_view(), name='test-list'),
# url(r'detail', TestRecordDetailViewSet ,name="detail"),
url(r'upload/$', TestRecordCreate, name='test-upload'),
+ # url(r'my-machine/$', UserMachineList.as_view(), name='my-machine'),
+
url(r'docs/', include_docs_urls(title='pgperffarm')),
# Static pages
# url(r'^$', 'pgperffarm.views.index', name='index'),