#!/usr/bin/env ruby # coding: utf-8 # Get the access token and the access token secret require 'oauth' class AccessTokenGetter USAGE = 'Usage: ./get_access_token ' SITE_URI = 'https://www.hatena.com' REQUEST_TOKEN_URI = '/oauth/initiate?scope=read_public%2Cread_private%2Cwrite_public%2Cwrite_private' ACCESS_TOKEN_URI = '/oauth/token' AUTHORIZE_URI = 'https://www.hatena.ne.jp/oauth/authorize' def initialize(consumer_key, consumer_secret) @consumer_key = consumer_key @consumer_secret = consumer_secret @consumer = OAuth::Consumer.new(@consumer_key, @consumer_secret, oauth_callback: 'oob', site: SITE_URI, request_token_url: REQUEST_TOKEN_URI, access_token_url: ACCESS_TOKEN_URI, authorize_url: AUTHORIZE_URI) end def get_request_token @consumer.get_request_token end def get_access_token(request_token, oauth_verifier) # Maybe Hatena returns "parameter_rejected" # if "oauth_callback" is in the request header. # So oauth_callback is deleted from the header. @consumer.options.delete(:oauth_callback) begin access_token = request_token.get_access_token(oauth_verifier: oauth_verifier) rescue => problem raise "Fail to get the access token:\n" + problem.request.body end access_token end def self.get_access_token if ARGV.size != 2 warn USAGE exit end getter = AccessTokenGetter.new(ARGV[0], ARGV[1]) request_token = getter.get_request_token puts "Visit this website and get the PIN: #{request_token.authorize_url}" print 'Enter the PIN:' pin = (STDIN.readline).chomp access_token = getter.get_access_token(request_token, pin) puts "Access token: #{access_token.token}" puts "Access token secret: #{access_token.secret}" end end AccessTokenGetter.get_access_token