Explorar el Código

dashboard require login

laiwei hace 8 años
padre
commit
e838015b6c

+ 2 - 1
rrd/__init__.py

@@ -1,5 +1,6 @@
 #-*- coding:utf-8 -*-
 import os
+import traceback
 from flask import Flask
 
 #-- create app --
@@ -8,7 +9,7 @@ app.config.from_object("rrd.config")
 
 @app.errorhandler(Exception)
 def all_exception_handler(error):
-    print "exception: %s" %error
+    print traceback.format_exc()
     return u'dashboard 暂时无法访问,请联系管理员', 500
 
 from view import index

+ 1 - 1
rrd/config.py

@@ -2,7 +2,7 @@
 import os
 
 #-- app config --
-DEBUG = True
+LOG_LEVEL = 'debug'
 SECRET_KEY = "secret-key"
 PERMANENT_SESSION_LIFETIME = 3600 * 24 * 30
 SITE_COOKIE = "open-falcon-ck"

+ 4 - 3
rrd/corelib/__init__.py

@@ -2,12 +2,13 @@
 import requests
 import json
 
-def auth_requests(user_token, method, *args, **kwargs):
-    if not user_token:
+def auth_requests(method, *args, **kwargs):
+    from flask import g
+    if not g.user_token:
         raise Exception("no api token")
 
     headers = {
-            "Apitoken": json.dumps({"name":user_token.name, "sig":user_token.sig})
+        "Apitoken": json.dumps({"name":g.user_token.name, "sig":g.user_token.sig})
     }
 
     if not kwargs:

+ 14 - 28
rrd/model/graph.py

@@ -1,7 +1,7 @@
 #-*- coding:utf-8 -*-
 import json
-import requests
 from rrd.config import API_ADDR
+from rrd import corelib
 
 class DashboardGraph(object):
     def __init__(self, id, title, hosts, counters, screen_id,
@@ -23,18 +23,20 @@ class DashboardGraph(object):
 
     @classmethod
     def gets_by_screen_id(cls, screen_id):
-        r = requests.get(API_ADDR + "/dashboard/graphs/screen/%s" %(screen_id,))
+        h = {"Content-type": "application/json"}
+        r = corelib.auth_requests("GET", API_ADDR + "/dashboard/graphs/screen/%s" %(screen_id,), headers=h)
         if r.status_code != 200:
-            return
+            raise Exception(r.text)
         j = r.json()
         return [cls(*[x["graph_id"], x["title"], x["endpoints"], x["counters"], \
                 x["screen_id"], x["timespan"], x["graph_type"], x["method"], x["position"]]) for x in j]
 
     @classmethod
     def get(cls, id):
-        r = requests.get(API_ADDR + "/dashboard/graph/%s" %(id,))
+        h = {"Content-type": "application/json"}
+        r = corelib.auth_requests("GET", API_ADDR + "/dashboard/graph/%s" %(id,), headers=h)
         if r.status_code != 200:
-            return
+            raise Exception(r.text)
         x = r.json()
         return x and cls(*[x["graph_id"], x["title"], x["endpoints"], x["counters"], \
                 x["screen_id"], x["timespan"], x["graph_type"], x["method"], x["position"]])
@@ -55,9 +57,9 @@ class DashboardGraph(object):
             "falcon_tags": "",
         }
         h = {"Content-type": "application/json"}
-        r = requests.post(API_ADDR + "/dashboard/graph", data = json.dumps(d), headers =h )
+        r = corelib.auth_requests("POST", API_ADDR + "/dashboard/graph", data = json.dumps(d), headers =h )
         if r.status_code != 200:
-            return
+            raise Exception(r.text)
         j = r.json()
 
         graph_id = j and j.get("id")
@@ -65,9 +67,10 @@ class DashboardGraph(object):
 
     @classmethod
     def remove(cls, id):
-        r = requests.delete(API_ADDR + "/dashboard/graph/%s" %(id,))
+        h = {"Content-type": "application/json"}
+        r = corelib.auth_requests("DELETE", API_ADDR + "/dashboard/graph/%s" %(id,), headers=h)
         if r.status_code != 200:
