Skip to content

Instantly share code, notes, and snippets.

@werebus
Created November 25, 2012 17:59
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 werebus/4144579 to your computer and use it in GitHub Desktop.
Save werebus/4144579 to your computer and use it in GitHub Desktop.
An example SSH-key-adding class for Github
require 'rubygems'
require 'httparty'
require 'io/console'
class GithubApi
include HTTParty
base_uri 'https://api.github.com'
def initialize(username, password)
@auth = {:username => username, :password => password}
self.class.headers({"Authorization" => "token #{token}"})
end
def token
if @token
@token
else
auth = authorizations.find {|a| a['app']['name'] =~ /umts-smeagol/} ||
self.class.post("/authorizations", :basic_auth => @auth, :body => auth_template).parsed_response
@token = auth['token']
end
end
def authorizations
auth = self.class.get("/authorizations", :basic_auth => @auth)
if auth.response.class == Net::HTTPOK
return auth
else
raise ResponseError, auth.response
end
end
def auth_template
{"note"=>"umts-smeagol",
"note_url"=>"https://github.com/umts/smeagol",
"scopes"=>["user"]}.to_json
end
def add_key(public_key)
response = self.class.post("/user/keys",
:body => { "title" => "testing", "key" => public_key }.to_json)
return response.code == 201
end
end
user = 'werebus'
print "Enter password for #{user}: "
passwd = STDIN.noecho(&:gets).chomp
gh = GithubApi.new(user, passwd)
keyfile = File.open(File.join(ENV['HOME'], ".ssh", "id_rsa.pub"))
puts "No go" unless gh.add_key(keyfile.read)
keyfile.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment