require 'launchy' require 'httparty' require 'heroku' class Auth < BASECLI CREDENTIALS_PATH = "#{ENV["HOME"]}/.railsonfire/" CREDENTIALS_FILE = CREDENTIALS_PATH + "credentials" desc "login", "Authenticate the local machine with Railsonfire" def login if File.exists?(CREDENTIALS_FILE) say "Credentials Found. Checking with Railsonfire Servers" token = File.read(CREDENTIALS_FILE) else Dir.mkdir(CREDENTIALS_PATH) unless File.exists?(CREDENTIALS_PATH) token = load_token_from_heroku token ||= ask_user_for_token File.open(CREDENTIALS_FILE, "w").tap do |file| file.write(token) file.close end end begin response = HTTParty.get("#{Railsonfire::DOMAIN}/users/#{token}/token") if response.code == 200 || response.code == 404 Railsonfire.login(token, response.body) send_signal :logged_in success "Credentials verified and logged in successfully" true else error "Couldn't authenticate with Railsonfire servers. Please try again and check your Token." notify("login", "Couldn't authenticate with railsonfire", {:token => token, :body => response.body}) logout exit end rescue Exception => e exit if e.class == SystemExit logout error "There was an Error when communicating with the Railsonfire server." error "Please login again and make sure you logged in with the correct Railsonfire Token." notify(e.class, "Request Error: #{e.message}", {:backtrace => e.backtrace, :error_class => e.class}) exit end end desc "logout", "Delete all Authentication Data from the local machine" def logout say "Removing local credentials" File.delete(CREDENTIALS_FILE) if File.exists?(CREDENTIALS_FILE) end private def load_token_from_heroku unless Heroku::Auth.read_credentials warning "You are not authenticated with Heroku locally, thus we can not automatically detect your credentials." return nil end success "Reading your credentials from Heroku.This may take a few seconds." h = heroku apps = h.get_apps.body.collect{|app| railsonfire_id = h.get_config_vars(app["name"]).body["RAILSONFIRE_ID"]; railsonfire_id ? [app["name"], railsonfire_id] : nil}.compact case apps.count when 0 error("Couldn't find any Heroku Addon Data for Railsonfire.") return nil when 1 app = apps.first else warning "You seem to have added Railsonfire to several apps. Please select the Heroku App you want to register with" app = select("Please select the Heroku App you added our Addon to", apps){|element, index| "#{index}. #{element.first}"} end response = post_json("#{Railsonfire::DOMAIN}/heroku/exchange_token", {:railsonfire_id => app.last, :email => Heroku::Auth.get_credentials.first}) response.code == 200 ? response.body : nil end def ask_user_for_token success("Please enter your Railsonfire Token. The Website to copy the token will open shortly") Launchy.open("https://www.railsonfire.com/users/edit") ask("Key:") end end