Files
component-system/lib/components_elixir/auth.ex
Schuwi 1b498d286d fix(elixir): improve storage location UI
- modify UI and UX to match categories system
2025-09-14 16:03:56 +02:00

68 lines
1.8 KiB
Elixir

defmodule ComponentsElixir.Auth do
@moduledoc """
Simple authentication system for the components inventory.
Uses a configured password for authentication with session management.
"""
@doc """
Validates the provided password against the configured password.
"""
def authenticate(password) do
configured_password = Application.get_env(:components_elixir, :auth_password, "changeme")
if password == configured_password do
{:ok, :authenticated}
else
{:error, :invalid_credentials}
end
end
@doc """
Checks if the current session is authenticated.
"""
def authenticated?(conn_or_socket_or_session) do
case get_session_value(conn_or_socket_or_session, :authenticated) do
true -> true
_ -> false
end
end
@doc """
Marks the session as authenticated.
"""
def sign_in(conn_or_socket) do
put_session_value(conn_or_socket, :authenticated, true)
end
@doc """
Clears the authentication from the session.
"""
def sign_out(conn_or_socket) do
put_session_value(conn_or_socket, :authenticated, nil)
end
# Helper functions to handle both Plug.Conn and Phoenix.LiveView.Socket
defp get_session_value(%Plug.Conn{} = conn, key) do
Plug.Conn.get_session(conn, key)
end
defp get_session_value(%Phoenix.LiveView.Socket{} = socket, key) do
get_in(socket.assigns, [:session, key])
end
defp get_session_value(session, key) when is_map(session) do
# Handle both string and atom keys
Map.get(session, to_string(key)) || Map.get(session, key)
end
defp put_session_value(%Plug.Conn{} = conn, key, value) do
Plug.Conn.put_session(conn, key, value)
end
defp put_session_value(%Phoenix.LiveView.Socket{} = socket, key, value) do
session = Map.put(socket.assigns[:session] || %{}, key, value)
%{socket | assigns: Map.put(socket.assigns, :session, session)}
end
end