OSDN Git Service

0ea6cecac998ec8c5dcaff3dda30532c5576ac90
[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 following URL to get auth code;\n#{url}"
34       if ENV['DISPLAY']
35         %w(/usr/bin/xdg-open /usr/bin/X11/xdg-open /usr/local/bin/xdg-open
36                /usr/bin/x-www-browser /usr/bin/firefox /usr/local/bin/firefox
37               ).each do |bin|
38           File.executable?(bin) or next
39           exec(bin, url) if fork.nil?
40           return
41         end
42       end
43       case RUBY_PLATFORM
44       when /mswin|msys|mingw|cygwin|bccwin|wince|emc/
45         exec("start #{url}") if fork.nil?
46       when /darwin|mac os/
47         exec("/usr/bin/open", url) if fork.nil?
48       end
49     end
50
51     def prompt(msg = "", newline = false)
52       require 'readline'
53       msg += "\n" if newline
54       Readline.readline(msg, true).to_s.squeeze(" ").strip
55     end
56
57     def help
58       puts "#{$0} login"
59     end
60
61     def self.description
62       "Login and save access token."
63     end
64   end
65 end; end; end