Как использовать Аутентификацию Spree в форме

Я изучаю рельсы и создаю веб-приложение, в котором также есть электронная коммерция. Существует форма, которую пользователь может заполнить только в том случае, если он вошел в систему. Для этого я использовал Devise, а для электронной коммерции я установил Spree Spree, у которого есть свой логин аутентификации, и нет authenticate_user! в контроллерах я тоже удалил devise и с трудом нашел способ использовать аутентификацию Spree с моей формой

Вот ОБНОВЛЕННЫЙ контроллер формы: жалоб_контроллер.рб

module Spree
class ComplaintsController < Spree::StoreController
  before_action :require_login

  before_action :set_complaint, only: [:show, :edit, :update, :destroy]

  # GET /complaints
  # GET /complaints.json



 def require_login
      redirect_to spree_login_path unless current_spree_user
    end 


      def index
        @complaints = Complaint.all
      end

  # GET /complaints/1
  # GET /complaints/1.json
  def show
  end

  # GET /complaints/new
  def new
    @complaint = Complaint.new
  end

  # GET /complaints/1/edit
  def edit
  end

  # POST /complaints
  # POST /complaints.json
  def create
    @complaint = Complaint.new(complaint_params)

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

  # PATCH/PUT /complaints/1
  # PATCH/PUT /complaints/1.json
  def update
    respond_to do |format|
      if @complaint.update(complaint_params)
        format.html { redirect_to @complaint, notice: 'Complaint was successfully updated.' }
        format.json { render :show, status: :ok, location: @complaint }
      else
        format.html { render :edit }
        format.json { render json: @complaint.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /complaints/1
  # DELETE /complaints/1.json
  def destroy
    @complaint.destroy
    respond_to do |format|
      format.html { redirect_to complaints_url, notice: 'Complaint was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_complaint
      @complaint = Complaint.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def complaint_params
      params.require(:complaint).permit(:id_society, :id_user, :heading, :text, :active, :action, :IsDelete, :flat_number)
    end
end
end
<% end %>

index.html.erb

  <% if spree_current_user %>
  <p id="notice"><%= notice %></p>

<h1>Listing Complaints</h1>

<table>
  <thead>
    <tr>
      <th>Id society</th>
      <th>Id user</th>
      <th>Heading</th>
      <th>Text</th>
      <th>Active</th>
      <th>Action</th>
      <th>Isdelete</th>
      <th>Flat number</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @complaints.each do |complaint| %>
      <tr>
        <td><%= complaint.id_society %></td>
        <td><%= complaint.id_user %></td>
        <td><%= complaint.heading %></td>
        <td><%= complaint.text %></td>
        <td><%= complaint.active %></td>
        <td><%= complaint.action %></td>
        <td><%= complaint.IsDelete %></td>
        <td><%= complaint.flat_number %></td>
        <td><%= link_to 'Show', complaint %></td>
        <td><%= link_to 'Edit', edit_complaint_path(complaint) %></td>
        <td><%= link_to 'Destroy', complaint, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New Complaint', new_complaint_path %>

<% else %>
<h1> please login</h1>
<% end %>

Это работает, так как он проверяет аутентификацию пользователя в View, есть ли способ проверить это в контроллере? Например, если пользователь вошел в систему, он будет отправлен к действию или перенаправлен на вход?

Спасибо

1 ответ

Решение

Spree использует разработанную аутентификацию через расширение:

https://github.com/spree/spree_auth_devise  

Для аутентификации ваших действий на уровне контроллеров (ваших собственных контроллеров) вам необходимо определить свой собственный фильтр аутентификации. Таким образом, вы можете управлять чем-то вроде этого:

before_action :require_login

def require_login
  redirect_to login_url unless current_spree_user
end 
Другие вопросы по тегам