require 'json' require 'rest_client' module ADNAuthorize class Authorize def initialize @auth_url = "https://account.app.net/oauth/authenticate?client_id=#{TokiCLI::Toki::CLIENT_ID}&response_type=token&redirect_uri=#{TokiCLI::Toki::CALLBACK_URL}&scope=basic,messages&include_marker=1" @home = Dir.home + "/.TokiCLI" end def authorize puts "\e[H\e[2J" old = Dir.home + '/.toki_token' if File.exist?(old) puts "The old authorization token isn't valid anymore: the file '#{old}' has been deleted.\n\n" File.delete(old) end show_link token = get_token check_token(token) puts "\n\nThanks! Contacting App.net...\n\n" user = create_user_data(token, @home) puts "Creating TokiCLI folder in '#{user.home_path}' ...\n\n" Dir.mkdir("#{user.home_path}") unless Dir.exist?("#{user.home_path}") puts "Saving user token...\n\n" create_token_file(user) puts "Done!\n\n" end private def create_token_file(user) data = { token: user.token, id: user.id, username: user.username, handle: user.handle, home: user.home_path } File.write("#{user.home_path}/config.json", data.to_json) end def show_link puts "\nPlease click this URL, or copy/paste it in a browser:\n\n" puts @auth_url puts "\n" puts "then log in with your ADN credentials to authorize TokiCLI.\n\n" puts "You will then be redirected to a page showing a 'user token'.\n\n" puts "Copy the token then paste it here:\n" print "> " end def get_token STDIN.gets.chomp() end def check_token(token) if token.empty? || token.nil? puts "\n\nOops, something went wrong, I couldn't get the token. Please try again.\n\n" exit end end def create_user_data(token, home_path) resp = get_user(token) model = Struct.new(:resp, :username, :id, :handle, :home_path, :token) username = resp['data']['username'] model.new(resp, username, resp['data']['id'], "@" + username, home_path, token) end def get_user(token) JSON.parse(RestClient.get("https://api.app.net/users/me?access_token=#{token}", :verify_ssl => OpenSSL::SSL::VERIFY_NONE) {|response, request, result| response }) end end end