Skip to content

Commit

Permalink
Add Basic License Key generation (#1298)
Browse files Browse the repository at this point in the history
  • Loading branch information
michaeljguarino authored Mar 1, 2024
1 parent 25e2f4c commit eec71f2
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
9 changes: 9 additions & 0 deletions apps/core/lib/core/services/accounts.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
"""
Expand Down
15 changes: 15 additions & 0 deletions apps/core/test/services/accounts_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit eec71f2

Please sign in to comment.