Rails 6, Authlogi c 6, Несогласованное поведение выхода из системы в разных браузерах - PullRequest
0 голосов
/ 12 апреля 2020

Итак, я поигрался с authlogi c в новом приложении на Rails 6, чтобы посмотреть, не хочу ли я начать использовать его для упрощения аутентификации в некоторых других приложениях. Я в основном все настроил так, как указано в репозитории github, примерно настолько, насколько это возможно. Кажется, все работает нормально, кроме выхода пользователя. В Chrome все работает, как и ожидалось, пользователь вышел из системы, как и ожидалось. Но по какой-то причине доступ к маршруту / logout фактически не выводит пользователя из системы - веб-консоль показывает, что файл user_credentials cook ie никогда не удаляется, пользователь остается в системе (хотя отображается флаг fla sh, поэтому правильный маршрут ударил).

Как ни странно, если я добавлю функцию logout_on_timeout и вручную установлю current_user.last_request_at, чтобы сказать 20 минут a go, я вышел из обоих браузеров, как и ожидалось.

Я включу весь соответствующий код ниже, кроме страницы индекса # со ссылками на вход / выход и регистрацию, единственное, что не является стандартным шаблоном нового приложения Rails, - это authlogi c. Я пробовал current_user_session.destroy, предложенную альтернативу session.destroy, и вручную очищал куки с cookie.delete.

У меня такое ощущение, что это что-то базовое c, возможно, нужно выполнить конфигурационную опцию с каким куки отправляются? но я потратил несколько часов, пытаясь понять, что происходит. Есть идеи?

Gemfile:

gem 'scrypt', '~> 3.0'
gem 'authlogic', '~> 6.0'

UserSessionsController

class UserSessionsController < ApplicationController
  def new
    @user_session = UserSession.new
  end
  def create
    @user_session = UserSession.new(user_session_params.to_h)
    if @user_session.save
      flash[:success] = 'You have been logged in.'
      redirect_to root_path
    else
      flash.now[:danger] = 'Unable to log you in'
      render :new
    end
  end
  def destroy
    current_user_session.destroy
    # session.destroy - tried this as well
    flash[:success] = 'You have been logged out.'
    redirect_to root_path
  end

  private

    def user_session_params
      params.require(:user_session).permit(:email, :password, :remember_me)
    end
end

ApplicationController

class ApplicationController < ActionController::Base
  helper_method :current_user_session, :current_user

  private

    def current_user_session
      return @current_user_session if defined?(@current_user_session)
      @current_user_session = UserSession.find
    end

    def current_user
      return @current_user if defined?(@current_user)
      @current_user = current_user_session && current_user_session.user
    end
end

Модель UserSession

class UserSession < Authlogic::Session::Base
  logout_on_timeout true
end

Модель пользователя

class User < ApplicationRecord
  acts_as_authentic do |c|
    c.crypto_provider = ::Authlogic::CryptoProviders::SCrypt
  end
  validates :email,
    format: {
      with: /@/,
      message: "should look like an email address"
    },
    length: { maximum: 100 },
    uniqueness: {
      case_sensitive: false,
      if: :will_save_change_to_email?
    }
  validates :password,
  confirmation: { if: :require_password? },
  length: {
    minimum: 8,
    if: :require_password?
  }
  validates :password_confirmation,
    length: {
      minimum: 8,
      if: :require_password?
  }
end

Основа c Индекс

Просто для проверки функциональности входа / выхода

<% if current_user %>
  <p>Logged in as <strong><%= current_user.email %></strong>. <%= link_to 'Log Out', user_session_path, method: :delete %></p>
<% else %>
  <p>You are not logged in. <%= link_to 'Log In', new_user_session_path %> or <%= link_to 'Register', new_user_path %></p>
<% end %>

Наконец, миграция CreateUsers

class CreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      # Authlogic::ActsAsAuthentic::Email
      t.string    :email
      t.index     :email, unique: true

      # Authlogic::ActsAsAuthentic::Password
      t.string    :crypted_password
      t.string    :password_salt

      # Authlogic::ActsAsAuthentic::PersistenceToken
      t.string    :persistence_token
      t.index     :persistence_token, unique: true

      # Authlogic::ActsAsAuthentic::SingleAccessToken
      t.string    :single_access_token
      t.index     :single_access_token, unique: true

      # Authlogic::ActsAsAuthentic::PerishableToken
      t.string    :perishable_token
      t.index     :perishable_token, unique: true

      # See "Magic Columns" in Authlogic::Session::Base
      t.integer   :login_count, default: 0, null: false
      t.integer   :failed_login_count, default: 0, null: false
      t.datetime  :last_request_at
      t.datetime  :current_login_at
      t.datetime  :last_login_at
      t.string    :current_login_ip
      t.string    :last_login_ip

      # See "Magic States" in Authlogic::Session::Base
      # t.boolean   :active, default: false
      # t.boolean   :approved, default: false
      # t.boolean   :confirmed, default: false

      # Additional
      t.string :first_name
      t.string :last_name
      t.string :unconfirmed_email
      t.index :unconfirmed_email, unique: true

      t.timestamps
    end
  end
end
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...