gitlab-org--gitlab-foss/lib/gitlab/backend/grack_auth.rb

109 lines
2.4 KiB
Ruby
Raw Normal View History

2013-02-14 13:25:55 +00:00
require_relative 'shell_env'
require_relative 'grack_ldap'
require_relative 'grack_helpers'
2013-02-14 13:25:55 +00:00
module Grack
class Auth < Rack::Auth::Basic
include LDAP
include Helpers
attr_accessor :user, :project, :ref, :env
def call(env)
@env = env
@request = Rack::Request.new(env)
@auth = Request.new(env)
2013-01-10 18:17:57 +00:00
# Need this patch due to the rails mount
@env['PATH_INFO'] = @request.path
@env['SCRIPT_NAME'] = ""
auth!
end
private
def auth!
return render_not_found unless project
if @auth.provided?
return bad_request unless @auth.basic?
# Authentication with username and password
login, password = @auth.credentials
2013-05-24 17:36:28 +00:00
@user = authenticate_user(login, password)
2013-05-24 17:36:28 +00:00
if @user
Gitlab::ShellEnv.set_env(@user)
@env['REMOTE_USER'] = @auth.username
else
return unauthorized
end
else
return unauthorized unless project.public
end
if authorized_git_request?
@app.call(env)
else
unauthorized
end
end
def authorized_git_request?
2012-06-29 07:43:15 +00:00
# Git upload and receive
if @request.get?
authorize_request(@request.params['service'])
elsif @request.post?
authorize_request(File.basename(@request.path))
else
false
2012-06-29 07:43:15 +00:00
end
end
def authenticate_user(login, password)
2013-07-16 08:28:19 +00:00
auth = Gitlab::Auth.new
auth.find(login, password)
2013-05-24 17:36:28 +00:00
end
def authorize_request(service)
case service
when 'git-upload-pack'
project.public || can?(user, :download_code, project)
when'git-receive-pack'
action = if project.protected_branch?(ref)
:push_code_to_protected_branches
else
:push_code
end
can?(user, action, project)
else
false
end
end
def project
@project ||= project_by_path(@request.path_info)
end
def ref
@ref ||= parse_ref
end
def parse_ref
input = if @env["HTTP_CONTENT_ENCODING"] =~ /gzip/
Zlib::GzipReader.new(@request.body).read
else
@request.body.read
end
2012-10-22 15:45:42 +00:00
# Need to reset seek point
@request.body.rewind
/refs\/heads\/([\w\.-]+)/n.match(input.force_encoding('ascii-8bit')).to_a.last
2013-05-24 17:36:28 +00:00
end
end
end