-
-
Save jamiehodge/6341102 to your computer and use it in GitHub Desktop.
auth plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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