87 lines
2.8 KiB
Elixir
87 lines
2.8 KiB
Elixir
defmodule ComponentsElixirWeb.LoginLive do
|
|
use ComponentsElixirWeb, :live_view
|
|
|
|
alias ComponentsElixir.Auth
|
|
|
|
@impl true
|
|
def mount(_params, session, socket) do
|
|
# If already authenticated, redirect to components
|
|
if Map.get(session, "authenticated") do
|
|
{:ok, socket |> push_navigate(to: ~p"/")}
|
|
else
|
|
{:ok,
|
|
socket
|
|
|> assign(:session, session)
|
|
|> assign(:error_message, nil)
|
|
|> assign(:form, to_form(%{"password" => ""}))}
|
|
end
|
|
end
|
|
|
|
@impl true
|
|
def handle_event("login", %{"password" => password}, socket) do
|
|
case Auth.authenticate(password) do
|
|
{:ok, :authenticated} ->
|
|
# Store authentication in a cookie that the server can read
|
|
{:noreply,
|
|
socket
|
|
|> put_flash(:info, "Successfully logged in!")
|
|
|> push_navigate(to: "/login/authenticate?password=#{URI.encode(password)}")}
|
|
|
|
{:error, :invalid_credentials} ->
|
|
{:noreply,
|
|
socket
|
|
|> assign(:error_message, "Invalid password")
|
|
|> assign(:form, to_form(%{"password" => ""}))}
|
|
end
|
|
end
|
|
|
|
@impl true
|
|
def render(assigns) do
|
|
~H"""
|
|
<div class="min-h-screen flex items-center justify-center bg-base-200 py-12 px-4 sm:px-6 lg:px-8">
|
|
<div class="max-w-md w-full space-y-8">
|
|
<div>
|
|
<h2 class="mt-6 text-center text-3xl font-extrabold text-base-content">
|
|
Components Inventory
|
|
</h2>
|
|
<p class="mt-2 text-center text-sm text-base-content/70">
|
|
Please enter your password to continue
|
|
</p>
|
|
</div>
|
|
|
|
<.form for={@form} phx-submit="login" class="mt-8 space-y-6">
|
|
<div>
|
|
<label for="password" class="sr-only">Password</label>
|
|
<input
|
|
id="password"
|
|
name="password"
|
|
type="password"
|
|
required
|
|
class="appearance-none rounded-md relative block w-full px-3 py-2 border border-base-300 placeholder-base-content/50 text-base-content bg-base-100 focus:outline-none focus:ring-primary focus:border-primary focus:z-10 sm:text-sm"
|
|
placeholder="Password"
|
|
autocomplete="current-password"
|
|
value={@form[:password].value}
|
|
/>
|
|
</div>
|
|
|
|
<%= if @error_message do %>
|
|
<div class="text-red-600 text-sm text-center">
|
|
<%= @error_message %>
|
|
</div>
|
|
<% end %>
|
|
|
|
<div>
|
|
<button
|
|
type="submit"
|
|
class="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
|
|
>
|
|
Sign in
|
|
</button>
|
|
</div>
|
|
</.form>
|
|
</div>
|
|
</div>
|
|
"""
|
|
end
|
|
end
|