-            return
+            raise Exception(r.text)
         return r.json()
 
     def update(self, title=None, hosts=None, counters=None, screen_id=None,
@@ -94,9 +97,9 @@ class DashboardGraph(object):
             "falcon_tags": "",
         }
         h = {"Content-type": "application/json"}
-        r = requests.put(API_ADDR + "/dashboard/graph/%s" %(self.id,), data = json.dumps(d), headers =h )
+        r = corelib.auth_requests("PUT", API_ADDR + "/dashboard/graph/%s" %(self.id,), data = json.dumps(d), headers =h )
         if r.status_code != 200:
-            return
+            raise Exception(r.text)
         j = r.json()
 
         graph_id = j and j.get("id")
@@ -111,20 +114,3 @@ class DashboardGraph(object):
             grh = cls.get(id)
             grh and grh.update(hosts=hosts, counters=counters)
         
-
-
-'''
-CREATE TABLE `dashboard_graph` (
-  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
-  `title` char(128) NOT NULL,
-  `hosts` varchar(10240) NOT NULL DEFAULT '',
-  `counters` varchar(1024) NOT NULL DEFAULT '',
-  `screen_id` int(11) unsigned NOT NULL,
-  `timespan` int(11) unsigned NOT NULL DEFAULT '3600',
-  `graph_type` char(2) NOT NULL DEFAULT 'h',
-  `method` char(8) DEFAULT '',
-  `position` int(11) unsigned NOT NULL DEFAULT 0,
-  PRIMARY KEY (`id`),
-  KEY `idx_sid` (`screen_id`)
-) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
-'''

+ 21 - 15
rrd/model/screen.py

@@ -1,7 +1,7 @@
 #-*- coding:utf-8 -*-
 import json
-import requests
 from rrd.config import API_ADDR
+from rrd import corelib
 
 class DashboardScreen(object):
     def __init__(self, id, pid, name):
@@ -15,9 +15,10 @@ class DashboardScreen(object):
 
     @classmethod
     def get(cls, id):
-        r = requests.get(API_ADDR + "/dashboard/screen/%s" %(id,))
+        h = {"Content-type": "application/json"}
+        r = corelib.auth_requests("GET", API_ADDR + "/dashboard/screen/%s" %(id,), headers=h)
         if r.status_code != 200:
-            return
+            raise Exception(r.text)
         j = r.json()
         if j:
             row = [j["id"], j["pid"], j["name"]]
@@ -25,34 +26,38 @@ class DashboardScreen(object):
 
     @classmethod
     def gets_by_pid(cls, pid):
-        r = requests.get(API_ADDR + "/dashboard/screens/pid/%s" %(pid,))
+        h = {"Content-type": "application/json"}
+        r = corelib.auth_requests("GET", API_ADDR + "/dashboard/screens/pid/%s" %(pid,), headers=h)
         if r.status_code != 200:
-            return
-        j = r.json()
+            raise Exception(r.text)
+        j = r.json() or []
         return [cls(*[x["id"], x["pid"], x["name"]]) for x in j]
 
     @classmethod
     def gets_all(cls, limit=500):
-        r = requests.get(API_ADDR + "/dashboard/screens?limit=%s" %(limit,))
+        h = {"Content-type": "application/json"}
+        r = corelib.auth_requests("GET", API_ADDR + "/dashboard/screens?limit=%s" %(limit,), headers=h)
         if r.status_code != 200:
-            return
-        j = r.json()
+            raise Exception(r.text)
+        j = r.json() or []
         return [cls(*[x["id"], x["pid"], x["name"]]) for x in j]
 
     @classmethod
     def add(cls, pid, name):
         d = {"pid": pid, "name": name}
-        r = requests.post(API_ADDR + "/dashboard/screen", data = d)
+        h = {"Content-type": "application/json"}
+        r = corelib.auth_requests("POST", API_ADDR + "/dashboard/screen", data = d, headers=h)
         if r.status_code != 200:
-            return
+            raise Exception(r.text)
         j = r.json()
         return cls(*[j["id"], j["pid"], j["name"]])
 
     @classmethod
     def remove(cls, id):
-        r = requests.delete(API_ADDR + "/dashboard/screen/%s" %(id,))
+        h = {"Content-type": "application/json"}
+        r = corelib.auth_requests("DELETE", API_ADDR + "/dashboard/screen/%s" %(id,), headers=h)
         if r.status_code != 200:
