Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby Build a Rails API Authorization and Authentication Basic Authentication: Part 2

With Rails 4 and Devise, I get an error with this code - undefined method `authenticate'

Hi, I use Devise for authentication in my app. I would like users to be able to sign in and out, and use current_user for users accessing the app through the API as well.

I am getting this error: undefined method `authenticate' for #<User:0x007fc16c3a3e48>

for this line: if user && user.authenticate(password)

I do not have a Sessions Controller because I use Devise. Can you point me in the right direction? Thanks!

API Controller

module Api
  class ApiController < ApplicationController
    skip_before_filter :verify_authenticity_token
    protect_from_forgery with: :null_session
    #before_action :authenticate_api_user!, only: [ :create ]

    before_filter :authenticate

    def current_user
      @current_user
    end

    def authenticate
      authenticate_or_request_with_http_basic do |email, password|
        Rails.logger.info "API authentication:#{email} #{password}"
        user = User.find_by(email: email)
        if user && user.authenticate(password)
          @current_user = user
          Rails.logger.info "Logging in #{user.inspect}"
          true
        else
          Rails.logger.warn "No valid credentials."
          false
        end
      end
    end

  end
end

2 Answers

Manuel Quintanilla
Manuel Quintanilla
3,083 Points

You get that error because of nesting devise within the :api namespace in your routes.rb file. Therefore, you should authenticate users in the following way:

class Api::PostsController < ApplicationController
    before_action :authenticate_api_user!, only: [ :create ]
end

Hi, thanks for the answer - I tried that but I am actually just trying to log in and out, I haven't even gotten to creating posts yet. I added more detail above in case you can help. Thanks!

Did you ever find a solution to this? Currently having the same issue.