From ffed717d3c57e0c682d7cbabc4756c46be8425bd Mon Sep 17 00:00:00 2001
From: Anton Sarukhanov <code@ant.sr>
Date: Fri, 15 Jul 2016 21:28:54 -0400
Subject: [PATCH] Strava API fully working

---
 api/api.py                           | 12 ----
 api/app.py                           | 25 ++++++--
 api/models.py                        |  9 +++
 api/strava.py                        | 42 +++++++++++---
 api/templates/index.html             |  6 +-
 config.py                            |  2 +
 manage.py                            | 15 +++++
 migrations/alembic.ini               | 45 ++++++++++++++
 migrations/env.py                    | 87 ++++++++++++++++++++++++++++
 migrations/script.py.mako            | 22 +++++++
 migrations/versions/28df97a5e20f_.py | 30 ++++++++++
 requirements.txt                     |  2 +
 run.py                               |  3 +-
 13 files changed, 274 insertions(+), 26 deletions(-)
 delete mode 100644 api/api.py
 create mode 100644 api/models.py
 create mode 100644 manage.py
 create mode 100644 migrations/alembic.ini
 create mode 100644 migrations/env.py
 create mode 100644 migrations/script.py.mako
 create mode 100644 migrations/versions/28df97a5e20f_.py

diff --git a/api/api.py b/api/api.py
deleted file mode 100644
index dbeb7e9..0000000
--- a/api/api.py
+++ /dev/null
@@ -1,12 +0,0 @@
-import json
-from strava import Strava
-
-class Api():
-    """API interfaces"""
-    def __init__(self, api_name):
-        def strava():
-            """Strava API - get my recent rides"""
-            s = Strava()
-            return json.dumps(s.get_athlete())
-        functions = {name:f for (name, f) in locals() if l != 'self'}
-        return functions[api_name]
diff --git a/api/app.py b/api/app.py
index fd1a6fa..1da83ce 100644
--- a/api/app.py
+++ b/api/app.py
@@ -1,11 +1,16 @@
+import json
 from flask import Flask, redirect, render_template, url_for
-from strava import Strava
 from decorators import admin
+from models import db
+from strava import Strava
+from stravalib import unithelper
 
 app = Flask(__name__, instance_relative_config=True)
 app.config.from_object('config')
 app.config.from_pyfile('config.py')
 
+db.init_app(app)
+
 @app.route('/')
 def index():
     return render_template('index.html')
@@ -13,12 +18,24 @@ def index():
 @admin
 @app.route('/strava_auth')
 def strava_auth():
-    return Strava.authorize()
+    if Strava.check_auth():
+        return Strava.deauthorize()
+    else:
+        return Strava.authorize()
 
 @app.route('/api/<api_name>')
 def api(api_name):
-    from api import Api
-    return Api(api_name)
+    if api_name == "strava":
+        s = Strava()
+        return json.dumps([{
+            'name': a.name,
+            'type': a.type,
+            'moving_time': a.moving_time.seconds,
+            'date': str(a.start_date),
+            'distance': unithelper.miles(a.distance).num,
+            'athlete_id': a.athlete.id,
+            'url': 'https://strava.com/activity/{}'.format(a.id)
+            } for a in s.activities])
 
 @app.context_processor
 def cp_is_admin():
diff --git a/api/models.py b/api/models.py
new file mode 100644
index 0000000..2bf2c79
--- /dev/null
+++ b/api/models.py
@@ -0,0 +1,9 @@
+from flask_sqlalchemy import SQLAlchemy
+
+db = SQLAlchemy()
+
+class StravaApiToken(db.Model):
+    """API token for Strava"""
+    __tablename__ = "strava_api_token"
+    id = db.Column(db.Integer, primary_key=True)
+    token = db.Column(db.String)
diff --git a/api/strava.py b/api/strava.py
index 434675c..04b85df 100644
--- a/api/strava.py
+++ b/api/strava.py
@@ -1,13 +1,24 @@
 from flask import request, redirect, current_app
 from stravalib.client import Client
 from requests.exceptions import HTTPError
+from sqlalchemy.orm.exc import NoResultFound
+from models import db, StravaApiToken
+
+class Strava(Client):
+    """Wrapper for stavalib Client, which is a Strava API client.
+    Grabs my API token from database to authenticate."""
+
+    def __init__(self):
+        token = db.session.query(StravaApiToken).one().token
+        super(Strava, self).__init__(token)
 
-class Strava():
     @classmethod
     def check_auth(cls, token = None):
         if not token:
-            # TODO: get token from database
-            token = "obviously invalid"
+            try:
+                token = db.session.query(StravaApiToken).one().token
+            except NoResultFound:
+                return False
         strava = Client(token)
         try:
             return strava.get_athlete().email
