class Pechkin::Auth::Middleware

Auth middleware to check if provided auth can be found in .htpasswd file

Attributes

htpasswd[R]

Public Class Methods

new(app, auth_file:) click to toggle source
# File lib/pechkin/auth.rb, line 24
def initialize(app, auth_file:)
  @htpasswd = HTAuth::PasswdFile.open(auth_file) if File.exist?(auth_file)
  @app = app
end

Public Instance Methods

call(env) click to toggle source
# File lib/pechkin/auth.rb, line 29
def call(env)
  authorize(env)
  @app.call(env)
rescue AuthError => e
  body = { status: 'error', reason: e.message }.to_json
  ['401', { 'Content-Type' => 'application/json' }, [body]]
rescue StandardError => e
  body = { status: 'error', reason: e.message }.to_json
  ['503', { 'Content-Type' => 'application/json' }, [body]]
end

Private Instance Methods

authorize(env) click to toggle source
# File lib/pechkin/auth.rb, line 42
def authorize(env)
  return unless htpasswd

  auth = env['HTTP_AUTHORIZATION']
  raise AuthError, 'Auth header is missing' unless auth

  match = auth.match(/^Basic (.*)$/)
  raise AuthError, 'Auth is not basic' unless match

  user, password = *Base64.decode64(match[1]).split(':')
  check_auth(user, password)
end
check_auth(user, password) click to toggle source
# File lib/pechkin/auth.rb, line 55
def check_auth(user, password)
  raise AuthError, 'User is missing' unless user

  raise AuthError, 'Password is missing' unless password

  e = htpasswd.fetch(user)

  raise AuthError, "User '#{user}' not found" unless e

  raise AuthError, "Can't authenticate" unless e.authenticated?(password)
end