Skip to content
This repository has been archived by the owner on Dec 6, 2022. It is now read-only.

#21: Generate JWT tokens for API development #22

Merged
merged 4 commits into from
Aug 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions lib/mix/tasks/smart_home/gen_token.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
defmodule Mix.Tasks.SmartHome.GenToken do
use Mix.Task

@shortdoc "Generate a JWT token for use with local API development"
def run(_) do
IO.puts("Generating JWT Token...")
jwt = SmartHomeAuth.gen_auth_token()

IO.puts("\n\n")
IO.puts(jwt)
end
end
14 changes: 14 additions & 0 deletions lib/smart_home_auth.ex
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,18 @@ defmodule SmartHomeAuth do
if it comes from the database, an external API or others.

"""

@doc """
Generate a local-use authentication token for API development.
"""
@spec gen_auth_token :: binary
def gen_auth_token do
AuthPlug.Token.generate_jwt!(
%{
"id" => 1,
"email" => "[email protected]",
"auth_provider" => "local-dev",
"givenName" => "Dev Superuser"
})
end
end
15 changes: 15 additions & 0 deletions test/mix/tasks/smart_home_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
defmodule Mix.Tasks.SmartHomeTest do
use ExUnit.Case
import ExUnit.CaptureIO

@jwt_pattern ~r/[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+\/=]*$/m

test "Mix task returns a valid JWT" do
out = capture_io(fn -> Mix.Tasks.SmartHome.GenToken.run([]) end)

jwt = Regex.run(@jwt_pattern, out) |> List.first()

decoded = AuthPlug.Token.verify_jwt!(jwt)
assert %{"id" => 1} = decoded
end
end
11 changes: 11 additions & 0 deletions test/smart_home_auth/helper_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
defmodule SmartHomeAuth.HelperTest do
use ExUnit.Case, async: true

test "gen_auth_token generates a correct token" do
token = SmartHomeAuth.gen_auth_token()

decoded = AuthPlug.Token.verify_jwt!(token)

assert %{"id" => 1} = decoded
end
end