From 04c82d60514d1c2fb0bdcb435d9a544cafdc0c36 Mon Sep 17 00:00:00 2001 From: Tom Hunger Date: Wed, 7 Jan 2015 16:25:37 +0000 Subject: [PATCH] Commit basic new structure of sirius. This is a fairly big commit because it took some fiddling to get the structure right. Note also that we're deleting the database and clearing out the migrations while the models still change a lot like this: rm sirius/data.sqlite rm migrations/versions/* ./manage.py db revision --autogenerate -m "Sirius models." ./manage.py db upgrade The web frontend lives in sirius.web. --- migrations/env.py | 3 +- .../versions/31a4efaaa779_sirius_models.py | 77 +++++++++++++ migrations/versions/571ce49cc27_.py | 63 ----------- requirements.txt | 6 +- sirius/models/__init__.py | 0 sirius/models/db.py | 3 + sirius/models/hardware.py | 106 ++++++++++++++++++ sirius/models/user.py | 26 +++++ sirius/stats.py | 11 +- sirius/web/landing.py | 8 ++ sirius/web/server.py | 41 ------- sirius/web/templates/admin.html | 7 ++ sirius/web/templates/base.html | 37 ++++++ sirius/web/templates/dump.html | 15 +++ sirius/web/templates/index.html | 12 ++ sirius/web/twitter.py | 70 ++++++++++++ sirius/web/webapp.py | 23 ++-- 17 files changed, 391 insertions(+), 117 deletions(-) create mode 100644 migrations/versions/31a4efaaa779_sirius_models.py delete mode 100644 migrations/versions/571ce49cc27_.py create mode 100644 sirius/models/__init__.py create mode 100644 sirius/models/db.py create mode 100644 sirius/models/hardware.py create mode 100644 sirius/models/user.py create mode 100644 sirius/web/landing.py delete mode 100644 sirius/web/server.py create mode 100644 sirius/web/templates/admin.html create mode 100644 sirius/web/templates/base.html create mode 100644 sirius/web/templates/dump.html create mode 100644 sirius/web/templates/index.html create mode 100644 sirius/web/twitter.py diff --git a/migrations/env.py b/migrations/env.py index 70961ce..2e76e4a 100644 --- a/migrations/env.py +++ b/migrations/env.py @@ -17,7 +17,7 @@ fileConfig(config.config_file_name) # target_metadata = mymodel.Base.metadata from flask import current_app config.set_main_option('sqlalchemy.url', current_app.config.get('SQLALCHEMY_DATABASE_URI')) -target_metadata = current_app.extensions['migrate'].db.metadata +target_metadata = current_app.extensions['migrate'].db.db.metadata # other values from the config, defined by the needs of env.py, # can be acquired: @@ -70,4 +70,3 @@ if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online() - diff --git a/migrations/versions/31a4efaaa779_sirius_models.py b/migrations/versions/31a4efaaa779_sirius_models.py new file mode 100644 index 0000000..95166d7 --- /dev/null +++ b/migrations/versions/31a4efaaa779_sirius_models.py @@ -0,0 +1,77 @@ +"""Sirius models. + +Revision ID: 31a4efaaa779 +Revises: None +Create Date: 2015-01-07 17:33:02.404123 + +""" + +# revision identifiers, used by Alembic. +revision = '31a4efaaa779' +down_revision = None + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.create_table('user', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('username', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('bridge', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('created', sa.DateTime(), nullable=True), + sa.Column('bridge_address', sa.String(), nullable=False), + sa.PrimaryKeyConstraint('id', 'bridge_address') + ) + op.create_table('device_log', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('created', sa.DateTime(), nullable=True), + sa.Column('device_address', sa.String(), nullable=True), + sa.Column('entry', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('printer', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('created', sa.DateTime(), nullable=True), + sa.Column('device_address', sa.String(), nullable=True), + sa.Column('hardware_xor', sa.String(), nullable=True), + sa.Column('owner', sa.Integer(), nullable=True), + sa.Column('used_claim_code', sa.String(), nullable=True), + sa.ForeignKeyConstraint(['owner'], [u'user.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('twitter_oauth', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('screen_name', sa.String(), nullable=True), + sa.Column('token', sa.String(), nullable=True), + sa.ForeignKeyConstraint(['user_id'], [u'user.id'], ), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('screen_name'), + sa.UniqueConstraint('token') + ) + op.create_table('claim_code', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('created', sa.DateTime(), nullable=True), + sa.Column('by', sa.Integer(), nullable=True), + sa.Column('hardware_xor', sa.String(), nullable=True), + sa.Column('claim_code', sa.String(), nullable=True), + sa.ForeignKeyConstraint(['by'], [u'user.id'], ), + sa.PrimaryKeyConstraint('id') + ) + ### end Alembic commands ### + + +def downgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.drop_table('claim_code') + op.drop_table('twitter_oauth') + op.drop_table('printer') + op.drop_table('device_log') + op.drop_table('bridge') + op.drop_table('user') + ### end Alembic commands ### diff --git a/migrations/versions/571ce49cc27_.py b/migrations/versions/571ce49cc27_.py deleted file mode 100644 index 582d200..0000000 --- a/migrations/versions/571ce49cc27_.py +++ /dev/null @@ -1,63 +0,0 @@ -"""empty message - -Revision ID: 571ce49cc27 -Revises: None -Create Date: 2014-09-27 13:49:33.601801 - -""" - -# revision identifiers, used by Alembic. -revision = '571ce49cc27' -down_revision = None - -from alembic import op -import sqlalchemy as sa - - -def upgrade(): - ### commands auto generated by Alembic - please adjust! ### - op.create_table('bridge_commands', - sa.Column('id', sa.Integer(), nullable=False), - sa.Column('timestamp', sa.DateTime(), nullable=False), - sa.Column('bridge_address', sa.String(), nullable=False), - sa.Column('json_payload', sa.UnicodeText(), nullable=False), - sa.Column('state', sa.String(), nullable=False), - sa.Column('return_code', sa.SmallInteger(), nullable=True), - sa.PrimaryKeyConstraint('id') - ) - op.create_table('device_commands', - sa.Column('id', sa.Integer(), nullable=False), - sa.Column('device_address', sa.String(), nullable=False), - sa.Column('binary_payload', sa.Text(), nullable=False), - sa.Column('state', sa.String(), nullable=False), - sa.Column('deliver_at', sa.DateTime(), nullable=False), - sa.Column('return_code', sa.SmallInteger(), nullable=True), - sa.PrimaryKeyConstraint('id') - ) - op.create_table('devices', - sa.Column('device_address', sa.String(), nullable=False), - sa.Column('hardware_xor', sa.Integer(), nullable=False), - sa.PrimaryKeyConstraint('device_address') - ) - op.create_table('pending_claims', - sa.Column('id', sa.Integer(), nullable=False), - sa.Column('claim_code', sa.String(), nullable=False), - sa.Column('hardware_xor', sa.String(), nullable=False), - sa.PrimaryKeyConstraint('id') - ) - op.create_table('bridges', - sa.Column('bridge_address', sa.String(), nullable=False), - sa.Column('last_power_on', sa.DateTime(), nullable=True), - sa.PrimaryKeyConstraint('bridge_address') - ) - ### end Alembic commands ### - - -def downgrade(): - ### commands auto generated by Alembic - please adjust! ### - op.drop_table('bridges') - op.drop_table('pending_claims') - op.drop_table('devices') - op.drop_table('device_commands') - op.drop_table('bridge_commands') - ### end Alembic commands ### diff --git a/requirements.txt b/requirements.txt index 64b7e7f..5d3a92d 100755 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,7 @@ Flask==0.10.1 Flask-Bootstrap==3.2.0.2 Flask-Migrate==1.2.0 +Flask-OAuth==0.12 Flask-SQLAlchemy==2.0 Flask-Script==2.0.5 Flask-Sockets==0.1 @@ -13,14 +14,17 @@ SQLAlchemy==0.9.7 WTForms==2.0.1 Werkzeug==0.9.6 alembic==0.6.7 +argparse==1.2.1 gevent==1.0.1 gevent-websocket==0.9.3 greenlet==0.4.4 gunicorn==19.1.1 +httplib2==0.9 itsdangerous==0.24 +nose==1.3.4 +oauth2==1.5.211 psycopg2==2.5.4 pycrypto==2.6.1 redis==2.10.3 selenium==2.43.0 wsgiref==0.1.2 -nose diff --git a/sirius/models/__init__.py b/sirius/models/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sirius/models/db.py b/sirius/models/db.py new file mode 100644 index 0000000..d8d772b --- /dev/null +++ b/sirius/models/db.py @@ -0,0 +1,3 @@ +from flask.ext import sqlalchemy + +db = sqlalchemy.SQLAlchemy() diff --git a/sirius/models/hardware.py b/sirius/models/hardware.py new file mode 100644 index 0000000..b4c7ea0 --- /dev/null +++ b/sirius/models/hardware.py @@ -0,0 +1,106 @@ +from sirius.models.db import db +from sirius.models import user + + +class Bridge(db.Model): + """Bridges are not really interesting for users other than that they + are connected so we don't store ownership for them. + """ + __tablename__ = 'bridge' + id = db.Column(db.Integer, primary_key=True) + created = db.Column(db.DateTime) + bridge_address = db.Column(db.String, primary_key=True) + + +class Printer(db.Model): + """On reset printers generate a new, unique device address, so every + reset will result in a new Printer row. + + Note that this model is only ever created by a printer calling + home. Users create a ClaimCode row. + """ + __tablename__ = 'printer' + id = db.Column(db.Integer, primary_key=True) + created = db.Column(db.DateTime) + device_address = db.Column(db.String) + hardware_xor = db.Column(db.String) + + # Update the following fields after we connected (i.e. joined over + # hardware xor) a claim to a printer. The fields start out as + # NULL. + owner = db.Column(db.Integer, db.ForeignKey(user.User.id), nullable=True) + used_claim_code = db.Column(db.String, nullable=True) + + +class ClaimCode(db.Model): + """Printer and claim codes are joined over the hardware xor. There are + several possible orders of creating the DB entries (dependent on + whether the user claims a device before it calls home or the other + way round). + + a. + 1. printer calls home with xor A + 2. claim code created with xor A code B + b. + 1. claim code created with xor A code B + 2. printer calls home with xor A + c. + 1. claim code created with xor A code B + 2. claim code created with xor A code C + 3. printer calls home with xor A + + The join is "loose" i.e. in general the order doesn't matter + unless a printer is claimed twice. In That case the newest claim + code has to be used (case c). + + Note also that claim codes are meant to be temporary. I.e. once a + printer has been claimed the claim code becomes irrelevant and + only the printer ownership counts. We don't enforce a valid time + window for claim codes though. + """ + id = db.Column(db.Integer, primary_key=True) + __tablename__ = 'claim_code' + created = db.Column(db.DateTime) + by = db.Column(db.ForeignKey(user.User.id)) + hardware_xor = db.Column(db.String) + claim_code = db.Column(db.String) + + +class DeviceLog(db.Model): + """The device log Recorde state changes in the bridge and connected + devices. We may selectively expose some of these to the user. + """ + __tablename__ = 'device_log' + id = db.Column(db.Integer, primary_key=True) + created = db.Column(db.DateTime) + device_address = db.Column(db.String) + + # json dict of events dispatched on VALID_STATES. E.g. + # {"type": "grant_access", "payload": {...}} + entry = db.Column(db.String) + + VALID_STATES = [ + 'power_on', + 'connect', + 'disconnect', + 'claim', + 'print', + 'grant_access', + 'revoke_access', + ] + + # Expose an explicit API to force people to provide the correct + # arguments. + @classmethod + def log_power_on(cls, bridge_address): + pass + + @classmethod + def log_connect(cls, device_address): + pass + + @classmethod + def log_disconnect(cls, device_address): + pass + + # TODO log all the things diff --git a/sirius/models/user.py b/sirius/models/user.py new file mode 100644 index 0000000..91e75c1 --- /dev/null +++ b/sirius/models/user.py @@ -0,0 +1,26 @@ +"""User models. Login only via twitter for now to avoid the whole +forgot-password/reset-password dance. +""" +from sirius.models.db import db + + +class User(db.Model): + __tablename__ = 'user' + id = db.Column(db.Integer, primary_key=True) + # username can't be unique because we may have multiple identity + # providers. For now we just copy the twitter handle. + username = db.Column(db.String) + + +class TwitterOAuth(db.Model): + __tablename__ = 'twitter_oauth' + id = db.Column(db.Integer, primary_key=True) + user_id = db.Column(db.Integer, db.ForeignKey(User.id)) + screen_name = db.Column(db.String, unique=True) + token = db.Column(db.String, unique=True) + +TwitterOAuth.user = db.relationship( + User, + primaryjoin=TwitterOAuth.user_id==User.id, + backref=db.backref('twitteroauth', lazy='dynamic'), +) diff --git a/sirius/stats.py b/sirius/stats.py index 876d245..2b762d2 100644 --- a/sirius/stats.py +++ b/sirius/stats.py @@ -1,8 +1,15 @@ +import flask import collections + STATS = collections.defaultdict(int) +blueprint = flask.Blueprint('stats', __name__) -def as_text(): - return '
' + '\n'.join('{} {}'.format(k, v) for k, v in STATS.items())
 
 def inc(key):
     STATS[key] += 1
