From db209117f85ae7e4a0a8b538b5f015d99c86be3f Mon Sep 17 00:00:00 2001 From: Luka Vandervelden Date: Sat, 22 Sep 2018 21:25:03 +0200 Subject: [PATCH] Authd library added to provide an auto-check middleware. --- src/authd.cr | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/authd.cr diff --git a/src/authd.cr b/src/authd.cr new file mode 100644 index 0000000..59de698 --- /dev/null +++ b/src/authd.cr @@ -0,0 +1,37 @@ + +require "kemal" +require "jwt" + +class HTTP::Server::Context + property authd_user : Hash(String, JSON::Any)? +end + +class AuthD::Middleware < Kemal::Handler + property key : String = "" + + @configured = false + @configurator : Proc(Middleware, Nil) + + def initialize(&block : Proc(Middleware, Nil)) + @configurator = block + end + + def call(context) + unless @configured + @configured = true + @configurator.call self + end + + context.request.headers["X-Token"]?.try do |x_token| + payload, header = JWT.decode x_token, @key, "HS256" + + if payload + context.authd_user = payload + end + end + + call_next context + end +end + +