Commits

Luke Plant committed d24fcb9

Implemented 'verses' method that returns verses for logged in user.

Comments (0)

Files changed (4)

lukeplant_me_uk/bibleverses/tests/cgi-bin/views.py

                                  urllib2.quote(v.encode('utf-8')))
                      for k, v in d.items())
 
-def post(path, data):
-    page = urllib2.urlopen(base_url + base_path + path,
-                           data=urlencode(data))
-    return ''.join(page.readlines())
+def make_cookie_header(values):
+    """Creates cookies, same format as is used by javascript format"""
+    return "; ".join('%s=%s' % (urllib2.quote(k), urllib2.quote(v)) 
+                     for k, v in values.iteritems())
+
+def httpopen(path, data=None, cookies=None, headers=None):
+    headers = headers or {}
+    if cookies is not None:
+        headers["Cookie"] = make_cookie_header(cookies)
+    req = urllib2.Request(base_url + base_path + path,
+                          headers=headers)
+    if data is not None:
+        req.add_data(urlencode(data))
+
+    page = urllib2.urlopen(req)
+    return ''.join(page.readlines())    
+
+def get(path, cookies=None, headers=None):
+    return httpopen(path, cookies=cookies, headers=headers)
+
+def post(path, data, cookies=None, headers=None):
+    return httpopen(path, data=data, cookies=cookies, headers=headers)
 
 
 EXISTING_USER = "user@somewhere.com"
 EXISTING_USER_PASSWORD = "password"
+EXISTING_USER_VERSES = ["John 3:16", "Genesis 1:1"]
 NEW_USER = "newuser@somewhere.com"
 NEW_USER_PASSWORD = "password2"
 
+
 def user_delete():
     db.execute("DELETE FROM users WHERE email = %s", NEW_USER)
     db.execute("DELETE FROM users WHERE email = %s", EXISTING_USER)
 
+def verse_delete():
+    res = db.execute("SELECT id FROM users WHERE email = %s;", EXISTING_USER)
+    if len(res) > 0:
+        db.execute("DELETE FROM verses WHERE userid = %s;", res[0][0])
+
 def user_setup():
+    verse_delete()
     user_delete()
     db.execute("INSERT INTO users (id, email, password) VALUES (NULL, %s, %s)", EXISTING_USER, EXISTING_USER_PASSWORD)
+    uid = db.execute("SELECT id FROM users WHERE email = %s;", EXISTING_USER)[0][0]
+    for v in EXISTING_USER_VERSES:
+        db.execute("INSERT INTO verses (id, userid, verseref) VALUES (NULL, %s, %s)", uid, v)
 
 def user_tearDown():
+    verse_delete()
     user_delete()
 
-class RegisterTest(unittest.TestCase):
+class TestBase(unittest.TestCase):
     def setUp(self):
         user_setup()
 
     def tearDown(self):
         user_tearDown()
 
+class RegisterTest(TestBase):
     def test_no_email(self):
         reply = simplejson.loads(post("/register/", {}))
         self.assertEqual(reply, {"success": False,
                                     NEW_USER)[0][0], NEW_USER)
 
 
-class LoginTest(unittest.TestCase):
-    def setUp(self):
-        user_setup()
-
-    def tearDown(self):
-        user_tearDown()
+class LoginTest(TestBase):
 
     def test_login_newuser(self):
         reply = simplejson.loads(post("/login/", {'email': NEW_USER,
                                                   'password': EXISTING_USER_PASSWORD}))
         self.assertEqual(reply, {"success": True})
 
+
+class GetVerseList(TestBase):
+
+    def test_get_list_logged_in(self):
+        """Tests getting of verse list, user is logged in."""
+        reply = simplejson.loads(get("/verses/", cookies={"email": EXISTING_USER,
+                                                          "password": EXISTING_USER_PASSWORD}))
+        self.assertEqual(reply, {'success': True,
+                                 'verselist': sorted(EXISTING_USER_VERSES)})
+
+    def test_get_list_not_logged_in(self):
+        """Attempt to get verse list, user is not logged in."""
+        reply = simplejson.loads(get("/verses/"))
+        self.assertEqual(reply, {'success': False})
+
+    def test_get_list_wrong_password(self):
+        reply = simplejson.loads(get("/verses/", cookies={"email": EXISTING_USER,
+                                                          "password": "x" + EXISTING_USER_PASSWORD}))
+        self.assertEqual(reply, {'success': False})
+
+
 # Entry point
 
 def main(base):