-            return
+            raise Exception(r.text)
         return r.json()
 
     def update(self, pid=None, name=None):
@@ -62,7 +67,8 @@ class DashboardScreen(object):
         if name:
             d["name"] = name
 
-        r = requests.put(API_ADDR + "/dashboard/screen/%s" %self.id, data = d)
+        h = {"Content-type": "application/json"}
+        r = corelib.auth_requests("PUT", API_ADDR + "/dashboard/screen/%s" %self.id, data = d, headers=h)
         if r.status_code != 200:
-            return
+            raise Exception(r.text)
         return r.json()

+ 7 - 17
rrd/model/tmpgraph.py

@@ -1,7 +1,7 @@
 #-*- coding:utf-8 -*-
 import json
-import requests
 from rrd.config import API_ADDR
+from rrd import corelib
 
 class TmpGraph(object):
     def __init__(self, id, endpoints, counters):
@@ -17,9 +17,10 @@ class TmpGraph(object):
 
     @classmethod
     def get(cls, id):
-        r = requests.get(API_ADDR + "/dashboard/tmpgraph/%s" %(id,))
+        h = {"Content-type": "application/json"}
+        r = corelib.auth_requests("GET", API_ADDR + "/dashboard/tmpgraph/%s" %(id,), headers=h)
         if r.status_code != 200:
-            return
+            raise Exception(r.text)
 
         j = r.json()
         return j and cls(*[id, j["endpoints"], j["counters"]])
@@ -31,22 +32,11 @@ class TmpGraph(object):
             "endpoints": endpoints,
             "counters": counters,
         }
-        headers = {'Content-type': 'application/json'}
-        r = requests.post(API_ADDR + "/dashboard/tmpgraph", headers=headers, data=json.dumps(d))
+        h = {'Content-type': 'application/json'}
+        r = corelib.auth_requests("POST", API_ADDR + "/dashboard/tmpgraph", headers=h, data=json.dumps(d))
         if r.status_code != 200:
-            return
+            raise Exception(r.text)
 
         j = r.json()
         return j and j.get('id')
 
-'''
-CREATE TABLE `tmp_graph` (
-`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
-`endpoints` varchar(10240) NOT NULL DEFAULT '',
-`counters` varchar(10240) NOT NULL DEFAULT '',
-`ck` varchar(32) NOT NULL,
-`time_` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
-PRIMARY KEY (`id`),
-UNIQUE KEY `idx_ck` (`ck`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8
-'''

+ 5 - 4
rrd/templates/navbar.html

@@ -15,12 +15,13 @@
           <li><a href="/nodata">Nodata</a></li>
           <li><a href="/alarm-dash">Alarm-Dashboard</a></li>
           <li class="dropdown">
-              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">链接<span class="caret"></span></a>
+              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
+                  {%if g.user%}{{g.user.name}}{%else%}Sign in{%endif%}<span class="caret"></span></a>
               <ul class="dropdown-menu" role="menu" style="font-size:12px;">
-                  <li><a href="">Profile</a></li>
-                  <li><a href="">Users</a></li>
-                  <li><a href="">Teams</a></li>
                   {%if g.user%}
+                      <li><a href="/user/profile">Profile</a></li>
+                      <li><a href="/user/list">Users</a></li>
+                      <li><a href="/team/list">Teams</a></li>
                       <li><a href="/auth/logout">Logout</a></li>
                   {%else%}
                       <li><a href="/auth/login">Login</a></li>

+ 0 - 1
rrd/utils/graph_urls.py

@@ -1,5 +1,4 @@
 #-*- coding:utf-8 -*-
-import requests
 import json
 import copy
 import re

+ 2 - 2
rrd/utils/rrdgraph.py

@@ -1,7 +1,7 @@
 #-*- coding:utf-8 -*-
-import requests
 from rrd.config import API_ADDR
 import json
+from rrd import corelib
 
 def graph_history(endpoints, counters, cf, start, end):
     #TODO:step
@@ -13,7 +13,7 @@ def graph_history(endpoints, counters, cf, start, end):
         "counters": counters,
     }
     h = {"Content-type": "application/json"}