+
+
+@blueprint.route('/_/stats')
+def showstats():
+    "Render some trivial stats"
+    return '
' + '\n'.join('{} {}'.format(k, v) for k, v in STATS.items())
diff --git a/sirius/web/landing.py b/sirius/web/landing.py
new file mode 100644
index 0000000..8c447b5
--- /dev/null
+++ b/sirius/web/landing.py
@@ -0,0 +1,8 @@
+import flask
+
+blueprint = flask.Blueprint('landing', __name__)
+
+
+@blueprint.route('/')
+def landing():
+    return flask.render_template('index.html')
diff --git a/sirius/web/server.py b/sirius/web/server.py
deleted file mode 100644
index d30e830..0000000
--- a/sirius/web/server.py
+++ /dev/null
@@ -1,41 +0,0 @@
-"""Main server entry. Run like:
-
-$ bin/gunicorn -k flask_sockets.worker sirius.server:app -b 0.0.0.0:5002 -w 1
-"""
-
-import logging
-import flask
-import flask_sockets
-
-from sirius.protocol import protocol_loop
-from sirius import stats
-from sirius import config
-
-logger = logging.getLogger(__name__)
-
-
-def create_app(config):
-    app = Flask(__name__)
-    app.config.from_object(config[config_name])
-    config[config_name].init_app(app)
-
-    bootstrap.init_app(app)
-    db.init_app(app)
-    sockets.init_app(app)
-
-    logging.basicConfig(level=logging.DEBUG if app.debug else logging.INFO)
-
-    @app.route('/_/stats')
-    def showstats():
-        "Expose some trivial stats"
-        return stats.as_text()
-
-    @sockets.route('/api/v1/connection')
-    def api_v1_connection(ws):
-        protocol_loop.accept(ws)
-
-    logger.info('Creating app.')
-    return app
-
-
-app = create_app()
diff --git a/sirius/web/templates/admin.html b/sirius/web/templates/admin.html
new file mode 100644
index 0000000..98968ea
--- /dev/null
+++ b/sirius/web/templates/admin.html
@@ -0,0 +1,7 @@
+{% extends "base.html" %}
+
+{% block title %}Sirius - Admin{% endblock %}
+
+{% block page_content %}
+

