BelgoCanadian
BelgoCanadian

Reputation: 934

How do i hookup a React button to authenticate with Devise Token Auth + OmniAuth

I'm having trouble connecting my Devise Token Auth with a token I get back from google in react.

I'm using this package for the button: https://www.npmjs.com/package/react-google-login

This is the auth I'm trying to set up: https://github.com/lynndylanhurley/devise_token_auth/blob/master/docs/config/omniauth.md

I'm getting a response from google with the react button but I have no idea how that information has to translate to go back to the devise auth.

Information online is severely lacking between these 2 technologies. What it comes down to is how to translate this ruby tag into react:

<%= link_to "Sign in with Google", user_google_oauth2_omniauth_authorize_path, method: :post %>

Upvotes: 3

Views: 1153

Answers (2)

radalin
radalin

Reputation: 600

It's in the end just a post request to that endpoint but I have encountered the same problems as you are.

What you need to do is to create a form like this:

<form action="<%=user_google_oauth2_omniauth_authorize_path %>" method="post">
<input type="hidden" name="authenticity_token" value="XX">
<button type="submit">Connect Google</button>
</form>

My trials failed when I haven't passed the auth token or added a "skip_before_action :verify_autneticity_token" to the callback controller. You need to fill the correct authenticity token, then it works.

Authenticity token information can be added to your html page's head section, via <%= csrf_meta_tags %>. Then you will need to parse the dom for the meta fields to fill them correctly.

Upvotes: 0

axelmukwena
axelmukwena

Reputation: 1049

I know this is old but here are my 2 cents.

I have used this gem OmniAuth Google OAuth2. The information is pretty clear. In my project, I manage my token using JWT while still storing the access and refresh tokens from Google.

Backend

# config/initializers/devise.rb
config.omniauth :google_oauth2,
                ENV['GOOGLE_CLIENT_ID'],
                ENV['GOOGLE_CLIENT_SECRET'],
                { scope: "userinfo.email, userinfo.profile",
                  prompt: 'select_account',
                  image_aspect_ratio: 'square',
                  provider_ignores_state: true,
                }
# controllers/users/omniauth_callbacks_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController

  def google_oauth2
    @user = User.from_omniauth(request.env['omniauth.auth'])

    if @user.persisted?
      # My personal token
      token = issue_token(@user)
      render json: { success: true,
                     user: @user,
                     token: token,
                     google_token: @user.access_token,
                     message: "Logged in successfully." }
    else
      render json: { success: false,
                     error: @user.errors.full_messages.join("\n"),
                     message: 'Google sign in unsuccessful.' }
    end
  end

  def failure
    set_flash_message! :alert, :failure, kind: OmniAuth::Utils.camelize(failed_strategy.name), reason: failure_message
    render json: { success: false, message: 'Google authentication failed.', reason: failure_message, kind: OmniAuth::Utils.camelize(failed_strategy.name) }
  end

  private

end
# In User.rb
  def self.from_omniauth(auth)

    user = User.where(email: auth.info.email).first

    if user
      user = User.update(id: user.id,
                         refresh_token: auth.credentials.refresh_token,
                         access_token: auth.credentials.token,
                         uid: auth.uid,
                         )
    else
      # Create a username from names, append incremental if username already exists
      username ||= auth.info.first_name + auth.info.last_name
      username = username.delete('^a-zA-Z0-9_').downcase
      num = 1
      until User.find_by(username: username).nil?
        username = "#{username}#{num}"
        num += 1
      end

      user = User.create(email: auth.info.email,
                         uid: auth.uid,
                         refresh_token: auth.credentials.refresh_token,
                         access_token: auth.credentials.token,
                         provider: auth.provider,
                         password: Devise.friendly_token[0, 20],
                         firstname: auth.info.first_name,
                         lastname: auth.info.last_name,
                         username: username,
                         )
    end
    user
  end
    # routes.rb
    # User Routes: Devise
    devise_for :users,
               path_names: {
                 sign_in: 'login',
                 sign_out: 'logout',
                 # sign_up: 'register'
               },
               controllers: {
                 sessions: 'users/sessions',
                 registrations: 'users/registrations',
                 omniauth_callbacks: 'users/omniauth_callbacks'
               }

Above routes translations

user_google_oauth2_omniauth_authorize_path  GET|POST    /api/users/auth/google_oauth2(.:format) 
users/omniauth_callbacks#passthru

user_google_oauth2_omniauth_callback_path   GET|POST    /api/users/auth/google_oauth2/callback(.:format)    
users/omniauth_callbacks#google_oauth2

Here is the front end

<!-- index.html -->
<head>
  <script src="https://apis.google.com/js/platform.js?onload=init" async defer></script>
</head>

Do not worry about defining the gapi function, it is loaded script in the above

// RegisterContent.js
const RegisterContent = function RegisterContent() {

     function handleResponse(response) {
         // Save user to redux store and all the tokens to cookies
     }

    // callback
    function signInCallback(authResult) {
        if (authResult.code) {
            const params = { code: authResult.code }
            const path = "localhost:3000/api/users/auth/google_oauth2/callback";
            // This just handdles posting with axios 
            postResource(path, params, handleResponse);
        }
    }

    // This will prompt opening the google window and returns a callback upon success
    const googleHandler = () => {
        googleAuth.grantOfflineAccess().then(signInCallback);
    };

    useEffect(() => {
        // Initialize the GoogleAuth object
        gapi.load("auth2", function foo() {
            const auth = gapi.auth2.init({
                client_id: process.env.REACT_APP_GOOGLE_CLIENT_ID,
                scope: "email profile",
            });
            setGoogleAuth(auth);
            console.log("Init");
        });
    }, []);

    return (
        <Button onclick={googleHandler}>
            Continue with Google
        </Button>
    
    );

}

A few resources to help Google Sign-In JavaScript client reference, How to integrate Google API into your React app and that's it.

Upvotes: 2

Related Questions