Permalink
Browse files

Added random example

Continued working on server
Removed pyc files
  • Loading branch information...
1 parent 31af41b commit e474d2e8b9d68c2942afcae78ab0b59c896a2a82 @sschaetz committed Aug 21, 2011
View
@@ -0,0 +1,2 @@
+*.pyc
+*.log
View
@@ -157,48 +157,55 @@ starbase.crypto.random = function()
starbase.crypto.random = {
- counter_: 0,
-
start_wait_entropy: function()
{ console.log("start_wait_entropy original"); },
- wait_entropy: function(progress)
- {console.log("wait_entropy original " + progress); },
+ update_progress: function()
+ { console.log("update_progress original ", + sjcl.random.getProgress()); },
stop_wait_entropy: function()
{ console.log("stop_wait_entropy original"); },
-
- register_callbacks: function(start, wait, stop)
+
+ // set custom callbacks for start, update and stop events of the rng
+ register_callbacks: function(start, update, stop)
{
this.start_wait_entropy = start;
- this.wait_entropy = wait;
+ this.wait_entropy = update;
this.stop_wait_entropy = stop;
},
-
- check_entropy()
+ /**
+ * if random numbers are required, the function requiring the numbers should
+ * be wrapped as a callback to check_entropy
+ */
+ check_entropy: function(callback)
{
- if(this.counter_ < 5)
+ // not enough entropy
+ if(!sjcl.random.isReady())
{
- this.counter_++;
- this.wait_entropy(this.counter_);
- setTimeout("starbase.crypto.random.check_entropy()", 100);
+ starbase.crypto.random.start_wait_entropy();
+
+ // if there is progress fire event
+ sjcl.random.addEventListener("progress",
+ function()
+ {
+ starbase.crypto.random.update_progress();
+ }
+ );
+
+ // if we have entropy call stop_wait_entropy and callback
+ sjcl.random.addEventListener("seeded",
+ function()
+ {
+ starbase.crypto.random.stop_wait_entropy();
+ callback();
+ }
+ );
}
else
{
- this.stop_wait_entropy();
- this.counter_ = 0;
- }
- },
-
- get: function(num)
- {
- if(counter_ < 5)
- {
- this.start_wait_entropy();
- this.check_entropy();
+ callback();
}
- return counter_;
}
};
@@ -0,0 +1,29 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
+ "http://www.w3.org/TR/html4/loose.dtd">
+<html>
+<head>
+
+<script src="http://code.jquery.com/jquery-latest.js"></script>
+
+<script src="../libs/json2.min.js"></script>
+<script src="../libs/sjcl-0.8.min.js"></script>
+<script src="../libs/bigint-5.4.min.js"></script>
+<script src="../starbase.js"></script>
+<script src="../crypto.js"></script>
+
+<script>
+$(document).ready(function(){
+
+
+sjcl.random.startCollectors();
+starbase.crypto.random.check_entropy(function() { console.log("yay!"); });
+
+
+});
+</script>
+
+</head>
+<body>
+
+</body>
+</html>
View
@@ -1,4 +1,4 @@
[general]
-domain = starba.se/
+domain = http://127.0.0.1:5000/
root_folder = /tmp/starbase/
user_data_folder = /tmp/starbase/users/
View
@@ -1,63 +1,16 @@
# script to create a new user
-import ConfigParser
import sys
-import shutil
-import sqlite3
-import os
-
-from starbase.utils import file_exists
-
-def create_user(username, accesstoken, verbose=0):
- if verbose:
- print "trying to create user", username
-
- # read configuration
- config = ConfigParser.RawConfigParser()
- config.read('../config.cfg')
-
- user_data_folder = config.get('general', 'user_data_folder')
- user_database = user_data_folder + username + '.sql'
- user_url = config.get('general', 'domain') + username
-
- # check if user already exists
- if file_exists(user_database):
- if verbose:
- print "error: user already exists"
- return 2
-
- # here be dragons
- try:
- # copy over initial database
- shutil.copy2('default.sql', user_database)
-
- # initialize database
- db = sqlite3.connect(user_database)
- db.execute('INSERT INTO admin (authkey, name, url) VALUES (?, ?, ?) ',
- (accesstoken, username, user_url))
- db.commit()
- db.close()
-
- except Exception, e:
- # delete the file if it was created
- if file_exists(user_database):
- os.remove(user_database)
- if verbose:
- print e
- return 2
- else:
- if verbose:
- print "success"
- return 0
+from starbase import utils
def main():
if len(sys.argv) != 3:
print "usage: python newuser.py <username> <accesstoken>"
return 2
username = sys.argv[1]
accesstoken = sys.argv[2]
- return create_user(username, accesstoken, 1)
+ return utils.create_user(username, accesstoken, 1)
if __name__ == "__main__":
View
@@ -1,44 +1,68 @@
import ConfigParser
import sqlite3
+import json
from werkzeug.wrappers import Response, Request
from werkzeug.routing import Map, Rule
-from werkzeug.exceptions import HTTPException, NotFound
+from werkzeug.exceptions import \
+ HTTPException, NotFound, Unauthorized, BadRequest
+
from werkzeug.wsgi import SharedDataMiddleware
from werkzeug.wrappers import CommonRequestDescriptorsMixin, BaseRequest
+import logging
+import datetime
+
+from starbase.utils import file_exists, create_user
+
+def error_response(code, message):
+ r = [code, message]
+ return Response(json.dumps(r), content_type="application/json")
-from starbase.utils import file_exists
+def success_response():
+ return Response(json.dumps("OK"), content_type="application/json")
+def data_response(data):
+ return Response(json.dumps(data), content_type="application/json")
class starbase(object):
def __init__(self):
self.config = ConfigParser.RawConfigParser()
self.config.read('../config.cfg')
self.user_data_folder = self.config.get('general', 'user_data_folder')
+ logging.basicConfig(filename='server.log',level=logging.DEBUG)
+ logging.info('Started server at ' + str(datetime.datetime.now()))
# map urls to functions
self.url_map = Map([
+ Rule('/', endpoint='root'),
Rule('/<user>/', endpoint='default'),
- Rule('/<user>/load_data', endpoint='load_data'),
+ Rule('/<user>/load_data/<authkey>', endpoint='load_data'),
Rule('/<user>/store_data', endpoint='store_data'),
Rule('/<user>/load_messages', endpoint='load_messages'),
- Rule('/<user>/inbox', endpoint='inbox'),
+ Rule('/<user>/inbox/<accesstoken>', endpoint='inbox'),
Rule('/<user>/add_accesstokens', endpoint='add_accesstokens'),
- Rule('/<user>/remove_accesstokens', endpoint='remove_accesstokens')
+ Rule('/<user>/remove_accesstokens', endpoint='remove_accesstokens'),
+ Rule('/createuser', endpoint='createuser'),
])
+
+ # those functions do not require a username
+ self.no_user = ["root", "createuser"]
def dispatch_request(self, request):
adapter = self.url_map.bind_to_environ(request.environ)
try:
endpoint, values = adapter.match()
- # only proceed if user exists
- if not self.user_exists(values['user']):
- raise NotFound()
-
- self.db = \
- sqlite3.connect(self.user_data_folder + values['user'] + '.sql')
+
+ # for some requests a user is required
+ if endpoint not in self.no_user:
+ if not self.user_exists(values['user']):
+ raise NotFound()
+ else:
+ # if a user is provided open the database
+ self.db = \
+ sqlite3.connect(self.user_data_folder + values['user'] + '.sql')
return getattr(self, 'on_' + endpoint)(request, **values)
except HTTPException, e:
@@ -53,43 +77,87 @@ def __call__(self, environ, start_response):
return self.wsgi_app(environ, start_response)
- # here are the responders -----
+ # here are the responders -----
+ def on_root(self, request):
+ return Response("on_root")
+
def on_default(self, request, user):
return Response("on_default " + user)
- def on_load_data(self, request, user):
- print request
- print request.form['authkey']
- return Response("load_data")
+ def on_load_data(self, request, user, authkey):
+ self.user_authenticate(authkey)
+ return data_response(self.get_data())
def on_store_data(self, request, user):
- return Response("store_data")
+ if not 'authkey' in request.form:
+ raise Unauthorized()
+ if not 'data' in request.form:
+ raise BadRequest()
+
+ self.user_authenticate(request.form['authkey'])
+ self.set_data(request.form['data'])
+ return success_response()
def on_load_messages(self, request, user):
+ if not 'authkey' in request.form:
+ raise Unauthorized()
+ self.user_authenticate(request.form['authkey'])
return Response("load_messages")
- def on_inbox(self, request, user):
- return Response("inbox")
+ def on_inbox(self, request, user, accesstoken):
+ return Response("inbox " + user + " " + accesstoken)
def on_add_accesstokens(self, request, user):
return Response("add_accesstokens")
def on_remove_accesstokens(self, request, user):
return Response("remove_accesstokens")
-
+ # create a new user
+ def on_createuser(self, request):
+ if not 'user' in request.form or not 'authkey' in request.form:
+ raise BadRequest("missing user or authkey")
+
+ user = request.form['user']
+ authkey = request.form['authkey']
+ if self.user_exists(user):
+ raise BadRequest("user already exists")
+ create_user(user, authkey)
+ return success_response()
+
+
+
+
# some utility functions -----
def user_exists(self, user):
user_database = self.user_data_folder + user + '.sql'
- print user_database
return file_exists(user_database)
-
+
+ # database functions -----
+
def user_authenticate(self, authkey):
- db.execute('SELECT autkey FROM admin WHERE authkey = ?', (authkey))
- print db
+ c = self.db.cursor()
+ c.execute('SELECT 1 FROM admin WHERE authkey = ?', [authkey])
+ rows = len(c.fetchall())
+ c.close()
+ if rows != 1:
+ raise Unauthorized()
+
+ def get_data(self):
+ c = self.db.cursor()
+ c.execute('SELECT data FROM blobs WHERE name = ?', ["datablob"])
+ row = c.fetchone()
+ c.close()
+ return row[0]
+
+ def set_data(self, data):
+ self.db.execute('UPDATE blobs SET data = ? WHERE name = ?',
+ [data, "datablob"])
+ self.db.commit()
+ return
def create_app():
Binary file not shown.
Oops, something went wrong. Retry.

0 comments on commit e474d2e

Please sign in to comment.