Admin!

+{% endblock %} \ No newline at end of file diff --git a/sirius/web/templates/base.html b/sirius/web/templates/base.html new file mode 100644 index 0000000..f69fbb4 --- /dev/null +++ b/sirius/web/templates/base.html @@ -0,0 +1,37 @@ +{% extends "bootstrap/base.html" %} + +{% block title %}Sirius{% endblock %} + +{% block navbar %} + +{% endblock %} + +{% block content %} +
+ {% for message in get_flashed_messages() %} +
+ + {{ message }} +
+ {% endfor %} + + {% block page_content %}{% endblock %} +
+{% endblock %} diff --git a/sirius/web/templates/dump.html b/sirius/web/templates/dump.html new file mode 100644 index 0000000..fe7eccf --- /dev/null +++ b/sirius/web/templates/dump.html @@ -0,0 +1,15 @@ +{% extends "base.html" %} +{% import "bootstrap/wtf.html" as wtf %} + +{% block title %}Sirius - Device{% endblock %} + +{% block page_content %} +

Send a message

+ +
+{{ dump }}
+
+ +{{ wtf.quick_form(form) }} + +{% endblock %} \ No newline at end of file diff --git a/sirius/web/templates/index.html b/sirius/web/templates/index.html new file mode 100644 index 0000000..35fbb55 --- /dev/null +++ b/sirius/web/templates/index.html @@ -0,0 +1,12 @@ +{% extends "base.html" %} + +{% block title %}Sirius - Index{% endblock %} + +{% block page_content %} +

