1

I have a rails 5.2 app that was originally built with Devise and plain old erb files. I could check current_user in the frontend and all that.

Now I am trying to slowly move it to React frontend. I haven't changed any of my setup but my controller's create action returns false for user_signed_in? but at index it returns true. Is there a header I am not passing in my request?

sample code

class FanciesController < ApplicationController

  skip_before_action :verify_authenticity_token, only: :search_fancy
  after_action :verify_authorized

  def index
    @fancies = Fancy.all

    authorize @fancies

    respond_to do |format|
      format.html { render :index }
      format.json { render json: {...}, status: :ok }
    end
  end

  def create
    @fancy = Fancy.new(...)
    authorize @fancy

    respond_to do |format|
      if @fancy.save
        format.html { redirect_to @fancy, notice: 'Availability was successfully created.' }
        format.json { render :show, status: :created, json: {..}}
      else
        format.html { render :new }
        format.json { render json: {...}, status: :unprocessable_entity }
      end
    end
  end

end

Frontend code:

#index.html.erb

<%= react_component("FancyScreen", { selection_fancies: @fancies }) %>

react component:

class FancyScreen extends React.Component {
  ...
    onCreateClick(selected_time) {
      const headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' };

      const requestOptions = {
        method: 'POST',
        headers: headers,
        body: JSON.stringify({...})
      }

      fetch(curl_url, requestOptions)
      .then(response => response.json())
      .then(data => {

        new_fancy.push(data)
        fn.setState({
          fancies: new_fancy
        });
      });
    }
  }
}

I tried passing the csrf token through my headers and that still did not work.

‘X-CSRF-TOKEN’: $(‘meta[name=”csrf-token”]’).attr(‘content’)

I am definitely away i am missing some fundementals but if someone could point me in the right direction I am sure I could figure it out. I tried installing devise-jwt gem but looks like it is not really what I want.

Any ideas on what I am doing wrong?

Coding Enthusiast
  • 3,865
  • 1
  • 27
  • 50

1 Answers1

0

IMO in order to authenticate user in React - Rails intergration you need to use a token based authentication system. Check devise_token_auth gem. After the first sign in rails send you client-id, token-id and uid. Store them in cookies and every time you make an API call send them in the header. API will refresh those values and will send them back to front. Update again the cookies with the new values and go on with that procedure.