Skip to content

Instantly share code, notes, and snippets.

@jamiehodge
Last active December 21, 2015 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamiehodge/6341102 to your computer and use it in GitHub Desktop.
Save jamiehodge/6341102 to your computer and use it in GitHub Desktop.
auth plugin
require 'base64'
class Zoidberg::Plugin::Auth
Zoidberg::Plugin.define :auth, self
def initialize(app)
app.generic_controller.send(:include, InstanceMethods)
end
module InstanceMethods
def basic(realm = 'realm', &blk)
Basic.new(self, realm).authenticate(&blk)
end
end
private
class Scheme
def initialize(c, realm)
@c = c
@realm = realm
end
def authorization
@c.req.headers.authorization && @c.req.headers.authorization.split(/ /, 2)
end
def name
authorization.first
end
def params
authorization.last
end
def bad_request
@c.res.status = 400
@c.res.body.close
@c.serve
throw :halt
end
def unauthorized
@c.res.status = 401
@c.res.headers.www_authenticate = challenge % @realm
@c.res.body.close
@c.serve
throw :halt
end
end
class Basic < Scheme
def authenticate(&blk)
return unauthorized unless authorization
return bad_request unless valid?
result = blk.call(username, password)
return result if result
unauthorized
end
def challenge
'Basic realm="%s"'
end
def params
Base64.decode64(super).split(/:/, 2)
end
def username
params.first
end
def password
params.last
end
def valid?
name =~ /^basic$/i
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment