Skip to content

Instantly share code, notes, and snippets.

@dakkar
Created December 8, 2017 12:48
Show Gist options
  • Select an option

  • Save dakkar/dba4b2da24f417bce7d23d20191fef21 to your computer and use it in GitHub Desktop.

Select an option

Save dakkar/dba4b2da24f417bce7d23d20191fef21 to your computer and use it in GitHub Desktop.
Simple authentication+authorisation example with Cro
use v6.d.PREVIEW;
use Cro::HTTP::Router;
use Cro::HTTP::Middleware;
use Cro::HTTP::Response;
use Cro::HTTP::Server;
use Cro::Transform;
# mixin for requests, carrying authentication info
role AuthToy::Request::Authed {
has Str $.user;
}
# stupid and insecure authentication step
class AuthToy::Middleware::Authentication does Cro::HTTP::Middleware::Request {
# this hash contains valid usernames & password; **DON'T DO
# THIS**, it's absurdly insecure
has %.accounts;
method process(Supply $request-stream) {
supply whenever $request-stream -> $request {
# here we would have some proper authentication logic
my $user = $request.query-value('user')[0];
my $password = $request.query-value('password')[0];
if ($user && $password && %!accounts{$user} eq $password) {
warn "authed $user $password\n";
$request does AuthToy::Request::Authed(:user($user));
}
else {
warn "non-authed request\n";
}
emit $request;
}
}
}
# authorisation step: short-circuit to a 403 if the request does not
# carry authentication information
class AuthToy::Middleware::Authorisation does Cro::HTTP::Middleware::Conditional {
method process(Supply $request-stream) {
supply whenever $request-stream -> $request {
if ($request ~~ AuthToy::Request::Authed) {
# here we could also add some access control
warn "got request for {$request.user}\n";
emit $request;
}
else {
emit Cro::HTTP::Response.new(:status<403>);
}
}
}
}
my $auth-toy = route {
before AuthToy::Middleware::Authentication.new(
accounts => (
gino => '1234',
pino => '5678',
),
);
before AuthToy::Middleware::Authorisation.new;
get -> 'hello' {
content 'application/json', {
status => 'ok',
version => 1,
you-are => request.user,
};
}
}
my Cro::Service $um = Cro::HTTP::Server.new(
:host<localhost>,
:port<8080>,
application => $auth-toy,
);
$um.start;
react whenever signal(SIGINT) {
$um.stop;
exit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment