From eec71f25ad77e1f41f350d4f07873342b9f25d17 Mon Sep 17 00:00:00 2001 From: michaeljguarino Date: Fri, 1 Mar 2024 09:14:29 -0500 Subject: [PATCH] Add Basic License Key generation (#1298) --- apps/core/lib/core/services/accounts.ex | 9 +++++++++ apps/core/test/services/accounts_test.exs | 15 +++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/apps/core/lib/core/services/accounts.ex b/apps/core/lib/core/services/accounts.ex index 4e8b42ee6..4b5385b37 100644 --- a/apps/core/lib/core/services/accounts.ex +++ b/apps/core/lib/core/services/accounts.ex @@ -3,6 +3,7 @@ defmodule Core.Services.Accounts do import Core.Policies.Account alias Core.PubSub alias Core.Services.{Users, Payments} + alias Core.Auth.Jwt alias Core.Schema.{ User, Account, @@ -416,6 +417,14 @@ defmodule Core.Services.Accounts do def impersonate_service_account(%User{} = service_account, %User{} = user), do: allow(service_account, user, :impersonate) + + def license_key() do + exp = Timex.now() |> Timex.shift(days: 365) |> Timex.to_unix() + with {:ok, claims} <- Jwt.generate_claims(%{"enterprise" => true, "exp" => exp}), + {:ok, token, _} <- Jwt.encode_and_sign(claims, Jwt.signer()), + do: {:ok, token} + end + @doc """ Fetch all users that can impersonate this service account. Return just the user if not a service account """ diff --git a/apps/core/test/services/accounts_test.exs b/apps/core/test/services/accounts_test.exs index 5846d44d9..01b174994 100644 --- a/apps/core/test/services/accounts_test.exs +++ b/apps/core/test/services/accounts_test.exs @@ -3,6 +3,7 @@ defmodule Core.Services.AccountsTest do use Mimic alias Core.PubSub alias Core.Services.Accounts + alias Core.Auth.Jwt describe "#create_service_account/2" do setup [:setup_root_user] @@ -757,6 +758,20 @@ defmodule Core.Services.AccountsTest do end end + describe "#license_key/0" do + test "It can generate a valid year-long jwt with an enterprise claim" do + {:ok, token} = Accounts.license_key() + + signer = Jwt.signer() + {:ok, claims} = Jwt.verify(token, signer) + + assert claims["enterprise"] + + assert Timex.from_unix(claims["exp"]) + |> Timex.after?(Timex.shift(Timex.now(), days: 364)) + end + end + describe "#recompute_usage/1" do test "it correctly recomputes an accounts usage" do ac1 = insert(:account)