Skip to content

Instantly share code, notes, and snippets.

@mmerickel
Last active March 6, 2016 17:04
Show Gist options
  • Save mmerickel/95494959d2f349a1728c to your computer and use it in GitHub Desktop.
Save mmerickel/95494959d2f349a1728c to your computer and use it in GitHub Desktop.
roll your own basic auth in pyramid
"""
Let's pretend Pyramid doesn't have an enterprise-grade auth system
that can support several workflows. Make our own with decorators!
"""
import base64
from pyramid.httpexceptions import HTTPUnauthorized
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return username == 'admin' and password == 'secret'
def parse_basic(request):
try:
auth_method, auth_token = request.authorization
if auth_method == 'Basic':
user, pw = base64.b64decode(auth_token.strip()).split(':', 1)
return user, pw
except:
pass
def requires_auth(fn):
def wrapper(context, request):
auth = parse_basic_auth(request)
if not auth or not check_auth(auth[0], auth[1]):
resp = HTTPUnauthorized()
resp.headers.update([
('WWW-Authenticate', 'Basic realm="Login Required"')
])
raise resp
return fn(context, request)
return wrapper
@view_config(
route_name='home',
decorator=[requires_auth],
renderer='string'
)
def home_view(request):
return 'hello'
"""
Utilize a custom authorization policy to check permissions against
principals however we want.
"""
from pyramid.authentication import BasicAuthenticationPolicy
from pyramid.security import Authenticated, Allowed, Denied
from pyramid.view import forbidden_view_config, view_config
class StupidSimpleAuthorizationPolicy(object):
def permits(self, context, principals, permission):
# who cares about permissions anyway?
if Authenticated in principals:
return Allowed
return Denied
def check_auth(username, password, request):
"""This function is called to check if a username /
password combination is valid.
"""
return username == 'admin' and password == 'secret'
config = Configurator()
config.set_authorization_policy(StupidSimpleAuthorizationPolicy())
config.set_authentication_policy(BasicAuthenticationPolicy(
check=check_auth,
realm='Login Required',
))
@forbidden_view_config()
def forbidden_view(request):
resp = HTTPUnauthorized()
reps.headers.update(forget(request))
return resp
@view_config(
route_name='home',
permission='yes please',
renderer='string',
)
def home_view(request):
return 'hello world'
@digitalresistor
Copy link

@digitalresistor
Copy link

Don't listen to @bertjwregeer he's a terrible person.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment