Documentation

Authenticate

Browse documentation

Read this page as HTML, Markdown, or structured JSON—or open the published Markdown with an AI assistant. Gemini receives the prompt through your clipboard because its signed-out page does not reliably prefill URL text; paste when the new tab opens. External assistants need the public site URL.

Authenticate

This recipe will help you to setup an authentication pipe in your application:

First you need an amber project generated with Amber CLI or from scratch.

src/pipes/authenticate.cr
Crystal
class Authenticate < Amber::Pipe::Base
  PUBLIC_PATHS = ["/"]

def call(context) some_id = context.session["some_id"]? # setup by some controller if some_id || public_path?(context.request.path) call_next(context) else context.flash[:warning] = "Please Sign In" context.response.headers.add "Location", "/" context.response.status_code = 302 end end

private def public_path?(path) PUBLIC_PATHS.includes?(path)

# Different strategies can be used to determine if a path is public
# Example, if /admin/* paths are the only private paths
# return false if path.starts_with?(&quot;/admin&quot;)
#
# Example, if only a few private paths exist
# return false if [&quot;/secret&quot;, &quot;/super/secret&quot;].includes?(path)

end end

Then in your routes file:

config/routes.cr
Crystal
Amber::Server.configure do |app|
  pipeline :web do
    # other pipes...
    plug Authenticate.new
  end

routes :web do # some routes,,, end end

To have a full authentication experience some extra controllers, views and models are still required, please see Amber Auth Example.

Also see pipelines.