Module: Shaf::Authentication

Defined in:
lib/shaf/helpers/authentication.rb

Defined Under Namespace

Classes: NoChallengesError, RealmChangedError

Instance Method Summary collapse

Instance Method Details

#authenticate(realm: Settings.default_authentication_realm) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/shaf/helpers/authentication.rb', line 34

def authenticate(realm: Settings.default_authentication_realm)
  if defined?(@current_realm) && @current_realm&.to_s != realm&.to_s
    raise RealmChangedError.new(from: @current_realm , to: realm)
  else
    @current_realm = realm
  end

  current_user.tap do |user|
    www_authenticate(realm: realm) unless user
  end
end

#authenticate!(realm: Settings.default_authentication_realm) ⇒ Object Also known as: current_user!



46
47
48
49
50
51
52
53
# File 'lib/shaf/helpers/authentication.rb', line 46

def authenticate!(realm: Settings.default_authentication_realm)
  user = authenticate(realm: realm)
  return user if user

  msg = +"Unauthorized action"
  msg << " (Realm: #{realm})" if realm
  raise Shaf::Errors::UnauthorizedError, msg
end

#authenticated?Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/shaf/helpers/authentication.rb', line 56

def authenticated?
  !current_user.nil?
end

#current_userObject



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/shaf/helpers/authentication.rb', line 60

def current_user
  unless defined? @current_realm
    if Settings.key? :default_authentication_realm
      @current_realm = Settings.default_authentication_realm
    else
      Shaf.logger.info <<~MSG
        No realm has been provided!
        Authentication/authorization cannot be performed. Did you perhaps
        forget to configure a realm in
        `Settings.default_authentication_realm` or provide it when calling
        `#authenticate!` (or `#authenticate!`)
      MSG
      return
    end
  end

  @current_user ||= Authenticator.user(request.env, realm: @current_realm)
end

#www_authenticate(realm: Settings.default_authentication_realm) ⇒ Object

Raises:



27
28
29
30
31
32
# File 'lib/shaf/helpers/authentication.rb', line 27

def www_authenticate(realm: Settings.default_authentication_realm)
  challenges = Authenticator.challenges_for(realm: realm)
  raise NoChallengesError.new(realm) if challenges.empty?

  headers 'WWW-Authenticate' => challenges.map(&:to_s)
end