require 'test_helper'
require 'ipaddr'

class TokenTest < ActiveSupport::TestCase

	def setup
		@frozen_time = Time.now
	end

	def teardown
		Token.delete_all()
	end

	test "should authentificate" do
		Timecop.freeze(@frozen_time) do
			Token.save_session({token: "123", ip: "8.8.8.8", created_at: Time.now})
			assert !! Token.authenticate({token: "123", created_at: Time.now, ip: "8.8.8.8"})
		end
	end

	test "shouldnt auth with wrong token" do
		Timecop.freeze(@frozen_time) do
			Token.save_session({token: "123", ip: "8.8.8.100", created_at: @frozen_time})
			assert_false !! Token.authenticate({token: "14423", created_at: @frozen_time, ip: "8.8.8.100"})
		end
	end

	test "shouldnt auth with wrong time" do
		Timecop.freeze(@frozen_time) do
			Token.save_session({token: "123", ip: "8.1.1.1", created_at: @frozen_time})
			assert_false !! Token.authenticate({token: "123", created_at: @frozen_time + Rails.application.config.max_lifetime + 10, ip: "8.1.1.1"})
		end
	end

	test "shouldnt auth with wrong ip" do
		Timecop.freeze(@frozen_time) do
			Token.save_session({token: "123", ip: "8.1.1.1", created_at: @frozen_time})
			assert_false !! Token.authenticate({token: "123", created_at: @frozen_time, ip: "8.1.1.100"})
		end
	end
end