danhper / plug-navigation-history

Elixir plug to keep navigation history
https://hex.pm/packages/navigation_history
MIT License
72 stars 15 forks source link

NavigationHistory

Build status Module Version Hex Docs Total Download License Last Updated

A plug to keep track of user navigation history using sessions. This can be useful for example to redirect the user back to the previous page, or to redirect after a login when the user tried to access a page without being authenticated.

Installation

Add :navigation_history to your list of dependencies in mix.exs:

def deps do
  [
    {:navigation_history, "~> 0.4"}
  ]
end

Usage

To keep track of the navigation, add the NavigationHistory.Tracker plug. For example, in a Phoenix application, your pipeline could become:

pipeline :browser do
  plug :accepts, ["html"]
  plug :fetch_session
  plug :fetch_flash
  plug :protect_from_forgery
  plug :put_secure_browser_headers
  plug NavigationHistory.Tracker
end

You can then retrieve the paths the user navigated to by using

NavigationHistory.last_path(conn) # will return the last navigated path or nil
NavigationHistory.last_path(conn, 1) # will return the second last navigated path
NavigationHistory.last_path(conn, default: "/") # will return the last path or "/"
NavigationHistory.last_paths(conn) # will return a list of the last navigated paths
NavigationHistory.last_path(session) # instead of passing a conn, can also pass a session

For example, to redirect the user to the last navigated path in Phoenix, you can use a helper like this

def redirect_back(conn, opts \\ []) do
  Phoenix.Controller.redirect(conn, to: NavigationHistory.last_path(conn, opts))
end

# you can then write
redirect_back(conn, default: "/")

Take a look at this conversation in Phoenix for more info about redirecting back.

Configuration

There are a few options that can be used with the plug:

Examples

plug NavigationHistory.Tracker, excluded_paths: ["/login", ~r(/admin.*)]
plug NavigationHistory.Tracker, included_paths: [~r(/admin.*)], key: "admin", history_size: 5

# which an be used
NavigationHistory.last_path(conn) # from default history
NavigationHistory.last_path(conn, key: "admin") # from admin history

Copyright and License

Copyright (c) 2016 Daniel Perez

Released under the MIT License, which can be found in the repository in LICENSE.