From b5b2a5a120054abd82c1d9b60c097a49052a6015 Mon Sep 17 00:00:00 2001 From: Fijxu Date: Fri, 19 Jul 2024 18:13:41 -0400 Subject: [PATCH] 0.2.5: Add token validation. --- src/main.cr | 18 ++++++++++++++++++ src/routes/routes.cr | 5 +++++ src/utils/utils.cr | 16 ++++++++++++++++ 3 files changed, 39 insertions(+) diff --git a/src/main.cr b/src/main.cr index f553afd..712e320 100644 --- a/src/main.cr +++ b/src/main.cr @@ -3,6 +3,7 @@ require "kemal" require "json" require "uri" require "redis" +require "colorize" require "./config" require "./routes/**" @@ -19,6 +20,22 @@ REDIS_UTILS = TwAPI::Utils::Redis REDIS_DB = Redis::Client.new(URI.parse("redis://#{CONFIG.redis_addr}/#{CONFIG.redis_database}#?keepalive=true")) puts "Connected to Redis" +# Fiber +spawn do + loop do + begin + response = JSON.parse(TwAPI::Utils.validate_token) + puts "#{"[INFO]".colorize(:green)} Token information:" + puts "Client-Id:\t\t#{response["client_id"]}" + puts "Login:\t\t\t#{response["login"]}" + puts "Token exipires in:\t#{response["expires_in"]} (#{response["expires_in"] == 0 ? "Token does not expire" : Time.utc.shift(response["expires_in"].to_s.to_i, 0)})" + rescue ex + puts "#{"[ERROR]".colorize(:red)} #{ex.message}" + end + sleep 3600 + end +end + TwAPI::Routes.register_misc TwAPI::Routes.register_all_twitch @@ -27,3 +44,4 @@ TwAPI::Routes.register_all_twitch {% end %} Kemal.run +Fiber.yield \ No newline at end of file diff --git a/src/routes/routes.cr b/src/routes/routes.cr index fff8faa..17e8e58 100644 --- a/src/routes/routes.cr +++ b/src/routes/routes.cr @@ -26,6 +26,11 @@ module TwAPI::Routes get "/v2" do {"message": "Welcome to v2, There is no docs!"}.to_json end + + get "/twitch_expiration" do + response = JSON.parse(TwAPI::Utils.validate_token) + {"message": "Token exipires in: #{response["expires_in"]} (#{response["expires_in"] == 0 ? "Token does not expire" : Time.utc.shift(response["expires_in"].to_s.to_i, 0)})"}.to_json + end end def register_all_twitch diff --git a/src/utils/utils.cr b/src/utils/utils.cr index c0ec7cd..30de26d 100644 --- a/src/utils/utils.cr +++ b/src/utils/utils.cr @@ -1,3 +1,19 @@ module TwAPI::Utils extend self + + def validate_token + puts "#{"[INFO]".colorize(:green)} Validating twitch token..." + headers = HTTP::Headers{ + "Content-Type" => "application/json", + "Authorization" => "OAuth #{CONFIG.helixOAuth}", + "Client-Id" => "#{CONFIG.helixClientID}", + } + response = HTTP::Client.get("https://id.twitch.tv/oauth2/validate", headers: headers) + + if response.success? + response.body + else + raise "Helix OAuth Token validation failed. #{response.status_code}: #{response.body}" + end + end end