lukeplant_me_uk/bibleverses/web/cgi-bin/lib/bibleverses/views.py

 import simplejson 
+from urllib import unquote
 from bibleverses.webutils import HttpResponse, dispatch
 from bibleverses import db
 
     else:
         return fail(validation=[MSG_EMAIL_NOT_FOUND, "Email address not found."])
 
+class User(object):
+    def __init__(self, uid, email):
+        self.id = uid
+        self.email = email
+
+def get_user(request):
+    email =  unquote(request.get_cookie('email', ''))
+    password = unquote(request.get_cookie('password',''))
+    
+    res = db.execute("SELECT id, email FROM users WHERE email = %s AND password = %s;", email, password)
+    if len(res) == 1:
+        return User(res[0][0], res[0][1])
+    else: 
+        return None
+
+def verses(request):
+    user = get_user(request)
+    if user is None:
+        return fail()
+    else:
+        verses = [row[0] for row in 
+                  db.execute("SELECT verseref FROM verses WHERE userid = %s ORDER BY verseref;", user.id)]
+        return success(verselist=verses)
+
 def initdb(request):
     db.execute("""
 CREATE TABLE users (
        email text UNIQUE,
        password text
 );
+
+CREATE TABLE verses (
+        id integer PRIMARY KEY,
+        userid integer,
+        verseref text,
+        foreign key (userid) REFERENCES users(id)
+)
+
+
 """)
     return success()
 
 def dropdb(request):
     db.execute("""
 DROP TABLE users;
-
+DROP TABLE verses;
 """)
     return success()
 
 urls = [
     ('^/register/$', catch_all(register)),
     ('^/login/$', catch_all(login)),
+    ('^/verses/$', verses),
     ('^/debug/$', catch_all(debug)),
-#    ('^/initdb/$', catch_all(initdb)),
-#    ('^/dropdb/$', catch_all(dropdb)),
+    ('^/initdb/$', catch_all(initdb)),
+    ('^/dropdb/$', catch_all(dropdb)),
 ]
 
 def main():

lukeplant_me_uk/bibleverses/web/cgi-bin/lib/bibleverses/webutils.py

         else:
             self.POST = {}
 
+    def get_cookie(self, name, default):
+        morsel = self.COOKIES.get(name)
+        if morsel is None:
+            return default
+        else:
+            return morsel.value
+
 def force_utf8(s):
     if isinstance(s, str):
         return s

lukeplant_me_uk/bibleverses/web/js/bibleverses.js

     logError(err);
 }
 
+function setCookie(name, val, expires) {
+    document.cookie = name + "=" + encodeURIComponent(val) + "; expires=" + expires.toGMTString() + "; path=" + rootUrl;
+}
+
+function setLoginCookie(email, password) {
+    // Security is very low (just put password in cookie).
+    // But the data being protected has minimal security requirements.
+    var d = new Date();
+    d.setFullYear(d.getFullYear()+100);
+    setCookie("email", email, d);
+    setCookie("password", password, d);
+}
+
 function registerResult(req) {
     var json = evalJSONRequest(req);
     logDebug(req.responseText);
 	hideElement($('regresultfail'));
 	hideElement($('regbuttonsdiv'));
 	showElement($('regclosediv'));
+	setLoginCookie($('id_reg_email').value, $('id_reg_password').value);
     } else {
 	fail = $('regresultfail');
 	logDebug(repr(fail));
 	hideElement($('loginresultfail'));
 	hideElement($('loginbuttonsdiv'));
 	showElement($('loginclosediv'));
+	setLoginCookie($('id_login_email').value, $('id_login_password').value);
     } else {
 	fail = $('loginresultfail');
 	logDebug(repr(fail));