dodgerogers747
dodgerogers747

Reputation: 3345

Current_user method for authenticate_or_request_with_http_digest - Rails 4

I am using authenticate_or_request_with_http_digest for simple administration within my app. It would be nice if the admin could see all of the delete, edit links for an object when logged in but have these hidden for regular users.

The app has no scope for users signing up or multiple users so devise or a similar authentication platform seems overkill in this instance.

I have tried to use the authenticate method in the view, as you would with a current_user method. However, it infinitely prompts you to login, which isn't ideal.

Is there a way to replicate the popular current_user method to check whether a session has been created and use this as a helper method?

application_controller.rb

helper_method :authenticate

USERS = { "username" => "password",
           "APP" => Digest::MD5.hexdigest(["APP", "realm", "password"].join(":"))}

private

def authenticate
    authenticate_or_request_with_http_digest(CONFIG[:realm]) do |username|
      USERS[username]
    end
  end

usage in controller

before_action :authenticate

Update

Thanks to Peter Goldstein's answer, I was able to save the username inside the authenticate block into a session[:admin] variable and use this inside the current_user helper method.

Upvotes: 1

Views: 1165

Answers (1)

Peter Goldstein
Peter Goldstein

Reputation: 4545

Something like this:

def authenticate
   current_user_name = nil
   is_authenticated = authenticate_or_request_with_http_digest(CONFIG[:realm]) do |username|
     current_user_name = username
     USERS[username]
   end
   @current_user = current_user_name if is_authenticated
   is_authenticated
end

def current_user
  @current_user
end
helper_method :current_user

should capture the username from the HTTP digest request and make it visible in the current_user method

Upvotes: 2

Related Questions