OneAuth.Login (OneAuth v0.1.0)

Copy Markdown View Source

Implements the OneAuth login workflow.

This module validates the configured credentials, creates and stores a signed session token, and determines where users should be redirected after a successful login.

Summary

Functions

Authenticates the provided credentials and starts a new session.

Returns the configured login path, optionally with a redirect_to query parameter appended so redirect_path/1 can send the user back there after a successful login.

Returns the destination path after a successful login.

Functions

authenticate(conn, username, password)

@spec authenticate(Plug.Conn.t(), String.t(), String.t()) ::
  {:ok, Plug.Conn.t()} | :error

Authenticates the provided credentials and starts a new session.

When the supplied username and password match the configured OneAuth credentials, a signed session token is created and stored in the Plug session.

Returns {:ok, conn} on success or :error when authentication fails.

Examples

case Login.authenticate(conn, username, password) do
  {:ok, conn} ->
    # Redirect the authenticated user

  :error ->
    # Invalid credentials
end

path(conn)

@spec path(Plug.Conn.t()) :: String.t()

Returns the configured login path, optionally with a redirect_to query parameter appended so redirect_path/1 can send the user back there after a successful login.

Pass the current Plug.Conn.t() and the right thing happens either way:

  • If the conn already has a redirect_to query parameter (e.g. it's the request to render or submit the login page itself, after OneAuth.Plug.RequireAuth redirected here), that value is reused as-is.
  • Otherwise, the conn's own request path (and query string, if any) is used as the redirect_to — handy for a "Log in" link anywhere in your app that should return the user to the page they were on.

This mirrors what OneAuth.Plug.RequireAuth builds internally when it redirects an unauthenticated request to the login page, so it's the same URL format redirect_path/1 expects to read back.

Examples

Login.path(conn)
#=> "/login"

Login.path(conn)
#=> "/login?redirect_to=%2Fadmin"

redirect_path(conn)

@spec redirect_path(Plug.Conn.t()) :: String.t()

Returns the destination path after a successful login.

If the login request includes a valid redirect_to query parameter, that path is returned. Otherwise, the configured login_redirect_path is used.

Only relative paths beginning with / are accepted. Any other value is ignored to prevent open redirect vulnerabilities.

Examples

Login.redirect_path(conn)
#=> "/admin"

Login.redirect_path(conn)
#=> "/"