Skip to content

Commit

Permalink
Scaffolds use of a cookie for auth
Browse files Browse the repository at this point in the history
  • Loading branch information
jaredbriskman committed May 3, 2018
1 parent 25a454d commit 8d2416f
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
1 change: 1 addition & 0 deletions .env.template
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
HOST="127.0.0.1"
PORT="3000"
HSTS_ENABLE=""
SHARED_SECRET=""
21 changes: 18 additions & 3 deletions abe/auth/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import os
from functools import wraps

from flask import request, abort
from flask import request, abort, g
from netaddr import IPNetwork, IPSet

# A set of IP addresses with edit permission.
Expand All @@ -17,14 +17,29 @@
INTRANET_IPS = (IPSet([IPNetwork(s) for s in os.environ.get('INTRANET_IPS', '').split(',')])
if 'INTRANET_IPS' in os.environ else IPSet(['0.0.0.0/0', '0000:000::/0']))

shared_secret = os.environ["SHARED_SECRET"] # Should fail if not set


def after_this_request(f): # For setting cookie
if not hasattr(g, 'after_request_callbacks'):
g.after_request_callbacks = []
g.after_request_callbacks.append(f)
return f


def edit_auth_required(f):
"Decorates f to raise an HTTP UNAUTHORIZED exception if the client IP is not in the list of authorized IPs."
@wraps(f)
def wrapped(*args, **kwargs):
client_ip = request.headers.get(
'X-Forwarded-For', request.remote_addr).split(',')[-1]
if client_ip not in INTRANET_IPS:
abort(401)
if client_ip in INTRANET_IPS:
@after_this_request
def remember_language(response):
response.set_cookie('app_secret', shared_secret)
else:
with request.cookies.get('app_secret') as app_secret:
if app_secret != shared_secret:
abort(401)
return f(*args, **kwargs)
return wrapped
4 changes: 4 additions & 0 deletions app.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@
"description": "Enforce SSL via HSTS",
"value": "True",
"required": true
},
"SHARED_SECRET": {
"description": "A secret key for verifying the integrity of signed cookies.",
"generator": "secret"
}
},
"formation": {
Expand Down

0 comments on commit 8d2416f

Please sign in to comment.