-
-
Save xiaohui-zhangxh/48daed1bd55074e70b49990ae2895a3a to your computer and use it in GitHub Desktop.
Gem In a Box basic authentication & authorization rackup file
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
# | |
# This is a simple rackup file for geminabox. It allows simple role-based authorization. | |
# | |
# roles: | |
# - developer | |
# - upload | |
# - delete | |
# - admin (can do anything) | |
# | |
# For example, a developer who can access the service and upload new gems would have the following roles: `%w(developer upload) | |
# | |
require "rubygems" | |
require "geminabox" | |
Geminabox.data = "~/geminabox/data" | |
API_KEYS = { | |
'iEYig7hDfRQMxV' => { password: '', roles: %w(developer) }, | |
'fvxdU4xcj29qF6' => { password: '', roles: %w(admin) } | |
} | |
use Rack::Session::Pool, expire_after: 1000 # sec | |
use Rack::Protection | |
Geminabox::Server.helpers do | |
def protect!(role='developer') | |
unless has_role?(role) | |
response['WWW-Authenticate'] = %(Basic realm="Gem In a Box") | |
halt 401, "Not Authorized.\n" | |
end | |
end | |
def auth | |
@auth ||= Rack::Auth::Basic::Request.new(request.env) | |
end | |
def username | |
auth ? auth.credentials.first : nil | |
end | |
def password | |
auth ? auth.credentials.last : nil | |
end | |
def user_roles | |
API_KEYS[username][:roles] | |
end | |
def authenticated? | |
return false unless auth.provided? && auth.basic? && auth.credentials | |
api_key = API_KEYS[username] | |
!api_key.nil? && password == api_key[:password] | |
end | |
def current_user_roles | |
authenticated? ? user_roles : [] | |
end | |
def has_role?(role) | |
current_user_roles.include?('admin') || current_user_roles.include?(role) | |
end | |
end | |
Geminabox::Server.before '/upload' do | |
protect!('upload') | |
end | |
Geminabox::Server.before do | |
if request.delete? | |
protect!('delete') | |
else | |
protect!('developer') | |
end | |
end | |
Geminabox::Server.before '/api/v1/gems' do | |
unless env['HTTP_AUTHORIZATION'] == 'API_KEY' | |
halt 401, "Access Denied. Api_key invalid or missing.\n" | |
end | |
end | |
run Geminabox::Server |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment