summaryrefslogtreecommitdiff
path: root/mach2.py
diff options
context:
space:
mode:
authorMichaël Ball <michael.ball@gmail.com>2015-12-05 12:26:19 +0000
committerMichaël Ball <michael.ball@gmail.com>2015-12-05 16:45:34 +0000
commite9749a150cfe8c0548cb78380aba9ab2e4730984 (patch)
tree76a329d775cc9d0589cf8f84e3211f60cc07b3a9 /mach2.py
parent3dc5f811def121a48c17bdb3bb419e5108675e04 (diff)
Support api key authentication
Diffstat (limited to 'mach2.py')
-rw-r--r--mach2.py48
1 files changed, 43 insertions, 5 deletions
diff --git a/mach2.py b/mach2.py
index f609534..fdd86c2 100644
--- a/mach2.py
+++ b/mach2.py
@@ -24,18 +24,21 @@ DATABASE = "app.db"
compress = Compress()
app = Flask(__name__)
-app.secret_key = """\xfc[\x16\x9d\x0f\x86;;\x9e_\x96\x01\xb7\xeay^\x8b\xa0E\x84
- \x91;\x18\xc2"""
app.config.from_object(__name__)
config = configparser.ConfigParser()
config.read("mach2.ini")
+app.config["DEBUG"] = config["DEFAULT"]["debug"]
+app.config["SECRET_KEY"] = config["DEFAULT"]["secret_key"]
+
login_manager = LoginManager()
login_manager.login_view = "login"
+config = configparser.ConfigParser()
+config.read("mach2.ini")
-login_manager.init_app(app)
-compress.init_app(app)
+login_manager = LoginManager()
+login_manager.login_view = "login"
def get_db():
@@ -62,6 +65,42 @@ def query_db(query, args=(), one=False):
return (rv[0] if rv else None) if one else rv
+@login_manager.request_loader
+def load_user(request):
+ # first, try to login using the api_key url arg
+ api_key = request.args.get('api_key', None)
+
+ if not api_key:
+ # next, try to login using Basic Auth
+ api_key = request.headers.get('Authorization', None)
+
+ if api_key:
+ api_key = api_key.replace('Basic ', '', 1)
+ try:
+ api_key = base64.b64decode(api_key)
+ except TypeError:
+ pass
+
+ if api_key:
+ user = None
+ result = query_db("SELECT * FROM user WHERE api_key = ?",
+ [api_key], one=True)
+
+ if result:
+ user = User(id=result[0],
+ username=result[1],
+ password_hash=result[2],
+ authenticated=0,
+ active=result[4],
+ anonymous=result[5])
+
+ if user:
+ return user
+
+ # finally, return None if both methods did not login the user
+ return None
+
+
@app.route("/")
@login_required
def index():
@@ -348,7 +387,6 @@ def login():
user = None
result = query_db("SELECT * FROM user WHERE username = ?",
[request.form["username"]], one=True)
-
if result:
user = User(id=result[0],
username=result[1],