Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Client token gen page #18

Merged
merged 4 commits into from
Feb 26, 2025
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
5 changes: 5 additions & 0 deletions lib/slippi_chat/auth.ex
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ defmodule SlippiChat.Auth do

alias SlippiChat.Auth.{ClientToken, TokenGranter, User}

@doc """
Determines if a user has the priviledge to grant new client tokens.
"""
def has_granter_status?(%User{is_admin: is_admin}), do: is_admin

## Session

@doc """
Expand Down
65 changes: 65 additions & 0 deletions lib/slippi_chat_web/live/create_token_live.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
defmodule SlippiChatWeb.CreateTokenLive do
use SlippiChatWeb, :live_view

alias SlippiChat.Auth

def render(assigns) do
~H"""
<div class="mx-auto max-w-md">
<.simple_form for={@form} id="grant-form" phx-submit="create" phx-update="ignore">
<.input field={@form[:grantee]} label="Connect code" required />

<:actions>
<.button phx-disable-with="Creating..." class="w-full">
Create token
</.button>
</:actions>
</.simple_form>

<div :if={@new_token} class="mt-4 text-center">
<div class="text-zinc-600">New token created, copy it now, you won't be able to again:</div>
<div id="new-token"><%= @new_token %></div>
<span>
<.button
onclick="copyToClipboard()"
class="mt-2 display-block"
phx-click={JS.remove_class("hidden", to: "#check")}
>
Copy
</.button>
<span id="check" class="hidden"><.icon name="hero-check-solid" /></span>
</span>
</div>

<script>
function copyToClipboard() {
const copyTextElem = document.getElementById("new-token");
navigator.clipboard.writeText(copyTextElem.innerHTML);
}
</script>
</div>
"""
end

def handle_event("create", %{"grantee" => grantee}, socket) do
socket =
case Auth.register_user(%{connect_code: grantee, is_admin: false}) do
{:ok, _new_user, new_token} ->
assign(socket, new_token: new_token)

{:error, _} ->
put_flash(socket, :error, "Failed to create token, does this user already exist?")
end

{:noreply, socket}
end

def mount(_params, _session, socket) do
form = to_form(%{"grantee" => nil})

{:ok,
socket
|> assign(form: form)
|> assign(new_token: nil), temporary_assigns: [form: form]}
end
end
8 changes: 8 additions & 0 deletions lib/slippi_chat_web/router.ex
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ defmodule SlippiChatWeb.Router do
on_mount: [{SlippiChatWeb.UserAuth, :ensure_authenticated}] do
live "/chat", ChatLive.Root, :index
end

live_session :require_granter_user,
on_mount: [
{SlippiChatWeb.UserAuth, :ensure_authenticated},
{SlippiChatWeb.UserAuth, :ensure_granter_status}
] do
live "/create_token", CreateTokenLive, :new
end
end

## Authentication routes
Expand Down
18 changes: 18 additions & 0 deletions lib/slippi_chat_web/user_auth.ex
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,24 @@ defmodule SlippiChatWeb.UserAuth do
end
end

def on_mount(:ensure_granter_status, _params, session, socket) do
socket = mount_current_user(socket, session)

if Auth.has_granter_status?(socket.assigns.current_user) do
{:cont, socket}
else
socket =
socket
|> Phoenix.LiveView.put_flash(
:error,
"You must have token granter status to access this page."
)
|> Phoenix.LiveView.redirect(to: signed_in_path(socket))

{:halt, socket}
end
end

defp mount_current_user(socket, session) do
Phoenix.Component.assign_new(socket, :current_user, fn ->
if user_token = session["user_token"] do
Expand Down
59 changes: 59 additions & 0 deletions test/slippi_chat_web/live/create_token_live_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
defmodule SlippiChatWeb.CreateTokenLiveTest do
use SlippiChatWeb.ConnCase, async: false

import Phoenix.LiveViewTest
import SlippiChat.AuthFixtures

alias SlippiChat.Auth
alias SlippiChat.Auth.User

describe "GET /create_token" do
test "is not accessible to those without granter status", %{conn: conn} do
non_admin = user_fixture(%{is_admin: false})

result =
log_in_user(conn, non_admin.connect_code)
|> live(~p"/create_token")

assert {:error, {:redirect, %{to: "/", flash: flash}}} = result
assert %{"error" => "You must have token granter status to access this page."} = flash
end

test "generates an admin token", %{conn: conn} do
user = user_fixture(%{is_admin: true})
new_user_connect_code = unique_connect_code()

{:ok, lv, _html} =
log_in_user(conn, user.connect_code)
|> live(~p"/create_token")

html =
lv
|> element("#grant-form")
|> render_submit(%{grantee: new_user_connect_code})

assert html =~ "New token created, copy it now, you won&#39;t be able to again:"
new_token = Floki.parse_fragment!(html) |> Floki.find("#new-token") |> Floki.text()

assert %User{connect_code: ^new_user_connect_code} =
Auth.get_user_by_client_token(new_token)
end

test "does not generate new token for existing user", %{conn: conn} do
user = user_fixture(%{is_admin: true})
other_user = user_fixture(%{is_admin: false})

{:ok, lv, _html} =
log_in_user(conn, user.connect_code)
|> live(~p"/create_token")

html =
lv
|> element("#grant-form")
|> render_submit(%{grantee: other_user.connect_code})

assert html =~ "Failed to create token, does this user already exist?"
assert Floki.parse_fragment!(html) |> Floki.find("#new-token") == []
end
end
end
2 changes: 1 addition & 1 deletion test/support/fixtures/auth_fixtures.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ defmodule SlippiChat.AuthFixtures do
"#{letters}##{number}"
end

defp unique_connect_code do
def unique_connect_code do
generated_connect_code = random_connect_code()

if Repo.exists?(from u in User, where: u.connect_code == ^generated_connect_code) do
Expand Down