Skip to content

Commit

Permalink
parse ISOz to determine seconds offset for expiration time
Browse files Browse the repository at this point in the history
  • Loading branch information
benwilson512 committed Jul 8, 2015
1 parent a19c0fd commit 23b81b9
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
9 changes: 6 additions & 3 deletions lib/ex_aws/config/auth_cache.ex
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
defmodule ExAws.Config.AuthCache do
use GenServer

@moduledoc false

# http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html

def start_link(opts \\ []) do
GenServer.start_link(__MODULE__, :ok, opts)
end
Expand Down Expand Up @@ -37,9 +41,8 @@ defmodule ExAws.Config.AuthCache do
end

def refresh_in(expiration) do
expiration = Timex.DateFormat.parse!(expiration, "{ISOz}")
|> Timex.Date.convert(:secs)
time_to_expiration = expiration - Timex.Date.now(:secs)
expiration = expiration |> ExAws.Utils.iso_z_to_secs
time_to_expiration = expiration - ExAws.Utils.now_in_seconds
refresh_in = time_to_expiration - 2 * 60 # check two min prior to expiration
refresh_in * 1000
end
Expand Down
25 changes: 25 additions & 0 deletions lib/ex_aws/utils.ex
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,29 @@ defmodule ExAws.Utils do
def upcase(value) when is_binary(value) do
String.upcase(value)
end

@seconds_0_to_1970 :calendar.datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}})

def iso_z_to_secs(<<date::binary-10, "T", time::binary-8, "Z">>) do
<<year::binary-4, "-", mon::binary-2, "-", day::binary-2>> = date
<<hour::binary-2, ":", min::binary-2, ":", sec::binary-2>> = time
year = year |> String.to_integer
mon = mon |> String.to_integer
day = day |> String.to_integer
hour = hour |> String.to_integer
min = min |> String.to_integer
sec = sec |> String.to_integer

# Seriously? Gregorian seconds but not epoch seconds?
greg_secs = :calendar.datetime_to_gregorian_seconds({{year, mon, day}, {hour, min, sec}})
greg_secs - @seconds_0_to_1970
end

def now_in_seconds do
greg_secs = :os.timestamp
|> :calendar.now_to_universal_time
|> :calendar.datetime_to_gregorian_seconds

greg_secs - @seconds_0_to_1970
end
end
4 changes: 4 additions & 0 deletions test/lib/ex_aws/utils_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,8 @@ defmodule ExAws.UtilsTest do
assert %{"FooBar" => ["foo", "bar"]} == [foo_bar: ["foo", "bar"]]
|> camelize_keys(deep: true)
end

test "iso_z_to_secs/1" do
assert iso_z_to_secs("2015-07-05T22:16:18Z") == 1436134578
end
end

0 comments on commit 23b81b9

Please sign in to comment.