class Gist::User
Class to hold user information
Attributes
access_token[RW]
password[RW]
username[RW]
Public Class Methods
new(username = nil, password = nil, netrc = nil)
click to toggle source
Create the GistUser instance
# File lib/gist/user.rb, line 9 def initialize(username = nil, password = nil, netrc = nil) @username ||= username @password ||= password @netrc ||= netrc @http = Net::HTTP.new(Gist::API_URL, Gist::API_PORT) @http.use_ssl = true @access_token = load_token if saved? end
Public Instance Methods
authenticate()
click to toggle source
Authentication method, will set the authentication token for the user
# File lib/gist/user.rb, line 19 def authenticate # If we already have authenticated, don't let it happen again return unless @access_token.nil? # If not, let's authenticate @http.start do |http| response = http.request(auth_obj) json_response = JSON.parse(response.body) @access_token = json_response['token'] end # Then save save populate_methods(user_info) end
Private Instance Methods
auth_obj()
click to toggle source
# File lib/gist/user.rb, line 80 def auth_obj req = Net::HTTP::Post.new('/authorizations') req.basic_auth(@username, @password) req['Content-Type'] = 'application/json' req.body = { scopes: ['gist'], # Only need Gist scope note: "Gist access for GistRB client on #{Socket.gethostname}", note_url: 'https://github.com/cameronbroe/gistrb' }.to_json req end
load_token()
click to toggle source
# File lib/gist/user.rb, line 70 def load_token if @netrc.nil? File.readlines(Gist::ACCESS_TOKEN_PATH).first else netrc = Netrc.read _username, token = netrc['api.github.com'] token end end
populate_methods(response)
click to toggle source
# File lib/gist/user.rb, line 39 def populate_methods(response) response.each do |k, v| define_singleton_method(k) { v } end end
save()
click to toggle source
# File lib/gist/user.rb, line 55 def save if @netrc.nil? unless Dir.exist?(File.dirname(Gist::ACCESS_TOKEN_PATH)) Dir.mkdir(File.dirname(Gist::ACCESS_TOKEN_PATH)) end token_file = File.new(Gist::ACCESS_TOKEN_PATH, 'w+') token_file << @access_token token_file.close else netrc = Netrc.read netrc['api.github.com'] = @username, @access_token netrc.save end end
saved?()
click to toggle source
# File lib/gist/user.rb, line 45 def saved? if @netrc.nil? File.exist?(Gist::ACCESS_TOKEN_PATH) else netrc = Netrc.read _username, token = netrc['api.github.com'] !token.nil? end end
user_info()
click to toggle source
# File lib/gist/user.rb, line 33 def user_info headers = { 'Authorization' => "token #{access_token}" } response = @http.get('/user', headers) JSON.parse(response.body) end