@@ -16,14 +27,16 @@ class Strava():
 
     @classmethod
     def authorize(cls, code = None):
-        """Redirect to Strava to get an access token."""
+        """[admin] Redirect to Strava to get an access token."""
         code = code or request.args.get('code', None)
         if not code:
             strava = Client()
             source_url = request.referrer
             authorized_url = request.url
             authorize_url = strava.authorization_url(
-                client_id=current_app.config['STRAVA_APP_ID'], redirect_uri=authorized_url, state=source_url)
+                client_id=current_app.config['STRAVA_APP_ID'],
+                redirect_uri=authorized_url,
+                state=source_url)
             return redirect(authorize_url)
         else:
             source_url = request.args.get('state', None)
@@ -33,8 +46,21 @@ class Strava():
                 client_secret=current_app.config['STRAVA_APP_SECRET'],
                 code=code)
             strava.access_token = access_token
-            # TODO: store the access token
-            athlete = strava.get_athlete()
+            db.session.add(StravaApiToken(token=access_token))
+            db.session.commit()
             if source_url:
                 return redirect(source_url)
-            return "Auth success: {}".format(athlete.email)
+            return "Auth success: {}".format(strava.get_athlete().email)
+
+    @classmethod
+    def deauthorize(cls):
+        """[admin] Remove stored access token."""
+        token = db.session.query(StravaApiToken).one()
+        db.session.delete(token)
+        db.session.commit()
+        return redirect(request.referrer) if request.referrer else "Deleted Strava auth token."
+
+    @property
+    def activities(self):
+        """Get list of activities from Strava API."""
+        return self.get_activities()
diff --git a/api/templates/index.html b/api/templates/index.html
index 4803e31..276b125 100644
--- a/api/templates/index.html
+++ b/api/templates/index.html
@@ -8,12 +8,16 @@
     <ul>
         <li>
             {% if strava %}
-                <a href="{{ url_for('strava_auth') }}">Strava API Connected ({{ strava }})</a>
+                Strava: <strong>{{ strava }}</strong>
+                <a href="{{ url_for('strava_auth') }}">Disconnect</a>
             {% else %}
                 <a href="{{ url_for('strava_auth') }}">Authorize Strava API</a>
             {% endif %}
         </li>
     </ul>
     </nav>
+    {% else %}
+    <header><h1>Hi</h1></header>
+    <p>There is nothing here for you.</p>
     {% endif %}
 {% endblock %}
diff --git a/config.py b/config.py
index 01cdaf9..ca7d9db 100644
--- a/config.py
+++ b/config.py
@@ -1,4 +1,6 @@
 STRAVA_APP_ID = '12345'
 STRAVA_APP_SECRET = 'your-strava-app-secret'
 ADMIN_IP = '127.0.0.1'
+SQLALCHEMY_DATABASE_URI = 'sqlite:///api.db'
+SQLALCHEMY_TRACK_MODIFICATIONS = True
 
