Created
November 25, 2012 17:59
-
-
Save werebus/4144579 to your computer and use it in GitHub Desktop.
An example SSH-key-adding class for Github
This file contains 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 '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