-    r = requests.post("%s/graph/history" %API_ADDR, headers=h, data=json.dumps(params))
+    r = corelib.auth_requests("POST", "%s/graph/history" %API_ADDR, headers=h, data=json.dumps(params))
     if r.status_code != 200:
         raise Exception("{} : {}".format(r.status_code, r.text))
 

+ 9 - 3
rrd/view/api.py

@@ -1,11 +1,13 @@
 #-*- coding:utf-8 -*-
 import json
-import requests
 from flask import request, abort, g
 from rrd import app, config
+from rrd import corelib
+from rrd.view.utils import require_login_json
 
 #done, TODO:query by tags
 @app.route("/api/endpoints")
+@require_login_json()
 def api_endpoints():
     ret = {
             "ok": False,
@@ -22,7 +24,8 @@ def api_endpoints():
         ret["msg"] = "no query params given"
         return json.dumps(ret)
 
-    r = requests.get(config.API_ADDR + "/graph/endpoint?q=%s&limit=%s&tags=%s" %(q, limit, tags))
+    h = {"Content-type": "application/json"}
+    r = corelib.auth_requests("GET", config.API_ADDR + "/graph/endpoint?q=%s&limit=%s&tags=%s" %(q, limit, tags), headers=h)
     if r.status_code != 200:
         abort(400, r.text)
 
@@ -36,6 +39,7 @@ def api_endpoints():
 
 #done
 @app.route("/api/counters", methods=["POST"])
+@require_login_json()
 def api_get_counters():
     ret = {
             "ok": False,
@@ -52,7 +56,9 @@ def api_get_counters():
         ret['msg'] = "no endpoints or counter given"
         return json.dumps(ret)
 
-    r = requests.get(config.API_ADDR + "/graph/endpoint_counter?eid=%s&metricQuery=%s&limit=%s" %(",".join(eids), q, limit))
+
+    h = {"Content-type": "application/json"}
+    r = corelib.auth_requests("GET", config.API_ADDR + "/graph/endpoint_counter?eid=%s&metricQuery=%s&limit=%s" %(",".join(eids), q, limit), headers=h)
     if r.status_code != 200:
         abort(400, r.text)
     j = r.json()

+ 8 - 0
rrd/view/chart.py

@@ -8,8 +8,10 @@ from rrd.consts import GRAPH_TYPE_KEY, GRAPH_TYPE_HOST
 from rrd.utils.rrdgraph import merge_list
 from rrd.utils.rrdgraph import graph_history
 from rrd.model.tmpgraph import TmpGraph
+from rrd.view.utils import require_login, require_login_json, require_login_abort
 
 @app.route("/chart", methods=["POST",])
+@require_login_json()
 def chart():
     endpoints = request.form.getlist("endpoints[]") or []
     counters = request.form.getlist("counters[]") or []
@@ -28,10 +30,12 @@ def chart():
     return json.dumps(ret)
 
 @app.route("/chart/big", methods=["GET",])
+@require_login()
 def chart_big():
     return render_template("chart/big_ng.html", **locals())
 
 @app.route("/chart/embed", methods=["GET",])
+@require_login()
 def chart_embed():
     w = request.args.get("w")
     w = int(w) if w else 600
@@ -40,6 +44,7 @@ def chart_embed():
     return render_template("chart/embed.html", **locals())
 
 @app.route("/chart/h", methods=["GET"])
+@require_login_abort()
 def multi_endpoints_chart_data():
     if not g.id:
         abort(400, "no graph id given")
@@ -116,6 +121,7 @@ def multi_endpoints_chart_data():
     return json.dumps(ret)
 
 @app.route("/chart/k", methods=["GET"])
+@require_login_abort()
 def multi_counters_chart_data():
     if not g.id:
         abort(400, "no graph id given")
@@ -192,6 +198,7 @@ def multi_counters_chart_data():
     return json.dumps(ret)
 
 @app.route("/chart/a", methods=["GET"])
+@require_login_abort()
 def multi_chart_data():
     if not g.id:
         abort(400, "no graph id given")
@@ -266,6 +273,7 @@ def multi_chart_data():
     return json.dumps(ret)
 
 @app.route("/charts", methods=["GET"])
+@require_login_abort()
 def charts():
     if not g.id:
         abort(400, "no graph id given")

+ 13 - 2
rrd/view/screen.py

@@ -1,7 +1,6 @@
 #-*- coding:utf-8 -*-
 import json
 import copy
-import requests
 import json
 from flask import render_template, abort, request, url_for, redirect, g
 import time
@@ -13,15 +12,18 @@ from rrd.model.graph import DashboardGraph
 from rrd import consts
 from rrd.utils.graph_urls import generate_graph_urls 
 from rrd import config
+from rrd.view.utils import require_login, require_login_json
 
 @app.route("/screen", methods=["GET", "POST"])
+@require_login()
 def dash_screens():
-    top_screens = DashboardScreen.gets_by_pid(pid='0')
+    top_screens = DashboardScreen.gets_by_pid(pid='0') or []
     top_screens = sorted(top_screens, key=lambda x:x.name)
 
     return render_template("screen/index.html", **locals())
 
 @app.route("/screen/<int:sid>/delete")
+@require_login()
 def dash_screen_delete(sid):
     screen = DashboardScreen.get(sid)
     if not screen:
@@ -31,6 +33,7 @@ def dash_screen_delete(sid):
     return redirect("/screen")
 
 @app.route("/screen/<int:sid>/edit", methods=["GET", "POST"])
+@require_login()
 def dash_screen_edit(sid):
     screen = DashboardScreen.get(sid)
     if not screen:
@@ -44,6 +47,7 @@ def dash_screen_edit(sid):
         return render_template("screen/edit.html", **locals())
 
 @app.route("/screen/<int:sid>/clone", methods=["GET", "POST"])
+@require_login()
 def dash_screen_clone(sid):
     screen = DashboardScreen.get(sid)
     if not screen:
@@ -68,6 +72,7 @@ def dash_screen_clone(sid):
         return render_template("screen/clone.html", **locals())
 
 @app.route("/graph/<int:gid>/delete")
+@require_login()
 def dash_graph_delete(gid):
     graph = DashboardGraph.get(gid)
     if not graph:
@@ -76,6 +81,7 @@ def dash_graph_delete(gid):
     return redirect("/screen/" + graph.screen_id)
 
 @app.route("/screen/<int:sid>")
+@require_login()
 def dash_screen(sid):
     start = request.args.get("start")
     end = request.args.get("end")
@@ -107,6 +113,7 @@ def dash_screen(sid):
     return render_template("screen/screen.html", **locals())
 
 @app.route("/screen/embed/<int:sid>")
+@require_login()
 def dash_screen_embed(sid):
     start = request.args.get("start")
     end = request.args.get("end")
@@ -130,6 +137,7 @@ def dash_screen_embed(sid):
 
 
 @app.route("/screen/add", methods=["GET", "POST"])
+@require_login()
 def dash_screen_add():
     if request.method == "POST":
         name = request.form.get("screen_name")
@@ -142,6 +150,7 @@ def dash_screen_add():
         return render_template("screen/add.html", **locals())
 
 @app.route("/screen/<int:sid>/graph", methods=["GET", "POST"])
+@require_login()
 def dash_graph_add(sid):
     all_screens = DashboardScreen.gets_all()
     top_screens = [x for x in all_screens if x.pid == '0']
@@ -180,6 +189,7 @@ def dash_graph_add(sid):
         return render_template("screen/graph_add.html", config=config, **locals())
 
 @app.route("/graph/<int:gid>/edit", methods=["GET", "POST"])
+@require_login()
 def dash_graph_edit(gid):
     error = ""
     graph = DashboardGraph.get(gid)
@@ -229,6 +239,7 @@ def dash_graph_edit(gid):
         return render_template("screen/graph_edit.html", **locals())
 
 @app.route("/graph/multi_edit", methods=["GET", "POST"])
+@require_login()
 def dash_graph_multi_edit():
     ret = {
             "ok": False,

+ 8 - 8
rrd/view/team.py

@@ -3,7 +3,7 @@ import json
 from flask import request, g, abort, render_template
 from rrd import app
 from rrd import config, corelib
-from rrd.view.utils import require_login
+from rrd.view.utils import require_login, require_login_json
 from rrd.model.team import Team
 from rrd.model.user import User
 
@@ -14,7 +14,7 @@ def team_users(team_id):
         ret = {"msg":""}
 
         h = {"Content-type": "application/json"}
-        r = corelib.auth_requests(g.user_token, "GET", "%s/team/%s" \
+        r = corelib.auth_requests("GET", "%s/team/%s" \
                 %(config.API_ADDR, team_id), headers=h)
         if r.status_code != 200:
             ret["msg"] = r.text
@@ -44,7 +44,7 @@ def team_list():
             }
 
         h = {"Content-type": "application/json"}
-        r = corelib.auth_requests(g.user_token, "GET", "%s/team" \
+        r = corelib.auth_requests("GET", "%s/team" \
                 %(config.API_ADDR,), params=d, headers=h)
         if r.status_code != 200:
             abort(400, "request to api fail: %s" %(r.text,))
@@ -81,7 +81,7 @@ def team_create():
         d = {
                 "team_name": name, "resume": resume, "users": user_ids,
         }
-        r = corelib.auth_requests(g.user_token ,"POST", "%s/team" %(config.API_ADDR,), \
+        r = corelib.auth_requests("POST", "%s/team" %(config.API_ADDR,), \
                 data=json.dumps(d), headers=h)
         if r.status_code != 200:
             ret["msg"] = r.text
@@ -94,7 +94,7 @@ def team_edit(team_id):
     if request.method == "GET":
 
         h = {"Content-type": "application/json"}
-        r = corelib.auth_requests(g.user_token, "GET", "%s/team/%s" \
+        r = corelib.auth_requests("GET", "%s/team/%s" \
                 %(config.API_ADDR, team_id), headers=h)
         if r.status_code != 200:
             abort(r.status_code, r.text)
@@ -118,7 +118,7 @@ def team_edit(team_id):
         d = {
                 "team_id": team_id, "resume": resume, "users": user_ids,
         }
-        r = corelib.auth_requests(g.user_token ,"PUT", "%s/team" %(config.API_ADDR,), \
+        r = corelib.auth_requests("PUT", "%s/team" %(config.API_ADDR,), \
                 data=json.dumps(d), headers=h)
         if r.status_code != 200:
             ret["msg"] = r.text
@@ -126,13 +126,13 @@ def team_edit(team_id):
         return json.dumps(ret)
 
 @app.route("/team/<int:team_id>/delete", methods=["POST"])
-@require_login(json_msg = "login first")
+@require_login_json()
 def team_delete(team_id):
     if request.method == "POST":
         ret = {"msg": ""}
         
         h = {"Content-type": "application/json"}
-        r = corelib.auth_requests(g.user_token, "DELETE", "%s/team/%s" \
+        r = corelib.auth_requests("DELETE", "%s/team/%s" \
                 %(config.API_ADDR, team_id), headers=h)
         if r.status_code != 200:
             ret['msg'] = "%s:%s" %(r.status_code, r.text)

+ 18 - 18
rrd/view/user.py

@@ -4,7 +4,7 @@ from flask import request, g, abort, render_template
 from rrd import app
 from rrd import corelib
 from rrd import config
-from rrd.view.utils import require_login
+from rrd.view.utils import require_login, require_login_json 
 from rrd.model.user import User
 
 @app.route("/user/about/<username>", methods=["GET",])
@@ -12,14 +12,14 @@ from rrd.model.user import User
 def user_info(username):
     if request.method == "GET":
         h = {"Content-type": "application/json"}
-        r = corelib.auth_requests(g.user_token, "GET", "%s/user/u/%s" %(config.API_ADDR, username), headers=h)
+        r = corelib.auth_requests("GET", "%s/user/u/%s" %(config.API_ADDR, username), headers=h)
         if r.status_code != 200:
             abort(400, "%s:%s" %(r.status_code, r.text))
         user_info = r.json()
         return render_template("user/about.html", **locals())
 
 @app.route("/user/profile", methods=["GET", "POST"])
-@require_login(json_msg = "please login first")
+@require_login()
 def user_profile():
     if request.method == "GET":
         current_user = g.user
@@ -45,7 +45,7 @@ def user_profile():
                 "qq": qq,
         }
 
-        r = corelib.auth_requests(g.user_token, "PUT", "%s/user/update" %(config.API_ADDR,), \
+        r = corelib.auth_requests("PUT", "%s/user/update" %(config.API_ADDR,), \
                 data=json.dumps(d), headers=h)
         if r.status_code != 200:
             ret["msg"] = r.text
@@ -53,7 +53,7 @@ def user_profile():
         return json.dumps(ret)
 
 @app.route("/user/chpwd", methods=["POST", ])
-@require_login(json_msg = "please login first")
+@require_login_json()
 def user_change_passwd():
     if request.method == "POST":
         ret = {"msg": ""}
@@ -75,7 +75,7 @@ def user_change_passwd():
             "new_password": new_password,
         }
 
-        r = corelib.auth_requests(g.user_token, "PUT", "%s/user/cgpasswd" %(config.API_ADDR,), \
+        r = corelib.auth_requests("PUT", "%s/user/cgpasswd" %(config.API_ADDR,), \
                 data=json.dumps(d), headers=h)
         if r.status_code != 200:
             ret['msg'] = r.text
@@ -95,7 +95,7 @@ def user_list():
                     "page": g.page or 1,
             }
             h = {"Content-type":"application/json"}
-            r = corelib.auth_requests(g.user_token, "GET", "%s/user/users" \
+            r = corelib.auth_requests("GET", "%s/user/users" \
                     %(config.API_ADDR,), params=d, headers=h)
             if r.status_code != 200:
                 abort(400, "request to api fail: %s" %(r.text,))
@@ -107,7 +107,7 @@ def user_list():
         return render_template("user/list.html", **locals())
 
 @app.route("/user/query", methods=["GET",])
-@require_login(json_msg="login first")
+@require_login_json()
 def user_query():
     if request.method == "GET":
         query_term = request.args.get("query", "")
@@ -118,7 +118,7 @@ def user_query():
                     "page": g.page or 1,
             }
             h = {"Content-type":"application/json"}
-            r = corelib.auth_requests(g.user_token, "GET", "%s/user/users" \
+            r = corelib.auth_requests("GET", "%s/user/users" \
                     %(config.API_ADDR,), params=d, headers=h)
             if r.status_code != 200:
                 ret['msg'] = t.text
@@ -152,7 +152,7 @@ def user_create():
         d = {
                 "name": name, "cnname": cnname, "password": password, "email": email, "phone": phone, "im": im, "qq": qq,
         }
-        r = corelib.auth_requests(g.user_token ,"POST", "%s/user/create" %(config.API_ADDR,), \
+        r = corelib.auth_requests("POST", "%s/user/create" %(config.API_ADDR,), \
                 data=json.dumps(d), headers=h)
         if r.status_code != 200:
             ret["msg"] = r.text
@@ -168,7 +168,7 @@ def admin_user_edit(user_id):
             abort(403, "no such privilege")
 
         h = {"Content-type":"application/json"}
-        r = corelib.auth_requests(g.user_token ,"GET", "%s/user/u/%s" %(config.API_ADDR, user_id), headers=h)
+        r = corelib.auth_requests("GET", "%s/user/u/%s" %(config.API_ADDR, user_id), headers=h)
         if r.status_code != 200:
             abort(r.status_code, r.text)
         j = r.json()
@@ -197,7 +197,7 @@ def admin_user_edit(user_id):
         d = {
                 "user_id": user_id, "cnname": cnname, "email": email, "phone": phone, "im": im, "qq": qq,
         }
-        r = corelib.auth_requests(g.user_token ,"PUT", "%s/admin/change_user_profile" %(config.API_ADDR,), \
+        r = corelib.auth_requests("PUT", "%s/admin/change_user_profile" %(config.API_ADDR,), \
                 data=json.dumps(d), headers=h)
         if r.status_code != 200:
             ret["msg"] = r.text
@@ -205,7 +205,7 @@ def admin_user_edit(user_id):
         return json.dumps(ret)
 
 @app.route("/admin/user/<int:user_id>/chpwd", methods=["POST", ])
-@require_login(json_msg="login first")
+@require_login_json()
 def admin_user_change_password(user_id):
     if request.method == "POST":
         ret = {"msg": ""}
@@ -223,7 +223,7 @@ def admin_user_change_password(user_id):
         d = {
                 "user_id": user_id, "password": password,
         }
-        r = corelib.auth_requests(g.user_token ,"PUT", "%s/admin/change_user_passwd" %(config.API_ADDR,), \
+        r = corelib.auth_requests("PUT", "%s/admin/change_user_passwd" %(config.API_ADDR,), \
                 data=json.dumps(d), headers=h)
         if r.status_code != 200:
             ret["msg"] = r.text
@@ -231,7 +231,7 @@ def admin_user_change_password(user_id):
         return json.dumps(ret)
 
 @app.route("/admin/user/<int:user_id>/role", methods=["POST", ])
-@require_login(json_msg="login first")
+@require_login_json()
 def admin_user_change_role(user_id):
     if request.method == "POST":
         ret = {"msg": ""}
@@ -250,7 +250,7 @@ def admin_user_change_role(user_id):
         h = {"Content-type":"application/json"}
         d = {"admin": admin, "user_id": int(user_id)}
 
-        r = corelib.auth_requests(g.user_token, "PUT", "%s/admin/change_user_role" \
+        r = corelib.auth_requests("PUT", "%s/admin/change_user_role" \
                 %(config.API_ADDR,), data=json.dumps(d), headers=h)
         if r.status_code != 200:
             ret["msg"] = r.text
@@ -258,7 +258,7 @@ def admin_user_change_role(user_id):
         return json.dumps(ret)
 
 @app.route("/admin/user/<int:user_id>/delete", methods=["POST", ])
-@require_login(json_msg="login first")
+@require_login_json()
 def admin_user_delete(user_id):
     if request.method == "POST":
         ret = {"msg": ""}
@@ -270,7 +270,7 @@ def admin_user_delete(user_id):
         h = {"Content-type":"application/json"}
         d = {"user_id": int(user_id)}
 
-        r = corelib.auth_requests(g.user_token, "DELETE", "%s/admin/delete_user" \
+        r = corelib.auth_requests("DELETE", "%s/admin/delete_user" \
                 %(config.API_ADDR,), data=json.dumps(d), headers=h)
         if r.status_code != 200:
             ret["msg"] = r.text

+ 25 - 12
rrd/view/utils.py

@@ -1,7 +1,7 @@
 #-*- coding:utf-8 -*-
 import json
 import requests
-from flask import g, redirect, session
+from flask import g, redirect, session, abort
 
 from functools import wraps
 
@@ -10,19 +10,32 @@ from rrd import corelib
 from rrd.utils import randbytes
 from rrd.model.user import User, UserToken
 
-def require_login(redir="/auth/login", json_msg="", html_msg=""):
+def require_login(redir="/auth/login"):
     def _(f):
         @wraps(f)
         def __(*a, **kw):
             if not g.user:
-                if redir:
-                    return redirect(redir)
-                elif json_msg:
-                    return json.dumps({"msg": json_msg})
-                elif html_msg:
-                    return abort(403, html_msg)
-                else:
-                    return abort(403, "please login first")
+                return redirect(redir or "/auth/login")
+            return f(*a, **kw)
+        return __
+    return _
+
+def require_login_abort(status_code=403, msg="login first"):
+    def _(f):
+        @wraps(f)
+        def __(*a, **kw):
+            if not g.user:
+                return abort(status_code, msg)
+            return f(*a, **kw)
+        return __
+    return _
+
+def require_login_json(json_msg={"ok":False, "msg":"login first"}):
+    def _(f):
+        @wraps(f)
+        def __(*a, **kw):
+            if not g.user:
+                return json.dumps(json_msg)
             return f(*a, **kw)
         return __
     return _
@@ -49,7 +62,7 @@ def get_current_user_profile(user_token):
         return 
 
     h = {"Content-type": "application/json"}
-    r = corelib.auth_requests(user_token, "GET", "%s/user/current" %config.API_ADDR, headers=h)
+    r = corelib.auth_requests("GET", "%s/user/current" %config.API_ADDR, headers=h)
     if r.status_code != 200:
         return
 
@@ -60,7 +73,7 @@ def logout_user(user_token):
     if not user_token:
         return 
 
-    r = corelib.auth_requests(user_token, "GET", "%s/user/logout" %config.API_ADDR)
+    r = corelib.auth_requests("GET", "%s/user/logout" %config.API_ADDR)
     if r.status_code != 200:
         raise Exception("%s:%s" %(r.status_code, r.text))
     clear_user_cookie(session)