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
1
class Authenticate < Amber::Pipe::Base
2
PUBLIC_PATHS = ["/"]
3
4
def call(context)
5
some_id = context.session["some_id"]? # setup by some controller
6
if some_id || public_path?(context.request.path)
7
call_next(context)
8
else
9
context.flash[:warning] = "Please Sign In"
10
context.response.headers.add "Location", "/"
11
context.response.status_code = 302
12
end
13
end
14
15
private def public_path?(path)
16
PUBLIC_PATHS.includes?(path)
17
18
# Different strategies can be used to determine if a path is public
19
# Example, if /admin/* paths are the only private paths
20
# return false if path.starts_with?("/admin")
21
#
22
# Example, if only a few private paths exist
23
# return false if ["/secret", "/super/secret"].includes?(path)
24
end
25
end
Copied!
Then in your routes file:
config/routes.cr
1
Amber::Server.configure do |app|
2
pipeline :web do
3
# other pipes...
4
plug Authenticate.new
5
end
6
7
routes :web do
8
# some routes,,,
9
end
10
end
Copied!
To have a full authentication experience some extra controllers, views and models are still required, please see Amber Auth Example.
Also see pipelines.
Last modified 3yr ago
Copy link