JumarWeb.UserAuth (Jumar v0.1.0)

View Source

Authentication helpers for Jumar.

Summary

Functions

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

Logs the user out.

Handles mounting and authenticating the current_user in LiveViews.

Used for routes that require the user to not be authenticated.

Used for routes that require the user to be authenticated.

Functions

fetch_current_user(conn, opts)

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

log_in_user(conn, user, params \\ %{})

Logs the user in.

It renews the session ID and clears the whole session to avoid fixation attacks. See the renew_session function to customize this behavior.

It also sets a :live_socket_id key in the session, so LiveView sessions are identified and automatically disconnected on log out. The line can be safely removed if you are not using LiveView.

log_out_user(conn)

Logs the user out.

It clears all session data for safety. See renew_session.

on_mount(atom, params, session, socket)

Handles mounting and authenticating the current_user in LiveViews.

on_mount arguments

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

  • :ensure_authenticated - Authenticates the user from the session, and assigns the current_user to socket assigns based on user_token. Redirects to login page if there's no logged user.

  • :redirect_if_user_is_authenticated - Authenticates the user from the session. Redirects to signed_in_path if there's a logged user.

Examples

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

defmodule JumarWeb.PageLive do
  use JumarWeb, :live_view

  on_mount {JumarWeb.UserAuth, :mount_current_user}
  ...
end

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

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

redirect_if_user_is_authenticated(conn, opts)

Used for routes that require the user to not be authenticated.

require_authenticated_user(conn, opts)

Used for routes that require the user to be authenticated.

If you want to enforce the user email is confirmed before they use the application at all, here would be a good place.