Created
January 7, 2018 10:07
-
-
Save andrey-kazakov/2429ef90e9a6512a4325ee02872cc733 to your computer and use it in GitHub Desktop.
Simple service for checking user's authenticity (and community role) for VK Iframe-apps.
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
module Vk::Web | |
class Authenticator | |
VK_VIEWER_TYPES = %i[not_participant participant moderator editor administrator].freeze | |
def initialize(params:) | |
@params = params | |
end | |
def real_viewer? | |
api_id_valid? && auth_key_valid? && signature_valid? | |
end | |
def viewer_type?(type) | |
@params[:viewer_type].to_i >= VK_VIEWER_TYPES.index(type) | |
end | |
private | |
def api_id_valid? | |
@params[:api_id].to_i == Rails.application.secrets.vk_api_id | |
end | |
def auth_key_valid? | |
ActiveSupport::SecurityUtils.secure_compare( | |
Digest::MD5.hexdigest(format_auth_key_params), | |
@params[:auth_key] | |
) | |
end | |
def format_auth_key_params | |
[ | |
@params[:api_id], | |
@params[:viewer_id], | |
Rails.application.secrets.vk_api_secret | |
].join("_") | |
end | |
def signature_valid? | |
ActiveSupport::SecurityUtils.secure_compare( | |
OpenSSL::HMAC.hexdigest( | |
OpenSSL::Digest.new("sha256"), | |
Rails.application.secrets.vk_api_secret, | |
format_signature_params | |
), | |
@params[:sign] | |
) | |
end | |
def format_signature_params | |
hash = @params.to_unsafe_h | |
hash.delete("hash") | |
hash.delete("api_result") | |
hash.delete("sign") | |
# utm params are esaped in signature, when others arne't | |
hash.each_pair do |key, value| | |
hash[key] = CGI.escape(value) if key.start_with?("utm_") | |
end | |
hash.values.join | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment