Last active
April 13, 2019 20:48
-
-
Save KonnorRogers/44c4e78a9d2d29f5db8e521e168d8bb5 to your computer and use it in GitHub Desktop.
Retrieving all github ssh keys and iterating through them to match your key
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
# This is using the v3 of github API, I could not find a guide for ssh keys | |
# within the github api v4 | |
# reading public keys, you need admin:public_key & admin:read_key | |
# https://developer.github.com/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/ | |
# Both libraries are part of the ruby standard library | |
require 'net/http' | |
require 'json' | |
# @param uri [URI] the url of website youre querying | |
# @return [String] Returns a JSON formatted string | |
def start_connection(uri) | |
Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http| | |
response = yield(http) | |
response.body | |
end | |
end | |
# @param uri [URI] The url where youre querying | |
# @return Net::HTTP::Get | |
def get_request(uri) | |
token = "token #{ENV['GITHUB_TOKEN']}" | |
headers = { 'Content-Type' => 'application/json', | |
'Accepts' => 'application/json', | |
'Authorization' => token } | |
Net::HTTP::Get.new(uri, headers) | |
end | |
# The full github http request which will return the json for all your ssh keys | |
# @return String returns a json string to be parsed | |
def full_http_request | |
uri = URI('https://api.github.com/user/keys') | |
request = get_request(uri) | |
start_connection(uri) do |http| | |
http.request(request) | |
end | |
end | |
# parses a json string then iterates through each string to return | |
# the value of all ssh keys of your github profile | |
# @return [Array<String>] Returns an array of ssh keys in a String data type | |
def array_of_keys(json_string) | |
# when parsed, returns an array | |
JSON.parse(json_string).map { |key| key['key'] } | |
end | |
# checks if the ssh key is found within your public keys | |
# @param original_key [String] The string value of your ssh key | |
# @param array [Array<String>] The array of ssh keys which you are seeing if your ssh key is a part of | |
# @return [Boolean] | |
def ssh_key_exists?(original_key, array) | |
return true if array.include?(original_key) | |
false | |
end | |
# Typical ssh key location | |
ssh_file = File.join(Dir.home, '.ssh', 'id_rsa.pub') | |
# Accounts for if you have a comment in your key and removes it | |
# when pulling keys from github, it does not recognize comments | |
original_ssh_key = File.read(ssh_file).split('==')[0].concat('==') | |
ssh_keys_array = array_of_keys(full_http_request) | |
puts ssh_key_exists?(original_ssh_key, ssh_keys_array) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment