18

I'm using devise and devise_token_auth along side each other. I have an Ionic 2 application that I'm attempting to login via Facebook with. Right now, the email/password authentication is working fine. Here's some of my code.

# initializers/devise_token_auth.rb
config.enable_standard_devise_support = true

# initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, 'xxxxx', 'xxxxx', scope: 'email', info_fields: 'email,first_name,last_name'
end

# app/models/user.rb
devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :omniauthable, :omniauth_providers => [:facebook, :google]
include DeviseTokenAuth::Concerns::User
devise :omniauthable

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery with: :null_session, if: -> { request.format.json? }
  include DeviseTokenAuth::Concerns::SetUserByToken
  # Allow other fields to be passed up on registration.
  before_action :configure_permitted_parameters, if: :devise_controller?
  def after_sign_in_path_for(resource)
    users_path
  end
  def authenticate_admin
    unless current_user && current_user.role == 'admin'
      flash[:error] = "Not Authorized"
      redirect_to root_path
    end
  end
  protected
  # Allow other fields to be passed up on registration.
  def configure_permitted_parameters
    # Permit the default plus the following.
    devise_parameter_sanitizer.permit(:sign_up, keys: [:subscribed])
  end
end

# config/routes.rb
devise_for :users, controllers: { :sessions => "users/sessions" }

namespace :api do
    namespace :v1 do
      mount_devise_token_auth_for 'User', at: 'auth'
    end
end

user_facebook_omniauth_authorize_path | GET\|POST | /omniauth/facebook(.:format) | devise/omniauth_callbacks#passthru
-- | -- | -- | --
user_facebook_omniauth_callback_path | GET\|POST | /omniauth/facebook/callback(.:format) | devise/omniauth_callbacks#facebook
user_google_omniauth_authorize_path | GET\|POST | /omniauth/google(.:format) | devise/omniauth_callbacks#passthru
user_google_omniauth_callback_path | GET\|POST | /omniauth/google/callback(.:format) | devise/omniauth_callbacks#google
GET | /api/v1/auth/:provider/callback(.:format) | devise_token_auth/omniauth_callbacks#omniauth_success
-- | -- | --
  | GET\|POST | /omniauth/:provider/callback(.:format) | devise_token_auth/omniauth_callbacks#redirect_callbacks
omniauth_failure_path | GET\|POST | /omniauth/failure(.:format) | devise_token_auth/omniauth_callbacks#omniauth_failure
  | GET | /api/v1/auth/:provider(.:format) | redirect(301)

And in my Ionic 2 app is the following

