2018-09-22 21:25:03 +02:00
|
|
|
|
|
|
|
require "kemal"
|
|
|
|
require "jwt"
|
|
|
|
|
2018-09-22 21:42:21 +02:00
|
|
|
require "./user.cr"
|
|
|
|
|
2018-09-22 21:25:03 +02:00
|
|
|
class HTTP::Server::Context
|
2018-09-22 21:42:21 +02:00
|
|
|
property authd_user : AuthD::User?
|
2018-09-22 21:25:03 +02:00
|
|
|
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
|
2018-09-22 21:42:21 +02:00
|
|
|
context.authd_user = AuthD::User.new.tap do |u|
|
|
|
|
u.username = payload["username"].as_s?
|
|
|
|
u.realname = payload["realname"].as_s?
|
|
|
|
u.avatar = payload["avatar"].as_s?
|
|
|
|
u.perms = Array(String).new
|
|
|
|
|
|
|
|
payload["perms"].as_a.tap do |perms|
|
|
|
|
perms.each do |perm|
|
|
|
|
if perm.class == String
|
|
|
|
u.perms! << perm.as_s
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2018-09-22 21:25:03 +02:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
call_next context
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
|