Skip to content
This repository has been archived by the owner on Feb 6, 2024. It is now read-only.

Commit

Permalink
Extract some logic to a service
Browse files Browse the repository at this point in the history
  • Loading branch information
pencil committed Aug 10, 2014
1 parent 70fc1a4 commit 936074d
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 30 deletions.
34 changes: 4 additions & 30 deletions app/controllers/casino/auth_tokens_controller.rb
Original file line number Diff line number Diff line change
@@ -1,30 +1,13 @@
class CASino::AuthTokensController < CASino::ApplicationController
before_action :validate_auth_token_signature, :validate_auth_token_ticket

def login
raise "#{auth_token_data[:username]} logged in successfully"
user = validator_service.extract_user
redirect_to_login unless user
end

private
def validate_auth_token_signature
digest = OpenSSL::Digest::SHA256.new
Dir.glob(Rails.root.join('config/auth_token_signers/*.pem')) do |file|
key = OpenSSL::PKey::RSA.new File.read(file)
if key.verify(digest, auth_token_signature, auth_token)
logger.info "Successfully validated auth token signature with #{file}"
return true
end
end
logger.info 'Auth token signature is not valid'
redirect_to_login
end

def validate_auth_token_ticket
unless auth_token_ticket_valid?(auth_token_data[:ticket])
redirect_to_login
end
def validator_service
@validator_service ||= CASino::AuthTokenValidatorService.new(auth_token, auth_token_signature)
end

def redirect_to_login
redirect_to login_path(service: params[:service])
end
Expand All @@ -38,19 +21,10 @@ def auth_token
end

def base64_decode(data)
return '' if data.nil?
begin
Base64.strict_decode64(data)
rescue
''
end
end

def auth_token_data
JSON.parse(auth_token).symbolize_keys
end

def auth_token_ticket_valid?(auth_token_ticket)
CASino::AuthTokenTicket.consume(auth_token_ticket)
end
end
41 changes: 41 additions & 0 deletions app/services/casino/auth_token_validator_service.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
class CASino::AuthTokenValidatorService
AUTH_TOKEN_SIGNERS_GLOB = Rails.root.join('config/auth_token_signers/*.pem').freeze

attr_reader :token, :signature

def initialize(token, signature)
@token = token
@signature = signature
end

def extract_user
return false unless signature_valid?
return false unless ticket_valid?
raise "#{token_data[:username]} logged in successfully"
end

def token_data
begin
JSON.parse(token).symbolize_keys
rescue
{}
end
end

private
def signature_valid?
digest = OpenSSL::Digest::SHA256.new
Dir.glob(AUTH_TOKEN_SIGNERS_GLOB) do |file|
key = OpenSSL::PKey::RSA.new(File.read(file))
if key.verify(digest, signature, token)
Rails.logger.info("Successfully validated auth token signature with #{file}")
return true
end
end
false
end

def ticket_valid?
CASino::AuthTokenTicket.consume(token_data[:ticket])
end
end

0 comments on commit 936074d

Please sign in to comment.