doFbLogin() {
    let permissions = ["public_profile"];
    let objThis = this;
    Facebook.login(permissions)
      .then(function (response) {
        objThis.authService.tryFacebookLogin(response.authResponse).subscribe(
          responseNow => console.log(responseNow),
          error => console.log(error)
        );
      }, function (error) {
        console.log(error);
      });


tryFacebookLogin(objParams) {
    return this.http.get(
      'https://example.com/api/v1/auth/facebook',
      this.apiService.getGetOptions(objParams)
    ).map((res) => this.apiService.extractData(res)).catch(this.apiService.handleError);
  }

I've tried to modify and mess around with several configuration settings but have had no luck. When I check my server logs I consistently see this. It doesn't create a Facebook user or anything.

Seans-MacBook-Air:app-s sean$ heroku logs
2017-08-30T17:19:19.354023+00:00 app[web.1]: [d3b2de6b-3404-4f26-a29b-094630260afc]   Parameters: {"token_validation"=>{}}
2017-08-30T17:19:20.089604+00:00 heroku[router]: at=info method=GET path="/api/v1/auth/validate_token" host=myherokuapp.herokuapp.com request_id=d3b2de6b-3404-4f26-a29b-094630260afc fwd="70.51.192.141" dyno=web.1 connect=0ms service=762ms status=401 bytes=1982 protocol=https
2017-08-30T17:19:20.086908+00:00 app[web.1]: [d3b2de6b-3404-4f26-a29b-094630260afc] Completed 401 Unauthorized in 733ms (Views: 0.3ms | ActiveRecord: 0.0ms)
2017-08-30T17:19:23.299874+00:00 heroku[router]: at=info method=GET path="/api/v1/auth/facebook?accessToken=EAAFDh9WxI34BACq4ZBJcZBRKOn0wTHJioXequZBlKNN6CzP1rChH7a14SZBOw6mEkhoIXPBXVqET37ANMRMKkk17ErOp4qDMC8JEUWKIT3ph1GhRYFyWLzUQrPmSRTnEICFCkmac4tPMeptO2rHcZCKJwvOnQB0K8TENdR1a3IJZAaiWfXisjSFy01qSWM3sdXxuftkcjgLHxXYLHTEIXll3D5hMf2uOAZD&expiresIn=5180219&session_key=true&sig=...&userID=10156547461238276&deviceToken=foQhl4DYPVI:APA91bFV1L_DM-YcciCPSj3XudUfu8hiThoR2T_uwl0-xSjSNE865tZ36tm4X1mp7Z9z8QzqFVmEpgW2bKRKRmguOVYNFMiORtR7DKo8NsQoCQmb" host=myherokuapp.herokuapp.com request_id=382104a1-2279-4d14-8bc9-0eefe57f3a45 fwd="70.51.192.141" dyno=web.1 connect=1ms service=6ms status=301 bytes=1463 protocol=https
2017-08-30T17:19:23.293472+00:00 app[web.1]: [382104a1-2279-4d14-8bc9-0eefe57f3a45] Started GET "/api/v1/auth/facebook?accessToken=EAAFDh9WxI34BACq4ZBJcZBRKOn0wTHJioXequZBlKNN6CzP1rChH7a14SZBOw6mEkhoIXPBXVqET37ANMRMKkk17ErOp4qDMC8JEUWKIT3ph1GhRYFyWLzUQrPmSRTnEICFCkmac4tPMeptO2rHcZCKJwvOnQB0K8TENdR1a3IJZAaiWfXisjSFy01qSWM3sdXxuftkcjgLHxXYLHTEIXll3D5hMf2uOAZD&expiresIn=5180219&session_key=true&sig=...&userID=10156547461238276&deviceToken=foQhl4DYPVI:APA91bFV1L_DM-YcciCPSj3XudUfu8hiThoR2T_uwl0-xSjSNE865tZ36tm4X1mp7Z9z8QzqFVmEpgW2bKRKRmguOVYNFMiORtR7DKo8NsQoCQmb" for 70.51.192.141 at 2017-08-30 17:19:23 +0000
2017-08-30T17:19:23.356264+00:00 app[web.1]: [65adeff7-ebb7-4b9a-8c83-6d0154a4b19d] Started GET "/omniauth/facebook?accessToken=EAAFDh9WxI34BACq4ZBJcZBRKOn0wTHJioXequZBlKNN6CzP1rChH7a14SZBOw6mEkhoIXPBXVqET37ANMRMKkk17ErOp4qDMC8JEUWKIT3ph1GhRYFyWLzUQrPmSRTnEICFCkmac4tPMeptO2rHcZCKJwvOnQB0K8TENdR1a3IJZAaiWfXisjSFy01qSWM3sdXxuftkcjgLHxXYLHTEIXll3D5hMf2uOAZD&deviceToken=foQhl4DYPVI:APA91bFV1L_DM-YcciCPSj3XudUfu8hiThoR2T_uwl0-xSjSNE865tZ36tm4X1mp7Z9z8QzqFVmEpgW2bKRKRmguOVYNFMiORtR7DKo8NsQoCQmb&expiresIn=5180219&namespace_name=api&resource_class=User&session_key=true&sig=...&userID=10156547461238276" for 70.51.192.141 at 2017-08-30 17:19:23 +0000
2017-08-30T17:19:23.356815+00:00 app[web.1]: I, [2017-08-30T17:19:23.356739 #4]  INFO -- omniauth: (facebook) Request phase initiated.
2017-08-30T17:19:23.367474+00:00 heroku[router]: at=info method=GET path="/omniauth/facebook?accessToken=EAAFDh9WxI34BACq4ZBJcZBRKOn0wTHJioXequZBlKNN6CzP1rChH7a14SZBOw6mEkhoIXPBXVqET37ANMRMKkk17ErOp4qDMC8JEUWKIT3ph1GhRYFyWLzUQrPmSRTnEICFCkmac4tPMeptO2rHcZCKJwvOnQB0K8TENdR1a3IJZAaiWfXisjSFy01qSWM3sdXxuftkcjgLHxXYLHTEIXll3D5hMf2uOAZD&deviceToken=foQhl4DYPVI:APA91bFV1L_DM-YcciCPSj3XudUfu8hiThoR2T_uwl0-xSjSNE865tZ36tm4X1mp7Z9z8QzqFVmEpgW2bKRKRmguOVYNFMiORtR7DKo8NsQoCQmb&expiresIn=5180219&namespace_name=api&resource_class=User&session_key=true&sig=...&userID=10156582648249377" host=myherokuapp.herokuapp.com request_id=65adeff7-ebb7-4b9a-8c83-6d0154a4b19d fwd="70.51.192.141" dyno=web.1 connect=1ms service=11ms status=302 bytes=2283 protocol=https
2017-08-30T17:39:04.311735+00:00 heroku[router]: at=info method=GET path="/api/v1/auth/facebook?accessToken=df978g6hd78fg6h78d6fghaUOlH2X3NMRhbZCsiXjSbrpaSEaZBImkIzQXVeR5uqctZBBYjW0C9XSRqzXuuEz5ZCEOvkktSqJnjmJMgl7ZB4aEQDMRkACPzcSaKxZCHwV9saMLPEkgEYivJ5jWdfghdfghdfghdfghtJBJUw9ZAPkaPo6tXt1CwyCAxoCUJKjapXn4ZAGvyKnxUPCUMrRZBQSvMMZD&expiresIn=5179039&session_key=true&sig=...&userID=10156582648249377&deviceToken=foQhl4DYPVI:APA91bFV1L_DM-YcciCPSj3XudUfu8hiThoR2T_uwl0-xSjSNE865tZ36tm4X1mp7Z9z8QzqFVmEpgW2bKRKRmguOVYNFMiORtR7DKo8NsQoCQmb" host=myherokuapp.herokuapp.com request_id=d5f155e0-624e-4ed8-b169-3e6f481b23ca fwd="70.51.192.141" dyno=web.1 connect=1ms service=4ms status=301 bytes=1471 protocol=https
2017-08-30T17:39:04.307596+00:00 app[web.1]: [d5f155e0-624e-4ed8-b169-3e6f481b23ca] Started GET "/api/v1/auth/facebook?accessToken=df978g6hd78fg6h78d6fghaUOlH2X3NMRhbZCsiXjSbrpaSEaZBImkIzQXVeR5uqctZBBYjW0C9XSRqzXuuEz5ZCEOvkktSqJnjmJMgl7ZB4aEQDMRkACPzcSaKxZCHwV9saMLPEkgEYivJ5jWdfghdfghdfghdfghtJBJUw9ZAPkaPo6tXt1CwyCAxoCUJKjapXn4ZAGvyKnxUPCUMrRZBQSvMMZD&expiresIn=5179039&session_key=true&sig=...&userID=10156582648249377&deviceToken=foQhl4DYPVI:APA91bFV1L_DM-YcciCPSj3XudUfu8hiThoR2T_uwl0-xSjSNE865tZ36tm4X1mp7Z9z8QzqFVmEpgW2bKRKRmguOVYNFMiORtR7DKo8NsQoCQmb" for 70.51.192.141 at 2017-08-30 17:39:04 +0000
2017-08-30T17:39:04.502963+00:00 app[web.1]: [ae1670c5-1246-4566-bdf5-24724ba98520] Started GET "/omniauth/facebook?accessToken=df978g6hd78fg6h78d6fghaUOlH2X3NMRhbZCsiXjSbrpaSEaZBImkIzQXVeR5uqctZBBYjW0C9XSRqzXuuEz5ZCEOvkktSqJnjmJMgl7ZB4aEQDMRkACPzcSaKxZCHwV9saMLPEkgEYivJ5jWdfghdfghdfghdfghtJBJUw9ZAPkaPo6tXt1CwyCAxoCUJKjapXn4ZAGvyKnxUPCUMrRZBQSvMMZD&deviceToken=foQhl4DYPVI:APA91bFV1L_DM-YcciCPSj3XudUfu8hiThoR2T_uwl0-xSjSNE865tZ36tm4X1mp7Z9z8QzqFVmEpgW2bKRKRmguOVYNFMiORtR7DKo8NsQoCQmb&expiresIn=5179039&namespace_name=api&resource_class=User&session_key=true&sig=...&userID=10156582648249377" for 70.51.192.141 at 2017-08-30 17:39:04 +0000
2017-08-30T17:39:04.503515+00:00 app[web.1]: I, [2017-08-30T17:39:04.503429 #4]  INFO -- omniauth: (facebook) Request phase initiated.
2017-08-30T17:39:04.515926+00:00 heroku[router]: at=info method=GET path="/omniauth/facebook?accessToken=df978g6hd78fg6h78d6fghaUOlH2X3NMRhbZCsiXjSbrpaSEaZBImkIzQXVeR5uqctZBBYjW0C9XSRqzXuuEz5ZCEOvkktSqJnjmJMgl7ZB4aEQDMRkACPzcSaKxZCHwV9saMLPEkgEYivJ5jWdfghdfghdfghdfghtJBJUw9ZAPkaPo6tXt1CwyCAxoCUJKjapXn4ZAGvyKnxUPCUMrRZBQSvMMZD&deviceToken=foQhl4DYPVI:APA91bFV1L_DM-YcciCPSj3XudUfu8hiThoR2T_uwl0-xSjSNE865tZ36tm4X1mp7Z9z8QzqFVmEpgW2bKRKRmguOVYNFMiORtR7DKo8NsQoCQmb&expiresIn=5179039&namespace_name=api&resource_class=User&session_key=true&sig=...&userID=10156582648249377" host=myherokuapp.herokuapp.com request_id=ae1670c5-1246-4566-bdf5-24724ba98520 fwd="70.51.192.141" dyno=web.1 connect=1ms service=17ms status=302 bytes=2283 protocol=https

EDIT

Still can't figure out this one. I do know though that when I try to log in via Facebook through my Ionic app, my Heroku logs show that Omniauth just dies at INFO -- omniauth: (facebook) Request phase initiated.. It never reaches or tries to hit the callback because otherwise it would say INFO -- omniauth: (facebook) Callback phase initiated., which it doesn't ever say. All of that being said, this process works and the Facebook user gets saved if I do it manually through my Rails site. Any ideas at all why that callback is not being triggered though the app? I'm lost.

EDIT

At this point I'm not even sure if its the correct implementation of Ionic 2 and devise_token_auth Facebook omniauth login. Could be an issue on the Ionic side of things? Like I said, through the browser it seems to work. I literally take the /api/auth/facebook?..... code below in my logs and paste it in the browser and it inserts the user.

How would one go about getting this to work with an Ionic 2 application? It seems everything is working through the browser but fails when I try to proceed with Facebook login through Ionic. Here's my Ionic 2 code to Login:

doFacebookLogin() {
    let objThis = this;
    this.fb.login(['public_profile', 'email'])
      .then(function (response) {
        objThis.authService.tryFacebookLogin(response.authResponse).subscribe(
          responseNow => objThis.loginSuccess(responseNow),
          error => console.log(error)
        );
      }, function (error) {
        console.log(error);
      });
  }
tryFacebookLogin(objParams) {
    return this.http.get(
      this.apiService.createUrl('auth/facebook'),
      this.apiService.getGetOptions(objParams)
    ).map((res) => this.apiService.extractData(res)).catch(this.apiService.handleError);
  }

And my logs from Heroku:

[d9350f73-4cbc-400c-8296-0248b2454a64] Started GET "/api/auth/facebook?accessToken=EAAFDh9WxI34BAEpTy54mVhiZCUtGDcCdQgHg8yYxIfHCk0iciDUZCsrkZAdu9SJ8vCLMZChgt7QoGZBkzvWzNkFFLhwJEcCrxtRo9dJ8ioOsErwM8h2Kv8dileZAjACZAheVg7nIxd7gKX1kZALdY2Ve7rwFxLeg0eKCYfZBBHGkjaZALkwLY1tEktsKYfrBNAR6wii2LZBoQtUEKe0Acc8ZD&expiresIn=5107217&session_key=true&sig=...&userID=xxx" for 184.145.16.206 at 2017-09-27 17:08:41 +0000
2017-09-27T17:08:41.505526+00:00 app[web.1]: [3c08d61c-4c30-4361-902a-cee8e15b63bc] Started GET "/omniauth/facebook?accessToken=EAAFDh9WxI34BAEpTy54mVhiZCUtGDcCdQgHg8yYxIfHCk0iciDUZCsrkZAdu9SJ8vCLMZChgt7QoGZBkzvWzNkFFLhwJEcCrxtRo9dJ8ioOsErwM8h2Kv8dileZAjACZAheVg7nIxd7gKX1kZALdY2Ve7rwFxLeg0eKCYfZBBHGkjaZALkwLY1tEktsKYfrBNAR6wii2LZBoQtUEKe0Acc8ZD&expiresIn=5107217&namespace_name=api&resource_class=User&session_key=true&sig=...&userID=xxx" for 184.145.16.206 at 2017-09-27 17:08:41 +0000
2017-09-27T17:08:41.507171+00:00 app[web.1]: I, [2017-09-27T17:08:41.506900 #4]  INFO -- omniauth: (facebook) Request phase initiated.

Through the app, it seems to die at INFO -- omniauth: (facebook) Request phase initiated. every single time. It never proceeds to the callback.

halfer
  • 19,824
  • 17
  • 99
  • 186
SeanWM
  • 16,789
  • 7
  • 51
  • 83
  • Since you log your JS responses to the console (`console.log(error)`), did you receive anything? – Holger Frohloff Sep 12 '17 at 09:43
  • @HolgerFrohloff I get the proper data from Facebook `"{"status":"connected","authResponse":{"accessToken":"EAAFDh9WxI34BAFcUFVS0FukZBijtTpZBZBj3Gcc79sc3gtthgGhJ7kxoxNsg3PZAHI1Wp62i35QGzNXf43hYG5CehNs9xl7aTP6ee1PwcENLVmBiCYpOTYzsZCGehyGZBqYqIEIS1rhjuIp6SZAREuB8LzXqBQdIxeLEg7fi0p3df8a7s9d8f6a879sd6f7a8s6df76asdfa6s78d6f987as6gd76sdf9g7sd8f6gfg","expiresIn":"5102471","session_key":true,"sig":"...","userID":"xxxxx"}}"` – SeanWM Sep 14 '17 at 15:19

1 Answers1

1

I know it sounds weird but, please try to switch your devise_for :users routes below the namespace :api

Like this:

namespace :api do
    namespace :v1 do
      mount_devise_token_auth_for 'User', at: 'auth'
    end
end

# config/routes.rb
devise_for :users, controllers: { :sessions => "users/sessions" }

Also, add skip: [:registrations] to exclude conflicts:

devise_for :users, controllers: {sessions: "users/sessions"}, skip: [:registrations]

And go to initializers/devise_token_auth.rb and make sure that config.enable_standard_devise_support is set to true

After trying this, can you override registrations controller and simply add a pry or some debug puts with your incoming params? thanks

jpgbarbosa
  • 780
  • 4
  • 14
  • Didn't make a difference. Interested thing to note though, it seems when I hit the endpoint `auth/facebook` it fails like I mentioned above. BUT, if I run the heroku logs I see `/omniauth/facebook?accessToken=xxx&expiresIn=5180180&namespace_name=api_v1&resource_class=User&session_key=true&sig=...&userID=xxx`. If I copy that URL to my browser and hit my server manually, the facebook user actually registers and it works. It seems like it just doesn't work with the api. – SeanWM Sep 14 '17 at 18:03
  • long shot but you have a `devise :omniauthable` right after `include DeviseTokenAuth::Concerns::User` and before. So, I'd recommend you to remove the last one. Unless there's something I may not be noticing. – jpgbarbosa Sep 14 '17 at 19:41
  • unfortunately that didn't make a difference... seems like it's just randomly failing at some point.. I did see it hit the callback function because it hit an error where "name" didn't exist on the user model. I added a migration to fix that and now I'm not getting any feedback on if it's hitting the callback when going through the api. – SeanWM Sep 14 '17 at 19:52
  • That's weird because it worked with without the API. Make sure you're not requiring email attr for example. Otherwise override register controller just like [this](https://github.com/lynndylanhurley/devise_token_auth/blob/master/app/controllers/devise_token_auth/omniauth_callbacks_controller.rb#L28), then debug each iteration with `binding.pry` and try to understand where it's failing. If it's getting in this endpoint you'll easily find the cause. Otherwise it's a routes issue. But this is just a suggestion, I'm a bit lost too. – jpgbarbosa Sep 14 '17 at 20:01
  • So I don't even think the api is hitting those `omniauth_callbacks_controller` methods. I overrode `redirect_callbacks` and `omniauth_success` and nothing outputted in the logs. When I do it though the brower though I see the debugging stuff. This is the last thing I see when I click "login with FB" on my app from my Heroku server `2017-09-15T14:30:09.037870+00:00 heroku[router]: at=info method=GET path="/omniauth/facebook?accessToken=xxxxxxxx"`. Must be a routing issue? This is my route when I hit login with FB `/api/v1/auth/:provider(.:format) ---> . redirect(301)` – SeanWM Sep 15 '17 at 14:34
  • and the route when it dies is `GET|POST --> /omniauth/facebook(.:format) --> devise/omniauth_callbacks#passthru` – SeanWM Sep 15 '17 at 14:43
  • lastly, when running it through my browser, it actually says it's starting that route that the API is dying at `Started GET "/omniauth/facebook?accessToken=xxxxxx"` Then it continues to `Started GET "/omniauth/facebook/callback?code=xxxxxxx"` and actually inserts the user – SeanWM Sep 15 '17 at 14:49
  • I'd say it's definitely a routing issue. I'm a little bit confused now when you said `it's starting... then it continues to...`. I'd suggest you to remove regular devise stuff, and test only with devise token. So isolate it and make sure it works through the api without the browser direct request. If it works fine it's a devise conflict issue. Otherwise it should some config on devise_token only. I bet on the first one. Also, test it in incognito without cache or any ad blocker – jpgbarbosa Sep 15 '17 at 14:59
  • Similar issue here https://github.com/lynndylanhurley/devise_token_auth/issues/666 try his hackish solution... repeated devise instructions on model before and after `include DeviseTokenAuth::Concerns::User`. But apparently he can't distinguish routes now. Btw, make sure this is really running if request is json. `protect_from_forgery with: :null_session, if: -> { request.format.json? }` as also, make sure that on your client your request is being sent with proper json format. – jpgbarbosa Sep 15 '17 at 15:13
  • So, this seems to be working with me: namespace :api do scope module: :v1, constraints: ApiConstraint.new(version: 1, default: true) do mount_devise_token_auth_for 'User', at: 'auth' end end devise_for :users, skip: [:registrations, :passwords, :confirmations] include DeviseTokenAuth::Concerns::User inside User class but first line sorry for this formatting – jpgbarbosa Sep 15 '17 at 15:24
  • Made a lot of those changes and still the same thing.. that being said, I do notice that the API is saying `Started GET "/omniauth/facebook?accessToken=xxxxx"`, it's just not triggering that `"/omniauth/facebook/callback?code=xxxxxxx"` – SeanWM Sep 15 '17 at 16:16