Skip to content

Instantly share code, notes, and snippets.

@yock
Created April 26, 2017 22:23
Show Gist options
  • Save yock/b27a3ad7938b8beb3028bb1ffd62a09c to your computer and use it in GitHub Desktop.
Save yock/b27a3ad7938b8beb3028bb1ffd62a09c to your computer and use it in GitHub Desktop.
class AuthenticateController < ApplicationController
DIGEST = OpenSSL::Digest::SHA256.new
def show
end
def create
nonce = Time.now.to_i
token = SecureRandom.hex
hmac = OpenSSL::HMAC.digest(DIGEST, 'soopersecret', "#{nonce}#{token}")
encoded_hmac = ERB::Util.url_encode Base64.strict_encode64(hmac)
redirect_to "http://consumer.dev/auth?token=#{token}&mac=#{encoded_hmac}&nonce=#{nonce}"
end
end
class AuthController < ApplicationController
DIGEST = OpenSSL::Digest::SHA256.new
NONCE_MAX_AGE = 30.seconds
def verify
nonce = params['nonce']
token = params['token']
decoded = Base64.strict_decode64(URI.unescape(params['mac']))
local = OpenSSL::HMAC.digest(DIGEST, 'soopersecret', "#{nonce}#{token}")
if (decoded == local) and not nonce_expired?
cookies['token'] = token
redirect_to root_path
else
head 403
end
end
def nonce_expired?
age = Time.now - params['nonce'].to_i
age <= NONCE_MAX_AGE
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment