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

Damian Sieczkowski
Damian Sieczkowski
9,730 Points

Authorization for Rails API

I'm building an API for an iOS application that will be using Facebook to sign-up.

My plan as it stands is to get the iOS application to send the API an FB authentication token that it uses to gather information from FB open graph and create a user. Upon successfully creating a new user the API returns a devise generated authentication token to be stored client side and sent with each subsequent request to authorize it using Devise.secure_compare - i.e. when creating an associated record.

# this is in my users_controller.rb, I still have to add functionality 
# to check if the fb_user authenticated our app and 
# raise an error if they aren't authorized
private
def fb_authenticate(user_params)
    url = "https://graph.facebook.com/me?access_token=#{user_params[:fb_authentication_token]}"
    uri = URI.parse(URI.encode(url.strip))
    response = Net::HTTP.get_response(uri)
    body = JSON.parse(response.body)
    user_keys = User.new.attributes.keys
    fb_info = body.select { |key, value| user_keys.include? key }
    fb_info["facebook_id"] = fb_info.delete("id")
    @user_params = user_params.merge(fb_info)
end

# this is in my application_controller
private
  def authenticate_user_from_token!
    @authenticated_user = User.find_by_email(request.headers["Email"])
    unless @authenticated_user && Devise.secure_compare(@authenticated_user.authentication_token, request.headers["Authentication-Token"])
      render json: {error:  "You are not authorized."}, status: :unauthorized
    end
  end

Is this a good approach?