[Kimchi-devel] [PATCH 4/4] Let frontend redirect user after logging

alinefm at linux.vnet.ibm.com alinefm at linux.vnet.ibm.com
Wed Jul 16 16:44:05 UTC 2014


From: Aline Manera <alinefm at linux.vnet.ibm.com>

The frontend should redirect user after logging so it can properly
store the user information returned by /login for authorization matters.

Signed-off-by: Aline Manera <alinefm at linux.vnet.ibm.com>
---
 src/kimchi/auth.py        |  9 ++----
 src/kimchi/root.py        | 19 +------------
 ui/js/src/kimchi.login.js | 71 +++++++++++++++++++++++++++++++++++++++++++++++
 ui/pages/login.html.tmpl  | 36 +++---------------------
 4 files changed, 78 insertions(+), 57 deletions(-)
 create mode 100644 ui/js/src/kimchi.login.js

diff --git a/src/kimchi/auth.py b/src/kimchi/auth.py
index 6a4a610..971faf7 100644
--- a/src/kimchi/auth.py
+++ b/src/kimchi/auth.py
@@ -28,6 +28,7 @@
 import re
 import termios
 import time
+import urllib2
 
 
 from kimchi import template
@@ -45,7 +46,7 @@ def redirect_login():
     url = "/login.html"
     if cherrypy.request.path_info.endswith(".html"):
         next_url = cherrypy.serving.request.request_line.split()[1]
-        next_url = base64.urlsafe_b64encode(next_url)
+        next_url = urllib2.quote(next_url.encode('utf-8'), safe="")
         url = "/login.html?next=%s" % next_url
 
     raise cherrypy.HTTPRedirect(url, 303)
@@ -203,12 +204,6 @@ def login(username, password, **kwargs):
             debug("User cannot be verified with the supplied password")
             return None
     except PAM.error, (resp, code):
-        if (cherrypy.request.path_info == "/login" and
-           not template.can_accept('application/json')):
-            next_url = kwargs.get("next")
-            url = "/login.html?error=userPassWrong"
-            url = url if next_url is None else url + "&next=%s" % next_url
-            raise cherrypy.HTTPRedirect(url, 303)
         msg_args = {'username': username, 'code': code}
         raise OperationFailed("KCHAUTH0001E", msg_args)
 
diff --git a/src/kimchi/root.py b/src/kimchi/root.py
index 6d1bd19..dec5862 100644
--- a/src/kimchi/root.py
+++ b/src/kimchi/root.py
@@ -128,24 +128,7 @@ def __init__(self, model, dev_env):
         self.messages = messages
 
     @cherrypy.expose
-    def login(self, *args, **kwargs):
-        username = kwargs.get('username')
-        password = kwargs.get('password')
-        # traditional form base authentication
-        kwa = {}
-        if username is not None:
-            # UI can parser the redirect url by "next" query parameter
-            next_url = kwargs.get('next')
-            next_url = next_url[0] if(type(next_url) is list) else next_url
-            if next_url is None:
-                lastPage = cherrypy.request.cookie.get("lastPage")
-                next_url = lastPage.value if lastPage is not None else "/"
-            else:
-                kwa = {"next": next_url.encode("utf-8")}
-                next_url = base64.urlsafe_b64decode(next_url.encode("utf-8"))
-            auth.login(username, password, **kwa)
-            raise cherrypy.HTTPRedirect(next_url, 303)
-
+    def login(self, *args):
         try:
             params = parse_request()
             username = params['username']
