Skip to content

Instantly share code, notes, and snippets.

@ahmadshah
Created September 23, 2017 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmadshah/b097deba681e067af9cb013d48329d8e to your computer and use it in GitHub Desktop.
Save ahmadshah/b097deba681e067af9cb013d48329d8e to your computer and use it in GitHub Desktop.
Kong JWT
defmodule Fashionista.Event.UserIsAuthenticated do
use Fashionista.Service.Kong
import Joken
@response_fields ~w(
username custom_id message secret id algorithm created_at key consumer_id
)
def create_token(email, id) do
with true <- is_consumer_exists?(email),
token <- create_token_request(email)
do
response = hydrate_response(token, @response_fields)
sign_token(email, response.key, response.secret)
else
false ->
create_consumer(email, id)
create_token(email, id)
end
end
def destroy_token(email) do
get_consumer_tokens(email)
|> Enum.each(fn(token) ->
delete!(base_url() <> "consumers/#{email}/jwt/#{token.id}")
end)
:ok
end
defp get_consumer(email) do
get!(base_url() <> "consumers/#{email}").body
|> hydrate_response(@response_fields)
end
defp is_consumer_exists?(email) do
case get_consumer(email) do
%{message: _message} -> false
%{custom_id: _custom_id, username: _username} -> true
end
end
defp create_consumer(email, id) do
post!(base_url() <> "consumers", Poison.encode!(%{
"username" => email,
"custom_id" => id
}), %{
"Content-Type" => "application/json"
})
end
defp create_token_request(email) do
post!(base_url() <> "consumers/#{email}/jwt", "", %{
"Content-Type" => "application/x-www-form-urlencoded"
}).body
end
defp sign_token(email, key, secret) do
consumer = get_consumer(email)
token =
%{email: email, id: consumer.custom_id}
|> token()
|> with_iss(key)
|> with_signer(hs256(secret))
|> sign()
|> get_compact()
end
def get_consumer_tokens(email) do
tokens = get!(base_url() <> "consumers/#{email}/jwt").body
|> Poison.decode!
Enum.map(tokens["data"], fn (token) ->
Map.take(token, @response_fields)
|> Enum.map(fn({k, v}) -> {String.to_atom(k), v} end)
|> Enum.into(%{})
end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment