Updated copyrights-blurb in all application files
[gitorious:mainline.git] / lib / gitorious / ssh / client.rb
1 # encoding: utf-8
2 #--
3 #   Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies)
4 #   Copyright (C) 2007, 2008 Johan Sørensen <johan@johansorensen.com>
5 #   Copyright (C) 2008 Tor Arne Vestbø <tavestbo@trolltech.com>
6 #
7 #   This program is free software: you can redistribute it and/or modify
8 #   it under the terms of the GNU Affero General Public License as published by
9 #   the Free Software Foundation, either version 3 of the License, or
10 #   (at your option) any later version.
11 #
12 #   This program is distributed in the hope that it will be useful,
13 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #   GNU Affero General Public License for more details.
16 #
17 #   You should have received a copy of the GNU Affero General Public License
18 #   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #++
20
21 require "net/http"
22
23 module Gitorious
24   module SSH  
25     class AccessDeniedError < StandardError; end
26   
27     class Client
28       def initialize(strainer, username)
29         @strainer = strainer
30         @project_name, @repository_name = strainer.path.split("/", 2)
31         @repository_name.gsub!(/\.git$/, "")
32         @user_name = username
33       end
34       attr_accessor :project_name, :repository_name, :user_name
35     
36       def writable_by_user?
37         query_for_permission_and_path
38         @writable == "true"
39       end
40     
41       def assure_user_can_write!
42         writable_by_user? || raise(AccessDeniedError)
43       end
44     
45       def query_url
46         url = ["/#{@project_name}"]
47         url << @repository_name
48         url << "writable_by?username=#{@user_name}"
49         url.join("/")
50       end
51       
52       def real_path
53         query_for_permission_and_path
54         full_real_path = File.join(GitoriousConfig["repository_base_path"], @real_path)
55         if !@real_path || @real_path == "nil" || !File.exist?(full_real_path)
56           raise AccessDeniedError
57         end
58         full_real_path
59       end
60     
61       def to_git_shell_argument
62         "#{@strainer.verb} '#{real_path}'"
63       end
64       
65       def query_for_permission_and_path
66         if !@writable || !@real_path
67           $stderr.puts "Querying #{query_url}" if $DEBUG
68           resp = connection.get(query_url)
69           @writable, @real_path = resp.body.split(" ")
70         end
71       end
72     
73       protected
74         def connection
75           port = GitoriousConfig["gitorious_client_port"]
76           host = GitoriousConfig["gitorious_client_host"]
77           @connection ||= Net::HTTP.start(host, port)
78         end
79     end
80   end
81 end