diff --git a/manage.py b/manage.py
new file mode 100644
index 0000000..722fbc8
--- /dev/null
+++ b/manage.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+from flask import g
+from flask_migrate import Migrate, MigrateCommand
+from flask_script import Manager
+from api.app import app, db
+from api import models
+
+manager = Manager(app)
+
+migrate = Migrate(app, db)
+
+manager.add_command('db', MigrateCommand)
+
+if __name__ == '__main__':
+    manager.run()
diff --git a/migrations/alembic.ini b/migrations/alembic.ini
new file mode 100644
index 0000000..f8ed480
--- /dev/null
+++ b/migrations/alembic.ini
@@ -0,0 +1,45 @@
+# A generic, single database configuration.
+
+[alembic]
+# template used to generate migration files
+# file_template = %%(rev)s_%%(slug)s
+
+# set to 'true' to run the environment during
+# the 'revision' command, regardless of autogenerate
+# revision_environment = false
+
+
+# Logging configuration
+[loggers]
+keys = root,sqlalchemy,alembic
+
+[handlers]
+keys = console
+
+[formatters]
+keys = generic
+
+[logger_root]
+level = WARN
+handlers = console
+qualname =
+
+[logger_sqlalchemy]
+level = WARN
+handlers =
+qualname = sqlalchemy.engine
+
+[logger_alembic]
+level = INFO
+handlers =
+qualname = alembic
+
+[handler_console]
+class = StreamHandler
+args = (sys.stderr,)
+level = NOTSET
+formatter = generic
+
+[formatter_generic]
+format = %(levelname)-5.5s [%(name)s] %(message)s
+datefmt = %H:%M:%S
diff --git a/migrations/env.py b/migrations/env.py
new file mode 100644
index 0000000..4593816
--- /dev/null
+++ b/migrations/env.py
@@ -0,0 +1,87 @@
+from __future__ import with_statement
+from alembic import context
+from sqlalchemy import engine_from_config, pool
+from logging.config import fileConfig
+import logging
+
+# this is the Alembic Config object, which provides
+# access to the values within the .ini file in use.
+config = context.config
+
+# Interpret the config file for Python logging.
+# This line sets up loggers basically.
+fileConfig(config.config_file_name)
+logger = logging.getLogger('alembic.env')
+
+# add your model's MetaData object here
+# for 'autogenerate' support
+# from myapp import mymodel
+# 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
+
+# other values from the config, defined by the needs of env.py,
+# can be acquired:
+# my_important_option = config.get_main_option("my_important_option")
+# ... etc.
+
+
+def run_migrations_offline():
+    """Run migrations in 'offline' mode.
+
+    This configures the context with just a URL
+    and not an Engine, though an Engine is acceptable
+    here as well.  By skipping the Engine creation
+    we don't even need a DBAPI to be available.
+
+    Calls to context.execute() here emit the given string to the
+    script output.
+
+    """
+    url = config.get_main_option("sqlalchemy.url")
+    context.configure(url=url)
+
+    with context.begin_transaction():
+        context.run_migrations()
+
+
+def run_migrations_online():
+    """Run migrations in 'online' mode.
+
+    In this scenario we need to create an Engine
+    and associate a connection with the context.
+
+    """
+
+    # this callback is used to prevent an auto-migration from being generated
+    # when there are no changes to the schema
+    # reference: http://alembic.readthedocs.org/en/latest/cookbook.html
+    def process_revision_directives(context, revision, directives):
+        if getattr(config.cmd_opts, 'autogenerate', False):
+            script = directives[0]
+            if script.upgrade_ops.is_empty():
+                directives[:] = []
+                logger.info('No changes in schema detected.')
+
+    engine = engine_from_config(config.get_section(config.config_ini_section),
+                                prefix='sqlalchemy.',
+                                poolclass=pool.NullPool)
+
+    connection = engine.connect()
+    context.configure(connection=connection,
+                      target_metadata=target_metadata,
+                      process_revision_directives=process_revision_directives,
+                      **current_app.extensions['migrate'].configure_args)
+
+    try:
+        with context.begin_transaction():
+            context.run_migrations()
+    finally:
+        connection.close()
+
+if context.is_offline_mode():
+    run_migrations_offline()
+else:
+    run_migrations_online()
diff --git a/migrations/script.py.mako b/migrations/script.py.mako
new file mode 100644
index 0000000..9570201
--- /dev/null
+++ b/migrations/script.py.mako
@@ -0,0 +1,22 @@
+"""${message}
+
+Revision ID: ${up_revision}
+Revises: ${down_revision}
+Create Date: ${create_date}
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = ${repr(up_revision)}
+down_revision = ${repr(down_revision)}
+
+from alembic import op
+import sqlalchemy as sa
+${imports if imports else ""}
+
+def upgrade():
+    ${upgrades if upgrades else "pass"}
+
+
+def downgrade():
+    ${downgrades if downgrades else "pass"}
diff --git a/migrations/versions/28df97a5e20f_.py b/migrations/versions/28df97a5e20f_.py
new file mode 100644
index 0000000..9ccc0bb
--- /dev/null
+++ b/migrations/versions/28df97a5e20f_.py
@@ -0,0 +1,30 @@
+"""empty message
+
+Revision ID: 28df97a5e20f
+Revises: None
+Create Date: 2016-07-15 18:37:18.805989
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '28df97a5e20f'
+down_revision = None
+
+from alembic import op
+import sqlalchemy as sa
+
+
+def upgrade():
+    ### commands auto generated by Alembic - please adjust! ###
+    op.create_table('strava_api_token',
+    sa.Column('id', sa.Integer(), nullable=False),
+    sa.Column('token', sa.String(), nullable=True),
+    sa.PrimaryKeyConstraint('id')
+    )
+    ### end Alembic commands ###
+
+
+def downgrade():
+    ### commands auto generated by Alembic - please adjust! ###
+    op.drop_table('strava_api_token')
+    ### end Alembic commands ###
diff --git a/requirements.txt b/requirements.txt
index d5c5ce6..aa10f9b 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,4 +1,6 @@
 Flask==0.11.1
+Flask-Migrate==1.8.1
 Flask-SQLAlchemy==2.1
+psycopg2==2.6.2
 SQLAlchemy==1.0.14
 stravalib==0.5.0
diff --git a/run.py b/run.py
index 53c616f..f1c709c 100644
--- a/run.py
+++ b/run.py
@@ -1,4 +1,5 @@
 #!/usr/bin/env python
 from api.app import app
 
-app.run()
+if __name__ == '__main__':
+    app.run()
-- 
GitLab