Created
December 19, 2016 16:43
-
-
Save logicmason/d1ce252f6a140d914933661af0878c9f to your computer and use it in GitHub Desktop.
Revisions
-
logicmason created this gist
Dec 19, 2016 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,12 @@ # my_app/web/controllers/auth_controller.ex defmodule MyApp.AuthController do use MyApp.Web, :controller import Ecto.Query alias MyApp.TwilioToken # Connect this to a route for /token:identity def token(conn, %{"identity" => identity}) do token = TwilioToken.for_video(identity) json conn, %{token: token, identity: identity} end end This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,42 @@ # my_app/web/twilio_token.ex defmodule MyApp.TwilioToken do # Generates token for Twilio Programmable video # Assumes Joken is in Mix.exs deps and Twilio creds are in app config def for_video(identity) do sid = config[:TWILIO_ACCOUNT_SID] api_key = config[:TWILIO_API_KEY] api_secret = config[:TWILIO_API_SECRET] rtc_profile_sid = config[:TWILIO_CONFIGURATION_SID] now = epoch_ts() exp = now + 3600 payload = %{ "jti" => "#{api_key}-#{now}", "iss" => api_key, "sub" => sid, "exp" => exp, "grants" => %{ "identity" => identity, "rtc" => %{ "configuration_profile_sid" => rtc_profile_sid } } } payload |> Joken.token() |> Joken.with_header_arg("cty", "twilio-fpa;v=1") |> Joken.with_signer(Joken.hs256(api_secret)) |> Joken.sign() |> Joken.get_compact() end defp epoch_ts() do epoch = {{1970, 1, 1}, {0, 0, 0}} epoch_i = :calendar.datetime_to_gregorian_seconds(epoch) now_i = :calendar.datetime_to_gregorian_seconds(:calendar.universal_time) now_i - epoch_i end def config, do: Application.get_env(:my_app, __MODULE__) end