Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


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
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)

# this is in my application_controller
  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

Is this a good approach?