Coherence v0.3.0 Coherence.Authentication.Session

Implements Session based authentication. By default, it uses an Agent for session state. Additionally, a the session can be stored in a database with an Agent based cache.

The plug can be used to force a login for unauthenticated users for routes that need to be protected with a password.

For example:

plug Coherence.Authentication.Session, login: true

will present the user for a login if they are accessing a route or controller that uses this plug.

For pages that don’t require authorization but would like to present logged in information on unprotected pages, use the default:

plug Coherence.Authentication.Session

This will set the current_user for use in templates, but not allow access to protected pages.

By default, the user model for a logged-in user can be accessed with conn.assigns[:current_user]. This can be changed with the global :assigns_key config option.

Controller Based Authentication

This plug can be used in either the router.ex file or in a controller file.

Database Persistence

To enable database persistence, implement [Coherence.DbStore] protocol for your user model. As well, you will need to provide the :db_model option to the plug. For example:

defimpl Coherence.DbStore, for: MyProject.User do
  def get_user_data(_, creds, _id_key) do
    alias MyProject.{Session, Repo}
    case Repo.one from s in Session, where: s.creds == ^creds, preload: :user do
      %{user: user} -> user
      _ -> nil
    end
  end

  def put_credentials(user, creds , _) do
    case Repo.one from s in Session, where: s.creds == ^creds do
      nil -> %Session{creds: creds}
      session -> session
    end
    |> Session.changeset(%{user_id: user.id})
    |> Repo.insert_or_update
  end

  def delete_credentials(_, creds) do
    case Repo.one from s in Session, where: s.creds == ^creds do
      nil -> nil
      session ->
        Repo.delete session
    end
  end
end

plug Coherence.Authentication.Session, db_model: MyProject.User, login: true

You should be aware that the Agent is still used to fetch the user data if can be found. If the key is not found, it checks the database. If a record is found in the database, the agent is updated and the user data returned.

This module is derived from https://github.com/lexmag/blaguth

Summary

Functions

Create a login for a user. user_data can be any term but must not be nil

Functions

create_login(conn, user_data, opts \\ [])

Create a login for a user. user_data can be any term but must not be nil.

delete_login(conn, opts \\ [])

Delete a login.