diff --git a/ui/js/src/kimchi.login.js b/ui/js/src/kimchi.login.js
new file mode 100644
index 0000000..72d2ee3
--- /dev/null
+++ b/ui/js/src/kimchi.login.js
@@ -0,0 +1,71 @@
+/*
+ * Project Kimchi
+ *
+ * Copyright IBM, Corp. 2014
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+kimchi.login_main = function() {
+
+    var selectedLanguage = kimchi.lang.get();
+    $('#userLang').val(selectedLanguage);
+
+    $('#userLang').on('change', function() {
+        kimchi.lang.set($(this).val());
+        location.reload();
+    });
+
+    var query = window.location.search;
+    var error = /.*error=(.*?)(&|$)/g.exec(query);
+    if (error && error[1] == "sessionTimeout") {
+        $("#messSession").show();
+    }
+
+    var userNameBox = $('#username');
+    var passwordBox = $('#password');
+    var loginButton = $('#btn-login');
+
+    var login = function(event) {
+        $("#login").hide()
+        $("#logging").show()
+
+        var userName = userNameBox.val();
+        userName && kimchi.user.setUserName(userName);
+        var settings = {
+            username: userName,
+            password: passwordBox.val()
+        };
+
+        kimchi.login(settings, function(data) {
+            var query = window.location.search;
+            var next  = /.*next=(.*?)(&|$)/g.exec(query);
+            if (next) {
+                var next_url = decodeURIComponent(next[1])
+            }
+            else {
+                var lastPage = kimchi.cookie.get('lastPage');
+                var next_url = lastPage ? lastPage.replace(/\"/g,'') : "/"
+            }
+            window.location.replace(next_url)
+        }, function() {
+            $("#messUserPass").show()
+            $("#messSession").hide();
+            $("#logging").hide()
+            $("#login").show()
+        });
+
+        return false;
+    };
+
+    $('#form-login').on('submit', login);
+};
diff --git a/ui/pages/login.html.tmpl b/ui/pages/login.html.tmpl
index f8f683d..7d61a6a 100644
--- a/ui/pages/login.html.tmpl
+++ b/ui/pages/login.html.tmpl
@@ -32,6 +32,7 @@
 <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
 <link rel="shortcut icon" href="images/logo.ico">
 <link rel="stylesheet" href="$href('css/theme-default.min.css')">
+<script src="$href('libs/modernizr.custom.76777.js')"></script>
 <script src="$href('libs/jquery-1.10.0.min.js')"></script>
 <script src="$href('libs/jquery-ui.min.js')"></script>
 <script src="$href('libs/jquery-ui-i18n.min.js')"></script>
@@ -56,40 +57,11 @@
     color: #C85305;
 }
 </style>
-<script>
-function changeLang() {
-    var lang = document.getElementById('userLang').value;
-    kimchi.cookie.set('kimchiLang', lang, 365);
-    window.location.reload();
-}
-function setLang() {
-    var defaultLang = 'en_US';
-    var clientLang = document.getElementsByTagName("html")[0].getAttribute("lang");
-    var persistLang = kimchi.cookie.get('kimchiLang');
-    document.getElementById("userLang").value = persistLang || clientLang || defaultLang;
-}
-function updateBtnLabel() {
-    document.getElementById("login").style.display = "none";
-    document.getElementById("logging").style.display = "";
-    kimchi.user.setUserName(document.getElementById("username").value);
-}
-function setMessage() {
-    var err = "$getVar('data.error', '')";
-    if(err=="userPassWrong")
-        document.getElementById("messUserPass").style.display = "";
-    if(err=="sessionTimeout")
-        document.getElementById("messSession").style.display = "";
-}
-function init() {
-    setLang();
-    setMessage();
-}
-</script>
 </head>
-<body onload="init()">
+<body onload="kimchi.login_main()">
 <div class="container topbar">
     <span id="logo"><img alt="Project Kimchi" src="images/theme-default/logo-white.png"></span>
-    <select id="userLang" onchange="changeLang()">
+    <select id="userLang">
         <option value="en_US">English (US)</option>
         <option value="zh_CN">中文(简体)</option>
         <option value="pt_BR">Português (Brasil)</option>
@@ -100,7 +72,7 @@ function init() {
         <div id="messUserPass" class="err-mess" style="display: none;">$_("The username or password you entered is incorrect. Please try again.")</div>
         <div id="messSession" class="err-mess" style="display: none;">$_("Session timeout, please re-login.")</div>
     </div>
-    <form id="form-login" action="/login$next" method="POST" class="login-panel" onsubmit="updateBtnLabel();">
+    <form id="form-login" class="login-panel">
         <div class="row">
             <input type="text" id="username" name="username" required="required" placeholder="$_("User Name")" autofocus/>
             <div id="username-msg" class="msg-required"></div>
-- 
1.9.3




More information about the Kimchi-devel mailing list