ZoonkWeb.UserAuth (Zoonk v0.1.0-dev)

View Source

Session management for user authentication.

This module manages user sign in and sign out by handling session tokens, renewing sessions to prevent fixation attacks, and coordinating disconnects for LiveView sessions.

Summary

Functions

Disconnects existing sockets for the given tokens.

Fetches the scope for API requests.

Authenticates the user by looking into the session and remember me token.

Logs the user in.

Logs the user out.

Stores the return to path for unauthenticated users.

Handles mounting and authenticating the scope in LiveViews.

Puts the given token in the session and sets the :live_socket_id key, so LiveView sessions are identified and automatically disconnected on log out.

Used for routes that require the user to be authenticated.

Returns the path to redirect to after log in.

Functions

disconnect_sessions(tokens)

Disconnects existing sockets for the given tokens.

fetch_api_scope(conn, opts)

Fetches the scope for API requests.

fetch_scope(conn, opts)

Authenticates the user by looking into the session and remember me token.

Will reissue the session token if it is older than the configured age.

login_user(conn, user)

Logs the user in.

Redirects to the session's :user_return_to path or falls back to the signed_in_path/1.

logout_user(conn)

Logs the user out.

It clears all session data for safety. See renew_session.

maybe_store_return_to(conn, opts)

Stores the return to path for unauthenticated users.

This is used to redirect the user back to the page they were trying to access. We store it for all GET requests that are not login, signup, or confirmation pages.

on_mount(atom, params, session, socket)

Handles mounting and authenticating the scope in LiveViews.

on_mount arguments

  • :mount_scope - Assigns scope to socket assigns based on user_token, or nil if there's no user_token or no matching user.

  • :ensure_auth_for_private_orgs - Ensures the user is authenticated for private organizations. If the organization is public, it continues; otherwise, it redirects to the login page.

  • :ensure_sudo_mode - Check if the user has been authenticated recently enough to access a certain page.

Examples

Use the on_mount lifecycle macro in LiveViews to mount or authenticate the scope:

defmodule ZoonkWeb.PageLive do
  use ZoonkWeb, :live_view

  on_mount {ZoonkWeb.UserAuth, :mount_scope}
  ...
end

Or use the live_session of your router to invoke the on_mount callback:

live_session :authenticated, on_mount: [{ZoonkWeb.UserAuth, :ensure_authenticated}] do
  live "/profile", ProfileLive, :index
end

put_token_in_session(conn, token)

Puts the given token in the session and sets the :live_socket_id key, so LiveView sessions are identified and automatically disconnected on log out.

require_authenticated_user(conn, opts)

Used for routes that require the user to be authenticated.

signed_in_path(conn)

Returns the path to redirect to after log in.