Created
August 19, 2013 03:54
-
-
Save pjc0247/6265639 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
require 'net/http/persistent' | |
require 'json' | |
SERVER_PREFIX = "http://anz.previrtu.com/test/" | |
# 발급받는곳 | |
# http://anz.previrtu.com/test/generate_app_token.php?name=app_name | |
CLIENT_ID = "c9b7a5b47fb09db8e9b4302ea86b32f0" | |
CLIENT_SECRET = "39df9efca429ba8ea8afcbc75cce54c3" | |
USER_ID = "pjc0247" | |
def send_query(http, query) | |
uri = URI.parse SERVER_PREFIX + query | |
response = http.request(uri) | |
result = JSON.parse(response.body) | |
return result["status"], result | |
end | |
def check_token(http, token) | |
send_query(http, "is_valid_token.php?token=" + token) | |
end | |
def request_token(http, user_id) | |
send_query(http, "login.php?client_id=" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET + "&user_id=" + user_id) | |
end | |
def query_user(http, token) | |
send_query(http, "user.php?token=" + token) | |
end | |
def delete_token(http, token) | |
send_query(http, "logout.php?token=" + token) | |
end | |
def has_token? | |
return false if File.exist?("token") == false | |
fp = File.new("token", "r") | |
token = fp.readline | |
fp.close | |
return token | |
end | |
def refresh_token(http) | |
status, data = request_token(http, USER_ID) | |
token = data["msg"] | |
raise ret["msg"] if status != 0 | |
fp = File.new("token", "w") | |
fp.write token | |
fp.close | |
return status, token | |
end | |
begin | |
http = Net::HTTP::Persistent.new | |
# 토큰을 가져오는 부분 | |
token = has_token? | |
if token == false # 토큰 없으면 새로 발급 | |
refresh_token(http) | |
else | |
status, data = check_token(http, token) | |
if status != 0 # 이미 가지고있는 토큰이 폐기된 토큰이어도 재발급 | |
puts "token is expired." | |
puts "refreshing...\n\n" | |
status, token = refresh_token(http) | |
end | |
end | |
puts "Your token : " + token.to_s + "\n\n" | |
# 현재 유저 정보를 가져오는 부분 | |
status, ret = query_user(http, token) | |
raise ret["msg"] if status != 0 | |
puts "User Info" | |
puts " id : " + ret["user_id"] | |
puts " nick : " + ret["nick"] | |
puts " profile_img : " + ret["img"] | |
puts " msg_blocked : " + ret["msg_blocked"].to_s | |
# 토큰을 지운다 ( 테스트용 ) | |
delete_token(http, token) | |
http.shutdown | |
rescue | |
puts "error : #{$!}" | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment