Skip to content

Commit

Permalink
simplify chain, wip
Browse files Browse the repository at this point in the history
  • Loading branch information
kickster97 committed Jan 24, 2025
1 parent 0161b46 commit d721710
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 35 deletions.
15 changes: 0 additions & 15 deletions src/lavinmq/auth/authenticator.cr
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,8 @@ module LavinMQ
module Auth
abstract class Authenticator
Log = LavinMQ::Log.for "auth.handler"
@log = Logger.new(Log)
property successor : Authenticator?

abstract def authenticate(username : String, password : String)

def set_successor(service : Authenticator) : Authenticator
@successor = service
service
end

def try_next(username : String, password : String)
if successor = @successor
successor.authenticate(username, password)
else
nil
end
end
end
end
end
5 changes: 2 additions & 3 deletions src/lavinmq/auth/authenticators/basic.cr
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,14 @@ require "../../server"

module LavinMQ
module Auth
class BasicAuthenticator < LavinMQ::Auth::Authenticator
class BasicAuthenticator < Authenticator
def initialize(@users : UserStore)
end

def authenticate(username : String, password : String)
user = @users[username]
return user if user && user.password && user.password.not_nil!.verify(password)
@log.info { "Basic authentication failed" }
try_next(username, password)
Log.info { "Basic authentication failed" }
end
end
end
Expand Down
27 changes: 10 additions & 17 deletions src/lavinmq/auth/chain.cr
Original file line number Diff line number Diff line change
Expand Up @@ -3,40 +3,33 @@ require "./authenticators/basic"

module LavinMQ
module Auth
class Chain
@first : Authenticator?
class Chain < Authenticator
@backends : Array(Authenticator)

def initialize(users : UserStore)
@backends = [] of Authenticator
backends = Config.instance.auth_backends
if backends.nil? || backends.size == 0
add_handler(BasicAuthenticator.new(users))
@backends << BasicAuthenticator.new(users)
else
backends.each do |backend|
case backend
when "basic"
add_handler(BasicAuthenticator.new(users))
@backends << BasicAuthenticator.new(users)
else
raise "Unsupported authentication backend: #{backend}"
end
end
end
end

def add_handler(auth : Authenticator)
if first = @first
current = first
while successor = current.@successor
current = successor
def authenticate(username : String, password : String)
@backends.each do |backend|
if user = backend.authenticate(username, password)
return user
end
current.set_successor(auth)
else
@first = auth
end
self
end

def authenticate(username : String, password : String)
@first.try &.authenticate(username, password)
nil
end
end
end
Expand Down

0 comments on commit d721710

Please sign in to comment.