class MultipartSignaturesController < ApplicationController
  skip_after_action :verify_authorized

  def create
    render plain: hmac_data, status: 200
  end

  private

  def hmac_data
    aws_secret = ENV['AWS_SECRET_ACCESS_KEY']
    timestamp = params[:datetime]

    # TESTING UTF-8 encoding
    aws_secret = aws_secret.encode('UTF-8')
    details = params[:to_sign].encode('UTF-8')

    date = hmac("AWS4#{aws_secret}", timestamp[0..7])
    region = hmac(date, ENV["AWS_REGION"])
    service = hmac(region, "s3")
    signing = hmac(service, 'aws4_request')

    hexhmac(signing, details)
  end

  def hmac(key, value)
    OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), key, value)
  end

  def hexhmac(key, value)
    OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), key, value)
  end
end
