diff --git a/lib/mix/tasks/smart_home/gen_token.ex b/lib/mix/tasks/smart_home/gen_token.ex new file mode 100644 index 0000000..b5fc239 --- /dev/null +++ b/lib/mix/tasks/smart_home/gen_token.ex @@ -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 diff --git a/lib/smart_home_auth.ex b/lib/smart_home_auth.ex index b8da1dc..0221b4f 100644 --- a/lib/smart_home_auth.ex +++ b/lib/smart_home_auth.ex @@ -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" => "test@example.com", + "auth_provider" => "local-dev", + "givenName" => "Dev Superuser" + }) + end end diff --git a/test/mix/tasks/smart_home_test.exs b/test/mix/tasks/smart_home_test.exs new file mode 100644 index 0000000..b2133e1 --- /dev/null +++ b/test/mix/tasks/smart_home_test.exs @@ -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 diff --git a/test/smart_home_auth/helper_test.exs b/test/smart_home_auth/helper_test.exs new file mode 100644 index 0000000..283b3bd --- /dev/null +++ b/test/smart_home_auth/helper_test.exs @@ -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