/
generate_access_token
executable file
·46 lines (33 loc) · 1.43 KB
/
generate_access_token
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/env ruby
require "json"
require "uri"
require "net/http"
class String
def green; "\033[32m#{self}\033[0m" end
def cyan; "\033[36m#{self}\033[0m" end
end
puts "1. Register an app at `https://docs.pcloud.com/my_apps/`".cyan
puts "2. Enter the client id and secret for the app:".cyan
print "Client ID > "
client_id = $stdin.gets.chomp.freeze
print "Client Secret > "
client_secret = $stdin.gets.chomp.freeze
puts "3. Enter the data region of your pCloud account [EU/US]:".cyan
print "> "
region_specific_api_base = $stdin.gets.chomp == "EU" ? "eapi.pcloud.com" : "api.pcloud.com"
puts "4. Navigate to this URL to start the access code flow:".cyan
puts "`https://my.pcloud.com/oauth2/authorize?client_id=#{client_id}&response_type=code`"
puts "5. After logging in, enter the access code provided below:".cyan
print "> "
access_code = $stdin.gets.chomp.freeze
puts "6. Requesting access token from pCloud...".cyan
query = { client_id: client_id, client_secret: client_secret, code: access_code }
uri = URI.parse("https://#{region_specific_api_base}/oauth2_token?#{URI.encode_www_form(query)}")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri)
request["Accept"] = "application/json"
response = http.request(request)
json_response = JSON.parse(response.body)
raise json_response["error"] if json_response["error"]
puts "Done! Your access token is: #{json_response["access_token"]}".green