OSDN Git Service

ddb3352e8b94804cf712c33bd015797eda5fc414
[osdn-codes/osdn-cli.git] / lib / osdn / cli / command / login.rb
1 module OSDN; module CLI; module Command
2   class Login < Base
3     def run
4       logger.debug "Trying login"
5       scope = %w(profile group group_write)
6
7       auth_url = "https://#{OSDNClient.configure.host}/account/oauth2ui/authorize?client_id=#{CLI.client_id}&state=cli#{Time.now.to_i}&response_type=code&scope=#{scope.join('%20')}"
8
9       launch_brwoser auth_url
10       puts
11       authcode = prompt("Type your auth code: ")
12       puts
13       if authcode.empty?
14         logger.error "Empty auth code, login has been canceled."
15         return
16       end
17
18       api = OSDNClient::DefaultApi.new
19       begin
20         set_credential api.token(CLI.client_id, CLI.client_secret, code: authcode)
21       rescue OSDNClient::ApiError => e
22         begin
23           err = JSON.parse(e.response_body)
24           logger.fatal err["error_description"]
25         rescue
26           logger.fatal "Failed to get access token"
27         end
28         return
29       end
30     end
31
32     def launch_brwoser(url)
33       puts "Access follwoing URL to get auth code;\n#{url}"
34       %w(/usr/bin/xdg-open /usr/bin/X11/xdg-open /usr/local/bin/xdg-open
35              /usr/bin/x-www-browser /usr/bin/firefox /usr/local/bin/firefox
36             ).each do |bin|
37         File.executable?(bin) or next
38         exec(bin, url) if fork.nil?
39         return
40       end
41       case RUBY_PLATFORM
42       when /mswin|msys|mingw|cygwin|bccwin|wince|emc/
43         exec("start #{url}") if fork.nil?
44       when /darwin|mac os/
45         exec("/usr/bin/open", url) if fork.nil?
46       end
47     end
48
49     def prompt(msg = "", newline = false)
50       require 'readline'
51       msg += "\n" if newline
52       Readline.readline(msg, true).to_s.squeeze(" ").strip
53     end
54
55     def help
56       puts "#{$0} login"
57     end
58
59     def self.description
60       "Login and save access token."
61     end
62   end
63 end; end; end