Reputation: 7466
For every request in Bottle I would like to check if the request is eligible through HTTP authentication. My idea is to use a function, which is called at the start of every @route
function.
def check_authentificaiton(requests):
auth = request.headers.get('Authorization')
credentials = parse_auth(auth)
if credentials[0] is not 'user' or credentials[1] is not 'password':
raise Exception('Request is not authorized')
This seems a bit redundant, since I want to protect every request, and it could fail if I forget to call it. Is there a better way?
Upvotes: 1
Views: 4027
Reputation: 38899
I think you are looking for a decorator which mandates a route to be accessed only if the user is loggedin. Like in the example below, @require_uid
is a decorator which you can use around any function where you need user to be logged in. Flask has a login_required decorator.
Using decorators to require sign in with bottle.py
def require_uid(fn):
def check_uid(**kwargs):
cookie_uid = request.get_cookie('cookieName', secret='cookieSignature')
if cookie_uid:
# do stuff with a user object
return fn(**kwargs)
else:
redirect("/loginagain")
return check_uid
@route('/userstuff', method='GET')
@require_uid
@view('app')
def app_userstuff():
# doing things is what i like to do
return dict(foo="bar")
Upvotes: 6