app.py 1.57 KB
Newer Older
okhin's avatar
okhin committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/env python

import sqlite3

from bottle import route, run, request, abort, install, get, post
from bottle_sqlite import SQLitePlugin
import jwt

install(SQLitePlugin(dbfile='call.db'))

# We need a decorator to check if our query is authenticated.
# We will store an API key and SECRET in ur database, the client
# needs to have both of them.
# He must then send us a JWT token with an API claim in the payload.
# The JWT token must be encoded and signed with the SECRET. If the
# token is bad, we return a 403.
def authenticated(f):
    def wrapped(db, *args, **kwargs):
        # Let's get the JWT token. It should be a params (from get or post or whatev')
        if 'token' not in request.params:
            abort(403, "No token found in the query")
        # We want the api id in the params to.
        if 'api' not in request.params:
            abort(403, "No api id found in the params")
        # Now, let's get the token on our side
        try:
            results = db.execute('SELECT token FROM users WHERE api = ?', (request.params['api'],)).fetchall()
            assert len(results) == 1
            token = results[0][0]
            auth_token = jwt.decode(request.params['token'], token)
            assert auth_token['api'] == request.params['api']
        except (jwt.exceptions.InvalidTokenError, AssertionError) as e:
            abort(403, e)
        except Exception as e:
            abort(500, e)
        return f(db, *args, **kwargs)
    return wrapped

@get('/call')
@authenticated
def call(db):
    return 'Ohai'
    
run(host='localhost', port=8080, debug=True)