Hello, World!

+ + + +{% endblock %} diff --git a/sirius/web/twitter.py b/sirius/web/twitter.py new file mode 100644 index 0000000..39a99a2 --- /dev/null +++ b/sirius/web/twitter.py @@ -0,0 +1,70 @@ +import flask +from flask.ext import oauth + +from sirius.models import user +from sirius.models.db import db + +blueprint = flask.Blueprint('twitter_oauth', __name__) +oauth_app = oauth.OAuth() + +# TODO move the consumer_key/secret to flask configuration. The +# current key is a test app that redirects to 127.0.0.1:8000. +twitter = oauth_app.remote_app( + 'twitter', + base_url='https://api.twitter.com/1/', + request_token_url='https://api.twitter.com/oauth/request_token', + access_token_url='https://api.twitter.com/oauth/access_token', + authorize_url='https://api.twitter.com/oauth/authenticate', + consumer_key='DdrpQ1uqKuQouwbCsC6OMA4oF', + consumer_secret='S8XGuhptJ8QIJVmSuIk7k8wv3ULUfMiCh9x1b19PmKSsBh1VDM', +) + + +@twitter.tokengetter +def get_twitter_token(token=None): + return flask.session.get('twitter_token') + + +@blueprint.route('/twitter/login') +def login(): + # Clear token, see https://github.com/mitsuhiko/flask-oauth/issues/48: + flask.session.pop('twitter_token', None) + flask.session.pop('twitter_screen_name', None) + + return twitter.authorize(callback=flask.url_for('twitter_oauth.oauth_authorized', + next=flask.request.args.get('next') or flask.request.referrer or None)) + + +@blueprint.route('/twitter/oauth-authorized') +@twitter.authorized_handler +def oauth_authorized(response): + next_url = flask.request.args.get('next') or '/' + if response is None: + flask.flash(u"Twitter didn't authorize our sign-in request.") + return flask.redirect(next_url) + + flask.session['twitter_token'] = ( + response['oauth_token'], + response['oauth_token_secret'], + ) + flask.session['twitter_screen_name'] = response['screen_name'] + + oauth = db.session.query(user.TwitterOAuth).filter_by( + screen_name=response['screen_name'], + ).first() + + # Create local user model for keying resources (e.g. claim codes) + # if we haven't seen this twitter user before. + if oauth is None: + new_user = user.User( + username=response['screen_name'], + ) + db.session.add(new_user) + db.session.add(user.TwitterOAuth( + user=new_user, + screen_name=response['screen_name'], + token=response['oauth_token'], + )) + db.session.commit() + + return flask.redirect(next_url) diff --git a/sirius/web/webapp.py b/sirius/web/webapp.py index 3f6cffa..eef559e 100644 --- a/sirius/web/webapp.py +++ b/sirius/web/webapp.py @@ -7,15 +7,22 @@ import logging import flask import flask_sockets from flask.ext import bootstrap -from flask.ext import sqlalchemy from sirius.protocol import protocol_loop from sirius import stats from sirius import config + # Import models so they get picked up for migrations. +from sirius.models import db +from sirius.models import hardware +from sirius.models import user + +from sirius.web import landing +from sirius.web import twitter + + logger = logging.getLogger(__name__) bootstrap = bootstrap.Bootstrap() -db = sqlalchemy.SQLAlchemy() sockets = flask_sockets.Sockets() @@ -24,16 +31,16 @@ def create_app(config_name): app.config.from_object(config.config[config_name]) config.config[config_name].init_app(app) + # Configure various plugins and logging bootstrap.init_app(app) - db.init_app(app) + db.db.init_app(app) sockets.init_app(app) - logging.basicConfig(level=logging.DEBUG if app.debug else logging.INFO) - @app.route('/_/stats') - def showstats(): - "Expose some trivial stats" - return stats.as_text() + # Register blueprints + app.register_blueprint(stats.blueprint) + app.register_blueprint(landing.blueprint) + app.register_blueprint(twitter.blueprint) @sockets.route('/api/v1/connection') def api_v1_connection(ws): -- 2.47.3