taiti101112 / portfolio

0 stars 0 forks source link

質問 #149

Closed taiti101112 closed 1 month ago

taiti101112 commented 2 months ago

自分と似たような状況の記事がなかったのでチャットGPTが原因に挙げた箇所がどのような働きをしているのかを調べて以下のように変更を加えましたがうまくいきませんでした

session_store.rb

Rails.application.config.session_store :cookie_store, key: '_tcg_place_session', secure: Rails.env.production?, same_site: :lax, domain: :all, tld_length: 2

importmap.rb

# Pin npm packages by running ./bin/importmap

pin "application"
pin "bootstrap", to: "https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"
pin "@popperjs/core", to: "https://unpkg.com/@popperjs/core@2.11.6/dist/umd/popper.min.js"
pin "@rails/ujs", to: "rails-ujs.js"
pin "@hotwired/turbo-rails", to: "https://cdn.jsdelivr.net/npm/@hotwired/turbo@7.3.0/dist/turbo.es2017-umd.js"

devise.rb

# frozen_string_literal: true

# Assuming you have not yet modified this file, each configuration option below
# is set to its default value. Note that some are commented out while others
# are not: uncommented lines are intended to protect your configuration from
# breaking changes in upgrades (i.e., in the event that future versions of
# Devise change the default values for those options).
#
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
  # The secret key used by Devise. Devise uses this key to generate
  # random tokens. Changing this key will render invalid all existing
  # confirmation, reset password and unlock tokens in the database.
  # Devise will use the `secret_key_base` as its `secret_key`
  # by default. You can change it below and use your own secret key.
  # config.secret_key = 'da17e9738cd2760572af5a08d737d804590757edd56ad8363abdc22d571903c76f149a18a31f9892ac51a20bc93ce4a7779e68c03c1a274f8b11928529760f35'

  # ==> Controller configuration
  # Configure the parent class to the devise controllers.
  # config.parent_controller = 'DeviseController'

  # ==> Mailer Configuration
  # Configure the e-mail address which will be shown in Devise::Mailer,
  # note that it will be overwritten if you use your own mailer class
  # with default "from" parameter.
  config.mailer_sender = ENV['MAILER_SENDER']

  # Configure the class responsible to send e-mails.
  config.mailer = 'Devise::Mailer'

  # Configure the parent class responsible to send e-mails.
  # config.parent_mailer = 'ActionMailer::Base'

  # ==> ORM configuration
  # Load and configure the ORM. Supports :active_record (default) and
  # :mongoid (bson_ext recommended) by default. Other ORMs may be
  # available as additional gems.
  require 'devise/orm/active_record'

  # ==> Configuration for any authentication mechanism
  # Configure which keys are used when authenticating a user. The default is
  # just :email. You can configure it to use [:username, :subdomain], so for
  # authenticating a user, both parameters are required. Remember that those
  # parameters are used only when authenticating and not when retrieving from
  # session. If you need permissions, you should implement that in a before filter.
  # You can also supply a hash where the value is a boolean determining whether
  # or not authentication should be aborted when the value is not present.
  config.authentication_keys = [:email]

  # Configure parameters from the request object used for authentication. Each entry
  # given should be a request method and it will automatically be passed to the
  # find_for_authentication method and considered in your model lookup. For instance,
  # if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
  # The same considerations mentioned for authentication_keys also apply to request_keys.
  # config.request_keys = []

  # Configure which authentication keys should be case-insensitive.
  # These keys will be downcased upon creating or modifying a user and when used
  # to authenticate or find a user. Default is :email.
  config.case_insensitive_keys = [:email]

  # Configure which authentication keys should have whitespace stripped.
  # These keys will have whitespace before and after removed upon creating or
  # modifying a user and when used to authenticate or find a user. Default is :email.
  config.strip_whitespace_keys = [:email]

  # Tell if authentication through request.params is enabled. True by default.
  # It can be set to an array that will enable params authentication only for the
  # given strategies, for example, `config.params_authenticatable = [:database]` will
  # enable it only for database (email + password) authentication.
  # config.params_authenticatable = true

  # Tell if authentication through HTTP Auth is enabled. False by default.
  # It can be set to an array that will enable http authentication only for the
  # given strategies, for example, `config.http_authenticatable = [:database]` will
  # enable it only for database authentication.
  # For API-only applications to support authentication "out-of-the-box", you will likely want to
  # enable this with :database unless you are using a custom strategy.
  # The supported strategies are:
  # :database      = Support basic authentication with authentication key + password
  # config.http_authenticatable = false

  # If 401 status code should be returned for AJAX requests. True by default.
  # config.http_authenticatable_on_xhr = true

  # The realm used in Http Basic Authentication. 'Application' by default.
  # config.http_authentication_realm = 'Application'

  # It will change confirmation, password recovery and other workflows
  # to behave the same regardless if the e-mail provided was right or wrong.
  # Does not affect registerable.
  # config.paranoid = true

  # By default Devise will store the user in session. You can skip storage for
  # particular strategies by setting this option.
  # Notice that if you are skipping storage for all authentication paths, you
  # may want to disable generating routes to Devise's sessions controller by
  # passing skip: :sessions to `devise_for` in your config/routes.rb
  config.skip_session_storage = [:http_auth, :params_auth]

  # By default, Devise cleans up the CSRF token on authentication to
  # avoid CSRF token fixation attacks. This means that, when using AJAX
  # requests for sign in and sign up, you need to get a new CSRF token
  # from the server. You can disable this option at your own risk.
  config.clean_up_csrf_token_on_authentication = true

  # When false, Devise will not attempt to reload routes on eager load.
  # This can reduce the time taken to boot the app but if your application
  # requires the Devise mappings to be loaded during boot time the application
  # won't boot properly.
  # config.reload_routes = true

  # ==> Configuration for :database_authenticatable
  # For bcrypt, this is the cost for hashing the password and defaults to 12. If
  # using other algorithms, it sets how many times you want the password to be hashed.
  # The number of stretches used for generating the hashed password are stored
  # with the hashed password. This allows you to change the stretches without
  # invalidating existing passwords.
  #
  # Limiting the stretches to just one in testing will increase the performance of
  # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
  # a value less than 10 in other environments. Note that, for bcrypt (the default
  # algorithm), the cost increases exponentially with the number of stretches (e.g.
  # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
  config.stretches = Rails.env.test? ? 1 : 12

  # Set up a pepper to generate the hashed password.
  # config.pepper = '15b609ede9b082a53592bb822ce246abac86718598db9d00cc1085067fbd85fd8c022bb5b14685f7216d7091ccacb3cbb2b8ed2e2c11bb9738f012afe5b07092'

  # Send a notification to the original email when the user's email is changed.
  # config.send_email_changed_notification = false

  # Send a notification email when the user's password is changed.
  # config.send_password_change_notification = false

  # ==> Configuration for :confirmable
  # A period that the user is allowed to access the website even without
  # confirming their account. For instance, if set to 2.days, the user will be
  # able to access the website for two days without confirming their account,
  # access will be blocked just in the third day.
  # You can also set it to nil, which will allow the user to access the website
  # without confirming their account.
  # Default is 0.days, meaning the user cannot access the website without
  # confirming their account.
  # config.allow_unconfirmed_access_for = 2.days

  # A period that the user is allowed to confirm their account before their
  # token becomes invalid. For example, if set to 3.days, the user can confirm
  # their account within 3 days after the mail was sent, but on the fourth day
  # their account can't be confirmed with the token any more.
  # Default is nil, meaning there is no restriction on how long a user can take
  # before confirming their account.
  # config.confirm_within = 3.days

  # If true, requires any email changes to be confirmed (exactly the same way as
  # initial account confirmation) to be applied. Requires additional unconfirmed_email
  # db field (see migrations). Until confirmed, new email is stored in
  # unconfirmed_email column, and copied to email column on successful confirmation.
  config.reconfirmable = true

  # Defines which key will be used when confirming an account
  # config.confirmation_keys = [:email]

  # ==> Configuration for :rememberable
  # The time the user will be remembered without asking for credentials again.
  # config.remember_for = 2.weeks

  # Invalidates all the remember me tokens when the user signs out.
  config.expire_all_remember_me_on_sign_out = true

  # If true, extends the user's remember period when remembered via cookie.
  # config.extend_remember_period = false

  # Options to be passed to the created cookie. For instance, you can set
  # secure: true in order to force SSL only cookies.
  # config.rememberable_options = {}

  # ==> Configuration for :validatable
  # Range for password length.
  config.password_length = 6..128

  # Email regex used to validate email formats. It simply asserts that
  # one (and only one) @ exists in the given string. This is mainly
  # to give user feedback and not to assert the e-mail validity.
  config.email_regexp = /\A[^@\s]+@[^@\s]+\z/

  # ==> Configuration for :timeoutable
  # The time you want to timeout the user session without activity. After this
  # time the user will be asked for credentials again. Default is 30 minutes.
  # config.timeout_in = 30.minutes

  # ==> Configuration for :lockable
  # Defines which strategy will be used to lock an account.
  # :failed_attempts = Locks an account after a number of failed attempts to sign in.
  # :none            = No lock strategy. You should handle locking by yourself.
  # config.lock_strategy = :failed_attempts

  # Defines which key will be used when locking and unlocking an account
  # config.unlock_keys = [:email]

  # Defines which strategy will be used to unlock an account.
  # :email = Sends an unlock link to the user email
  # :time  = Re-enables login after a certain amount of time (see :unlock_in below)
  # :both  = Enables both strategies
  # :none  = No unlock strategy. You should handle unlocking by yourself.
  # config.unlock_strategy = :both

  # Number of authentication tries before locking an account if lock_strategy
  # is failed attempts.
  # config.maximum_attempts = 20

  # Time interval to unlock the account if :time is enabled as unlock_strategy.
  # config.unlock_in = 1.hour

  # Warn on the last attempt before the account is locked.
  # config.last_attempt_warning = true

  # ==> Configuration for :recoverable
  #
  # Defines which key will be used when recovering the password for an account
  # config.reset_password_keys = [:email]

  # Time interval you can reset your password with a reset password key.
  # Don't put a too small interval or your users won't have the time to
  # change their passwords.
  config.reset_password_within = 6.hours

  # When set to false, does not sign a user in automatically after their password is
  # reset. Defaults to true, so a user is signed in automatically after a reset.
  # config.sign_in_after_reset_password = true

  # ==> Configuration for :encryptable
  # Allow you to use another hashing or encryption algorithm besides bcrypt (default).
  # You can use :sha1, :sha512 or algorithms from others authentication tools as
  # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20
  # for default behavior) and :restful_authentication_sha1 (then you should set
  # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper).
  #
  # Require the `devise-encryptable` gem when using anything other than bcrypt
  # config.encryptor = :sha512

  # ==> Scopes configuration
  # Turn scoped views on. Before rendering "sessions/new", it will first check for
  # "users/sessions/new". It's turned off by default because it's slower if you
  # are using only default views.
  config.scoped_views = true

  # Configure the default scope given to Warden. By default it's the first
  # devise role declared in your routes (usually :user).
  # config.default_scope = :user

  # Set this configuration to false if you want /users/sign_out to sign out
  # only the current scope. By default, Devise signs out all scopes.
  # config.sign_out_all_scopes = true

  # ==> Navigation configuration
  # Lists the formats that should be treated as navigational. Formats like
  # :html should redirect to the sign in page when the user does not have
  # access, but formats like :xml or :json, should return 401.
  #
  # If you have any extra navigational formats, like :iphone or :mobile, you
  # should add them to the navigational formats lists.
  #
  # The "*/*" below is required to match Internet Explorer requests.
  # config.navigational_formats = ['*/*', :html, :turbo_stream]

  # The default HTTP method used to sign out a resource. Default is :delete.
  config.sign_out_via = :delete

  # ==> OmniAuth
  # Add a new OmniAuth provider. Check the wiki for more information on setting
  # up on your models and hooks.
  # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'

  # ==> Warden configuration
  # If you want to use other strategies, that are not supported by Devise, or
  # change the failure app, you can configure them inside the config.warden block.
  #
  # config.warden do |manager|
  #   manager.intercept_401 = false
  #   manager.default_strategies(scope: :user).unshift :some_external_strategy
  # end

  # ==> Mountable engine configurations
  # When using Devise inside an engine, let's call it `MyEngine`, and this engine
  # is mountable, there are some extra configurations to be taken into account.
  # The following options are available, assuming the engine is mounted as:
  #
  #     mount MyEngine, at: '/my_engine'
  #
  # The router that invoked `devise_for`, in the example above, would be:
  # config.router_name = :my_engine
  #
  # When using OmniAuth, Devise cannot automatically set OmniAuth path,
  # so you need to do it manually. For the users scope, it would be:
  # config.omniauth_path_prefix = '/my_engine/users/auth'

  # ==> Hotwire/Turbo configuration
  # When using Devise with Hotwire/Turbo, the http status for error responses
  # and some redirects must match the following. The default in Devise for existing
  # apps is `200 OK` and `302 Found` respectively, but new apps are generated with
  # these new defaults that match Hotwire/Turbo behavior.
  # Note: These might become the new default in future versions of Devise.
  config.responder.error_status = :unprocessable_entity
  config.responder.redirect_status = :see_other

  # ==> Configuration for :registerable

  # When set to false, does not sign a user in automatically after their password is
  # changed. Defaults to true, so a user is signed in automatically after changing a password.
  # config.sign_in_after_change_password = true
end

production.rb

require "active_support/core_ext/integer/time"

Rails.application.configure do
  config.cache_classes = true
  config.eager_load = true

  # セッションストアの設定
  config.session_store :cookie_store, key: '_tcg_place_session', secure: Rails.env.production?, same_site: :lax

  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  # CSRF保護を有効にする
  config.action_controller.allow_forgery_protection = true
  config.force_ssl = true

  config.public_file_server.enabled = ENV["RAILS_SERVE_STATIC_FILES"].present?

  # Compress CSS using a preprocessor.
  # config.assets.css_compressor = :sass

  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = false

  config.active_storage.service = :local
  config.log_level = :info
  config.log_tags = [ :request_id ]
  config.action_mailer.perform_caching = false
  config.i18n.fallbacks = true
  config.active_support.report_deprecations = false
  config.log_formatter = ::Logger::Formatter.new

  if ENV["RAILS_LOG_TO_STDOUT"].present?
    logger           = ActiveSupport::Logger.new(STDOUT)
    logger.formatter = config.log_formatter
    config.logger    = ActiveSupport::TaggedLogging.new(logger)
  end

  config.active_record.dump_schema_after_migration = false

  # メール設定
  config.action_mailer.default_url_options = { host: 'https://tcgplace-9f88c4df2f96.herokuapp.com' } # 本番環境のURL
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    address:              'smtp.gmail.com',
    port:                 587,
    domain:               'herokuapp.com', # 使用するドメインを指定
    user_name:            ENV['MAILER_SENDER'],
    password:             ENV['MAILER_PASSWORD'],
    authentication:       'plain',
    enable_starttls_auto: true 
  }

end

ログ

2024-09-07T06:30:06.915266+00:00 app[web.1]: I, [2024-09-07T06:30:06.915202 #2]  INFO -- : [09f024b1-d7d2-4699-bf55-9afecc028cfb] Started POST "/users/sign_in" for 106.72.156.98 at 2024-09-07 06:30:06 +0000
2024-09-07T06:30:06.915926+00:00 app[web.1]: I, [2024-09-07T06:30:06.915888 #2]  INFO -- : [09f024b1-d7d2-4699-bf55-9afecc028cfb] Processing by Users::SessionsController#create as HTML
2024-09-07T06:30:06.915955+00:00 app[web.1]: I, [2024-09-07T06:30:06.915937 #2]  INFO -- : [09f024b1-d7d2-4699-bf55-9afecc028cfb]   Parameters: {"authenticity_token"=>"[FILTERED]", "user"=>{"name"=>"kota", "email"=>"kkkk@jp", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"ログイン"}
2024-09-07T06:30:07.144594+00:00 app[web.1]: I, [2024-09-07T06:30:07.144523 #2]  INFO -- : [09f024b1-d7d2-4699-bf55-9afecc028cfb] Redirected to https://tcgplace-9f88c4df2f96.herokuapp.com/users/4
2024-09-07T06:30:07.144657+00:00 app[web.1]: I, [2024-09-07T06:30:07.144635 #2]  INFO -- : [09f024b1-d7d2-4699-bf55-9afecc028cfb] Completed 303 See Other in 229ms (ActiveRecord: 0.6ms | Allocations: 1113)
2024-09-07T06:30:07.329737+00:00 heroku[router]: at=info method=GET path="/users/4" host=tcgplace-9f88c4df2f96.herokuapp.com request_id=22a84a55-b819-4f3a-87de-9af778df791f fwd="106.72.156.98" dyno=web.1 connect=0ms service=4ms status=302 bytes=1164 protocol=https
2024-09-07T06:30:07.145997+00:00 heroku[router]: at=info method=POST path="/users/sign_in" host=tcgplace-9f88c4df2f96.herokuapp.com request_id=09f024b1-d7d2-4699-bf55-9afecc028cfb fwd="106.72.156.98" dyno=web.1 connect=0ms service=231ms status=303 bytes=1188 protocol=https
2024-09-07T06:30:07.326356+00:00 app[web.1]: I, [2024-09-07T06:30:07.326288 #2]  INFO -- : [22a84a55-b819-4f3a-87de-9af778df791f] Started GET "/users/4" for 106.72.156.98 at 2024-09-07 06:30:07 +0000
2024-09-07T06:30:07.326921+00:00 app[web.1]: I, [2024-09-07T06:30:07.326889 #2]  INFO -- : [22a84a55-b819-4f3a-87de-9af778df791f] Processing by UsersController#show as HTML
2024-09-07T06:30:07.326935+00:00 app[web.1]: I, [2024-09-07T06:30:07.326921 #2]  INFO -- : [22a84a55-b819-4f3a-87de-9af778df791f]   Parameters: {"id"=>"4"}
2024-09-07T06:30:07.327933+00:00 app[web.1]: I, [2024-09-07T06:30:07.327906 #2]  INFO -- : [22a84a55-b819-4f3a-87de-9af778df791f] Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms | Allocations: 373)
2024-09-07T06:30:07.519282+00:00 app[web.1]: I, [2024-09-07T06:30:07.519215 #2]  INFO -- : [fb4af5d6-3f1c-4f8c-be51-07797c9c032b] Started GET "/users/sign_in" for 106.72.156.98 at 2024-09-07 06:30:07 +0000
2024-09-07T06:30:07.520019+00:00 app[web.1]: I, [2024-09-07T06:30:07.519976 #2]  INFO -- : [fb4af5d6-3f1c-4f8c-be51-07797c9c032b] Processing by Users::SessionsController#new as HTML
2024-09-07T06:30:07.523342+00:00 app[web.1]: I, [2024-09-07T06:30:07.523301 #2]  INFO -- : [fb4af5d6-3f1c-4f8c-be51-07797c9c032b]   Rendered users/sessions/new.html.erb within layouts/application (Duration: 1.8ms | Allocations: 1055)
2024-09-07T06:30:07.524944+00:00 app[web.1]: I, [2024-09-07T06:30:07.524910 #2]  INFO -- : [fb4af5d6-3f1c-4f8c-be51-07797c9c032b]   Rendered layout layouts/application.html.erb (Duration: 3.4ms | Allocations: 2230)
2024-09-07T06:30:07.525118+00:00 app[web.1]: I, [2024-09-07T06:30:07.525090 #2]  INFO -- : [fb4af5d6-3f1c-4f8c-be51-07797c9c032b] Completed 200 OK in 5ms (Views: 3.8ms | ActiveRecord: 0.0ms | Allocations: 2938)
2024-09-07T06:30:07.526658+00:00 heroku[router]: at=info method=GET path="/users/sign_in" host=tcgplace-9f88c4df2f96.herokuapp.com request_id=fb4af5d6-3f1c-4f8c-be51-07797c9c032b fwd="106.72.156.98" dyno=web.1 connect=0ms service=8ms status=200 bytes=8530 protocol=https
2024-09-07T06:30:07.819883+00:00 heroku[router]: at=info method=GET path="/assets/rails-ujs-1fc700a7beaac60f463364fcba0edbe3921a0d3e0c4b828e7584a7ad7d574e59.js" host=tcgplace-9f88c4df2f96.herokuapp.com request_id=c8663b08-3b26-472d-86c4-05e54e250980 fwd="106.72.156.98" dyno=web.1 connect=0ms service=1ms status=200 bytes=6047 protocol=https
2024-09-07T06:30:07.819646+00:00 heroku[router]: at=info method=GET path="/assets/application-a613f87eebd264ae152faaf633034887c277d39c0d1015bc71d2f0edd4b92cf2.css" host=tcgplace-9f88c4df2f96.herokuapp.com request_id=c30edc0f-dfd2-4aa8-b5bc-5176c5ef40ed fwd="106.72.156.98" dyno=web.1 connect=0ms service=1ms status=200 bytes=1507 protocol=https
2024-09-07T06:30:07.819274+00:00 heroku[router]: at=info method=GET path="/assets/application-6eb1cb21eed39a0f97511588a01d5aa51f0d791d5d346389086ca1fbd5139b3a.js" host=tcgplace-9f88c4df2f96.herokuapp.com request_id=60ea5256-4e54-46f1-b29f-d9d567eff4bb fwd="106.72.156.98" dyno=web.1 connect=0ms service=1ms status=200 bytes=449 protocol=https
2024-09-07T06:30:08.044492+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=tcgplace-9f88c4df2f96.herokuapp.com request_id=c3963089-13c2-48d5-9ace-e84d96e71ab8 fwd="106.72.156.98" dyno=web.1 connect=0ms service=1ms status=200 bytes=207 protocol=https
kenchasonakai commented 2 months ago

UsersController内の処理が原因なのであれば下記のようにcorrect_userを使わずにcurrent_user起点でチェックするようにするとよいのではないでしょうか?

class UsersController < ApplicationController
  before_action :authenticate_user!, except: [:new, :create]

  def show
    @user = User.find_by(id: current_user.id)
  end

  private

  def user_params
    params.require(:user).permit(:name, :email)
  end

end
taiti101112 commented 1 month ago

お疲れさまです。 Userコントローラを以下のように変更して試してみましたが、ログインすることができませんでした。 また、開発環境だとログインできて、本番環境だとログインできないことから本番環境ではログインしたユーザーがリダイレクトした際にセッション等のユーザーに付帯する情報が抜けることでログイン画面に戻されてるのだと考えています。

また、本日はエラーの解決のために以下のことを試しましたが解決には至りませんでした。 このほかに着目すべき点などがあれば教えていただけたら幸いです。 よろしくお願いいたします。

class UsersController < ApplicationController
  before_action :authenticate_user!, except: [:new, :create]
  before_action :set_user, only: [:show, :edit, :update, :destroy]
  before_action :correct_user, only: [:show, :edit, :update, :destroy]

  def show
  end

  private

  def user_params
    params.require(:user).permit(:name, :email)
  end

  def set_user  
    @user = User.find(params[:id])
  end

  def correct_user
    redirect_to(root_path) unless @user && @user == current_user
  end
end
kenchasonakai commented 1 month ago

本番環境でのみ、ログインすることができずログイン画面にリダイレクトされてします。 ログを確認したところログイン自体は成功していて、そこからユーザー詳細ページにリダイレクトされる際に401 Unauthorizedエラーが発生してしまいます。

こちらからログイン自体は成功していてログイン後に意図しないページにリダイレクトされてしまうと解釈していたのですが、ログイン自体出来ていないということでしょうか? 前提が変わったのであればその旨記載してください

また、試したことは何の検証のために試したのか、何を参考に実行したのかを共有していただきますようお願いします

また、ログインとログイン機能が混同されて書かれているのか状況が把握しづらいです 下記状況の整理をお願いします ログイン出来ているのか、出来ていないのか、何のメソッドやコードや仕様によってログイン画面にリダイレクトされているのか等分解して記載おねがします その際、gemの中に該当のコードがあるのであれば公式ドキュメント等から該当の記載を探して軽く調べてみると良いと思います

ログインしたユーザーがリダイレクトした際にセッション等のユーザーに付帯する情報が抜けることでログイン画面に戻されてる

kenchasonakai commented 1 month ago

また、私がしたコメントに対して検証したのかしていないのか、そもそも関係のないものなのか等どのような判断や対処を行ったのか書いていただかないと無視されたみたいに思ってしまいます

taiti101112 commented 1 month ago

ログインできているかについてですが、厳密に言えばログインできておりません。 また、ログインできない事象はherokuにデプロイした本番環境でのみ起こっております 以下に詳細を記載しましたのでご確認いただければ幸いです。 よろしくお願いいたします。

エラーの詳細

まず、ログイン画面でユーザーの情報を入力してログインボタンを押下するとログインに成功し、ユーザー詳細ページ(/user/4)にリダイレクトされます。 しかし、このユーザー詳細ページにリダイレクトされた際にcorrect_user メソッドで認証エラー「401 Unauthorized」が発生し、ログインが取り消され、認証が失敗した際のdeviseのデフォルト機能によりログイン画面にリダイレクトされてしまいます。 そして最終的にはログイン画面にリダイレクトされログインできていない状態で処理が終了しています。 原因としてはログイン後にユーザー詳細ページにリダイレクトされた際にcorrect_user メソッドで認証エラー(401 Unauthorized)が発生しているからになります。 ただ、認証エラーが起きてしまう詳細な原因は現在も特定できておらず、セッションの設定やアクセス権限が問題だと考えております。

エラーが起こる際の処理の流れ

  1. ログイン画面でユーザーの情報を入力してログインボタンを押下

  2. ログイン成功

  3. ユーザー詳細ページにリダイレクト

  4. correct_user メソッドで認証エラー(401 Unauthorized)

  5. 認証されていないor ユーザーが一致しないためログイン成功が取り消される

  6. 認証できなかった際のdeviseのデフォルトの処理によりログイン画面にリダイレクト

試した検証と検証理由

1.ログインボタンを押した際にクッキー(_tcg_place_session)が存在するかの確認

ユーザー詳細ページにリダイレクトした際にクッキーが存在しないことからエラーが発生しているのではと考えたから。

2.herokuのキャッシュをクリア

古いキャッシュを保持していることで認証が通らないのではないかと考えたから。

3.異なるブラウザで試す(chromeではログイン画面にリダイレクトされていたのがsafariでは422エラーになった)

chromeのキャッシュがクリアされていなくてエラーが発生しているのではと考えたから。 結果はsafariの場合は「ActionController::InvalidAuthenticityToken」が発生し、chromeはログイン処理は行えていてユーザー詳細ページにリダイレクトする際にエラーが発生していたのに対して、safariはログイン処理自体が行えていませんでした。 なぜブラウザごとにエラーの内容が異なるのかは現在調査中です。

4.Herokuの環境設定変数(SECRET_KEY_BASE)が存在しているかの確認

SECRET_KEY_BASEはクッキーやCSRFトークンの生成などセキュリティ機能に関わっているものなので存在しないと認証が行えないと考えたから。

5.session_storeのsame_siteをlaxからnoneに変更

クッキーが存在しないことが認証エラーにつながっていると考え、laxからnoenに変更することで全てのリクエストに対してクッキーが送信されるようにするため。

6.デベロッパーツールで「キャッシュの削除とハードの再読み込み」を行う

ブラウザが古いキャッシュを保持していることで認証が通らないのではないかと考えたから。

chromeのログ

2024-09-09T02:29:46.905620+00:00 app[web.1]: I, [2024-09-09T02:29:46.905565 #2]  INFO -- : [85a2ee72-9383-4e0b-b1ab-a0bc4d833c16] Started POST "/users/sign_in" for 106.72.156.98 at 2024-09-09 02:29:46 +0000
2024-09-09T02:29:46.906248+00:00 app[web.1]: I, [2024-09-09T02:29:46.906213 #2]  INFO -- : [85a2ee72-9383-4e0b-b1ab-a0bc4d833c16] Processing by Users::SessionsController#create as HTML
2024-09-09T02:29:46.906275+00:00 app[web.1]: I, [2024-09-09T02:29:46.906258 #2]  INFO -- : [85a2ee72-9383-4e0b-b1ab-a0bc4d833c16]   Parameters: {"authenticity_token"=>"[FILTERED]", "user"=>{"name"=>"kota", "email"=>"kkkk@jp", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"ログイン"}
2024-09-09T02:29:47.137678+00:00 app[web.1]: I, [2024-09-09T02:29:47.137610 #2]  INFO -- : [85a2ee72-9383-4e0b-b1ab-a0bc4d833c16] Redirected to https://tcgplace-9f88c4df2f96.herokuapp.com/users/4
2024-09-09T02:29:47.137733+00:00 app[web.1]: I, [2024-09-09T02:29:47.137714 #2]  INFO -- : [85a2ee72-9383-4e0b-b1ab-a0bc4d833c16] Completed 303 See Other in 231ms (ActiveRecord: 0.6ms | Allocations: 1097)
2024-09-09T02:29:47.138957+00:00 heroku[router]: at=info method=POST path="/users/sign_in" host=tcgplace-9f88c4df2f96.herokuapp.com request_id=85a2ee72-9383-4e0b-b1ab-a0bc4d833c16 fwd="106.72.156.98" dyno=web.1 connect=1ms service=235ms status=303 bytes=1187 protocol=https
2024-09-09T02:29:47.330246+00:00 heroku[router]: at=info method=GET path="/users/4" host=tcgplace-9f88c4df2f96.herokuapp.com request_id=41a3d190-2881-474f-ab5c-94968ed7ee59 fwd="106.72.156.98" dyno=web.1 connect=0ms service=4ms status=302 bytes=1171 protocol=https
2024-09-09T02:29:47.327056+00:00 app[web.1]: I, [2024-09-09T02:29:47.327004 #2]  INFO -- : [41a3d190-2881-474f-ab5c-94968ed7ee59] Started GET "/users/4" for 106.72.156.98 at 2024-09-09 02:29:47 +0000
2024-09-09T02:29:47.327604+00:00 app[web.1]: I, [2024-09-09T02:29:47.327576 #2]  INFO -- : [41a3d190-2881-474f-ab5c-94968ed7ee59] Processing by UsersController#show as HTML
2024-09-09T02:29:47.327622+00:00 app[web.1]: I, [2024-09-09T02:29:47.327608 #2]  INFO -- : [41a3d190-2881-474f-ab5c-94968ed7ee59]   Parameters: {"id"=>"4"}
2024-09-09T02:29:47.328594+00:00 app[web.1]: I, [2024-09-09T02:29:47.328567 #2]  INFO -- : [41a3d190-2881-474f-ab5c-94968ed7ee59] Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms | Allocations: 373)
2024-09-09T02:29:47.517925+00:00 app[web.1]: I, [2024-09-09T02:29:47.517867 #2]  INFO -- : [dd1b5aa6-4e95-45c4-94cd-78cdebae34d1] Started GET "/users/sign_in" for 106.72.156.98 at 2024-09-09 02:29:47 +0000
2024-09-09T02:29:47.518605+00:00 app[web.1]: I, [2024-09-09T02:29:47.518564 #2]  INFO -- : [dd1b5aa6-4e95-45c4-94cd-78cdebae34d1] Processing by Users::SessionsController#new as HTML
2024-09-09T02:29:47.521410+00:00 app[web.1]: I, [2024-09-09T02:29:47.521344 #2]  INFO -- : [dd1b5aa6-4e95-45c4-94cd-78cdebae34d1]   Rendered users/sessions/new.html.erb within layouts/application (Duration: 1.3ms | Allocations: 1055)
2024-09-09T02:29:47.522594+00:00 app[web.1]: I, [2024-09-09T02:29:47.522550 #2]  INFO -- : [dd1b5aa6-4e95-45c4-94cd-78cdebae34d1]   Rendered layout layouts/application.html.erb (Duration: 2.5ms | Allocations: 2229)
2024-09-09T02:29:47.522747+00:00 app[web.1]: I, [2024-09-09T02:29:47.522724 #2]  INFO -- : [dd1b5aa6-4e95-45c4-94cd-78cdebae34d1] Completed 200 OK in 4ms (Views: 3.0ms | ActiveRecord: 0.0ms | Allocations: 2930)
2024-09-09T02:29:47.524238+00:00 heroku[router]: at=info method=GET path="/users/sign_in" host=tcgplace-9f88c4df2f96.herokuapp.com request_id=dd1b5aa6-4e95-45c4-94cd-78cdebae34d1 fwd="106.72.156.98" dyno=web.1 connect=1ms service=7ms status=200 bytes=8533 protocol=https

safariのログ


2024-09-09T04:56:41.298563+00:00 heroku[router]: at=info method=POST path="/users/sign_in" host=tcgplace-9f88c4df2f96.herokuapp.com request_id=2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc fwd="106.72.156.98" dyno=web.1 connect=0ms service=3ms status=422 bytes=1960 protocol=https
2024-09-09T04:56:41.295698+00:00 app[web.1]: I, [2024-09-09T04:56:41.295632 #2]  INFO -- : [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] Started POST "/users/sign_in" for 106.72.156.98 at 2024-09-09 04:56:41 +0000
2024-09-09T04:56:41.296300+00:00 app[web.1]: I, [2024-09-09T04:56:41.296265 #2]  INFO -- : [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] Processing by Users::SessionsController#create as HTML
2024-09-09T04:56:41.296326+00:00 app[web.1]: I, [2024-09-09T04:56:41.296303 #2]  INFO -- : [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc]   Parameters: {"authenticity_token"=>"[FILTERED]", "user"=>{"name"=>"kota", "email"=>"kkkk@jp", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"ログイン"}
2024-09-09T04:56:41.296828+00:00 app[web.1]: W, [2024-09-09T04:56:41.296799 #2]  WARN -- : [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] Can't verify CSRF token authenticity.
2024-09-09T04:56:41.297009+00:00 app[web.1]: I, [2024-09-09T04:56:41.296984 #2]  INFO -- : [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms | Allocations: 280)
2024-09-09T04:56:41.297593+00:00 app[web.1]: F, [2024-09-09T04:56:41.297561 #2] FATAL -- : [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc]
2024-09-09T04:56:41.297593+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] ActionController::InvalidAuthenticityToken (Can't verify CSRF token authenticity.):
2024-09-09T04:56:41.297594+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc]
2024-09-09T04:56:41.297596+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_controller/metal/request_forgery_protection.rb:253:in `handle_unverified_request'
2024-09-09T04:56:41.297597+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_controller/metal/request_forgery_protection.rb:286:in `handle_unverified_request'
2024-09-09T04:56:41.297597+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] devise (4.9.4) lib/devise/controllers/helpers.rb:257:in `handle_unverified_request'
2024-09-09T04:56:41.297597+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_controller/metal/request_forgery_protection.rb:275:in `verify_authenticity_token'
2024-09-09T04:56:41.297597+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] activesupport (7.0.8.1) lib/active_support/callbacks.rb:400:in `block in make_lambda'
2024-09-09T04:56:41.297597+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] activesupport (7.0.8.1) lib/active_support/callbacks.rb:199:in `block (2 levels) in halting'
2024-09-09T04:56:41.297598+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/abstract_controller/callbacks.rb:34:in `block (2 levels) in <module:Callbacks>'
2024-09-09T04:56:41.297598+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] activesupport (7.0.8.1) lib/active_support/callbacks.rb:200:in `block in halting'
2024-09-09T04:56:41.297598+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] activesupport (7.0.8.1) lib/active_support/callbacks.rb:595:in `block in invoke_before'
2024-09-09T04:56:41.297600+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] activesupport (7.0.8.1) lib/active_support/callbacks.rb:595:in `each'
2024-09-09T04:56:41.297600+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] activesupport (7.0.8.1) lib/active_support/callbacks.rb:595:in `invoke_before'
2024-09-09T04:56:41.297600+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] activesupport (7.0.8.1) lib/active_support/callbacks.rb:116:in `block in run_callbacks'
2024-09-09T04:56:41.297600+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] activesupport (7.0.8.1) lib/active_support/callbacks.rb:138:in `run_callbacks'
2024-09-09T04:56:41.297600+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/abstract_controller/callbacks.rb:233:in `process_action'
2024-09-09T04:56:41.297600+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_controller/metal/rescue.rb:23:in `process_action'
2024-09-09T04:56:41.297600+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_controller/metal/instrumentation.rb:67:in `block in process_action'
2024-09-09T04:56:41.297600+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] activesupport (7.0.8.1) lib/active_support/notifications.rb:206:in `block in instrument'
2024-09-09T04:56:41.297601+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] activesupport (7.0.8.1) lib/active_support/notifications/instrumenter.rb:24:in `instrument'
2024-09-09T04:56:41.297601+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] activesupport (7.0.8.1) lib/active_support/notifications.rb:206:in `instrument'
2024-09-09T04:56:41.297601+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_controller/metal/instrumentation.rb:66:in `process_action'
2024-09-09T04:56:41.297601+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_controller/metal/params_wrapper.rb:259:in `process_action'
2024-09-09T04:56:41.297601+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] activerecord (7.0.8.1) lib/active_record/railties/controller_runtime.rb:27:in `process_action'
2024-09-09T04:56:41.297601+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/abstract_controller/base.rb:151:in `process'
2024-09-09T04:56:41.297601+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionview (7.0.8.1) lib/action_view/rendering.rb:39:in `process'
2024-09-09T04:56:41.297602+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_controller/metal.rb:188:in `dispatch'
2024-09-09T04:56:41.297602+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_controller/metal.rb:251:in `dispatch'
2024-09-09T04:56:41.297602+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/routing/route_set.rb:49:in `dispatch'
2024-09-09T04:56:41.297602+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/routing/route_set.rb:32:in `serve'
2024-09-09T04:56:41.297602+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/routing/mapper.rb:18:in `block in <class:Constraints>'
2024-09-09T04:56:41.297602+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/routing/mapper.rb:48:in `serve'
2024-09-09T04:56:41.297604+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/journey/router.rb:50:in `block in serve'
2024-09-09T04:56:41.297604+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/journey/router.rb:32:in `each'
2024-09-09T04:56:41.297604+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/journey/router.rb:32:in `serve'
2024-09-09T04:56:41.297604+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/routing/route_set.rb:852:in `call'
2024-09-09T04:56:41.297604+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] warden (1.2.9) lib/warden/manager.rb:36:in `block in call'
2024-09-09T04:56:41.297604+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] warden (1.2.9) lib/warden/manager.rb:34:in `catch'
2024-09-09T04:56:41.297604+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] warden (1.2.9) lib/warden/manager.rb:34:in `call'
2024-09-09T04:56:41.297605+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] rack (2.2.9) lib/rack/tempfile_reaper.rb:15:in `call'
2024-09-09T04:56:41.297605+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] rack (2.2.9) lib/rack/etag.rb:27:in `call'
2024-09-09T04:56:41.297605+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] rack (2.2.9) lib/rack/conditional_get.rb:40:in `call'
2024-09-09T04:56:41.297605+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] rack (2.2.9) lib/rack/head.rb:12:in `call'
2024-09-09T04:56:41.297605+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/http/permissions_policy.rb:38:in `call'
2024-09-09T04:56:41.297605+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/http/content_security_policy.rb:36:in `call'
2024-09-09T04:56:41.297605+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] rack (2.2.9) lib/rack/session/abstract/id.rb:266:in `context'
2024-09-09T04:56:41.297605+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] rack (2.2.9) lib/rack/session/abstract/id.rb:260:in `call'
2024-09-09T04:56:41.297606+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/middleware/cookies.rb:704:in `call'
2024-09-09T04:56:41.297606+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/middleware/callbacks.rb:27:in `block in call'
2024-09-09T04:56:41.297606+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] activesupport (7.0.8.1) lib/active_support/callbacks.rb:99:in `run_callbacks'
2024-09-09T04:56:41.297606+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/middleware/callbacks.rb:26:in `call'
2024-09-09T04:56:41.297606+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/middleware/debug_exceptions.rb:28:in `call'
2024-09-09T04:56:41.297606+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/middleware/show_exceptions.rb:29:in `call'
2024-09-09T04:56:41.297606+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] railties (7.0.8.1) lib/rails/rack/logger.rb:40:in `call_app'
2024-09-09T04:56:41.297606+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] railties (7.0.8.1) lib/rails/rack/logger.rb:25:in `block in call'
2024-09-09T04:56:41.297606+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] activesupport (7.0.8.1) lib/active_support/tagged_logging.rb:99:in `block in tagged'
2024-09-09T04:56:41.297606+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] activesupport (7.0.8.1) lib/active_support/tagged_logging.rb:37:in `tagged'
2024-09-09T04:56:41.297606+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] activesupport (7.0.8.1) lib/active_support/tagged_logging.rb:99:in `tagged'
2024-09-09T04:56:41.297607+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] railties (7.0.8.1) lib/rails/rack/logger.rb:25:in `call'
2024-09-09T04:56:41.297607+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/middleware/remote_ip.rb:93:in `call'
2024-09-09T04:56:41.297607+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] request_store (1.7.0) lib/request_store/middleware.rb:19:in `call'
2024-09-09T04:56:41.297607+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/middleware/request_id.rb:26:in `call'
2024-09-09T04:56:41.297607+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] rack (2.2.9) lib/rack/method_override.rb:24:in `call'
2024-09-09T04:56:41.297607+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] rack (2.2.9) lib/rack/runtime.rb:22:in `call'
2024-09-09T04:56:41.297607+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/middleware/executor.rb:14:in `call'
2024-09-09T04:56:41.297607+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/middleware/static.rb:23:in `call'
2024-09-09T04:56:41.297607+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] rack (2.2.9) lib/rack/sendfile.rb:110:in `call'
2024-09-09T04:56:41.297608+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/middleware/ssl.rb:77:in `call'
2024-09-09T04:56:41.297608+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] actionpack (7.0.8.1) lib/action_dispatch/middleware/host_authorization.rb:131:in `call'
2024-09-09T04:56:41.297608+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] railties (7.0.8.1) lib/rails/engine.rb:530:in `call'
2024-09-09T04:56:41.297610+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] puma (5.6.8) lib/puma/configuration.rb:252:in `call'
2024-09-09T04:56:41.297610+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] puma (5.6.8) lib/puma/request.rb:77:in `block in handle_request'
2024-09-09T04:56:41.297611+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] puma (5.6.8) lib/puma/thread_pool.rb:340:in `with_force_shutdown'
2024-09-09T04:56:41.297611+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] puma (5.6.8) lib/puma/request.rb:76:in `handle_request'
2024-09-09T04:56:41.297611+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] puma (5.6.8) lib/puma/server.rb:443:in `process_client'
2024-09-09T04:56:41.297611+00:00 app[web.1]: [2a7b6fe8-b49f-48bd-a7a6-dbf32a7b02bc] puma (5.6.8) lib/puma/thread_pool.rb:147:in `block in spawn_thread'
taiti101112 commented 1 month ago

以前教えていただいたことに対する検証結果の報告をしておらず大変申し訳ございませんでした。 教えていただいたことを参考にして、Userコントローラーのshowアクションにおけるユーザーの取得を「@user = User.find_by(id: current_user.id)」から「 @user = current_user」にして検証を行いました。 検証しようと思った理由についてですがcurrent_userはdeviseのメソッドのためfind_byメソッドよりも認証が通りやすくなるのではないかと考えたからになります。 また結果についてですがログに変化はなく同じエラーが出ております。

変更前

class UsersController < ApplicationController
  before_action :authenticate_user!, except: [:new, :create]
  before_action :set_user, only: [:show, :edit, :update, :destroy]
  before_action :correct_user, only: [:show, :edit, :update, :destroy]

  def show
    @user = User.find_by(id: current_user.id)
  end

  private

  def user_params
    params.require(:user).permit(:name, :email)
  end

  def set_user  
    @user = User.find(params[:id])
  end

  def correct_user
    # `@user` が存在し、かつ現在のユーザーと一致するかを確認
    redirect_to(root_path) unless @user && @user == current_user
  end
end

変更後

class UsersController < ApplicationController
  before_action :authenticate_user!, except: [:new, :create]

  def show
    @user = current_user
  end

  private

  def user_params
    params.require(:user).permit(:name, :email)
  end
end
kenchasonakai commented 1 month ago

ご回答いただいている下記のエラーが起きる流れですが、別途ご回答いただいているコントローラーの変更の検証でcorrect_userを使わない形で検証いただいているのでcorrect_user メソッドで認証エラー(401 Unauthorized)のところの推測が違っていることが検証できているかなと思いますがいかがですか?また、検証する際にアレンジを加える場合はアレンジ前のものも検証すると良い思いますよ 元のコードではcurrent_userの値がnilの場合は例外が発生するようになっているので別の検証も出来たかなと思います https://github.com/taiti101112/portfolio/issues/149#issuecomment-2337192235

エラーが起こる際の処理の流れ

ログイン画面でユーザーの情報を入力してログインボタンを押下

ログイン成功

ユーザー詳細ページにリダイレクト

correct_user メソッドで認証エラー(401 Unauthorized)

認証されていないor ユーザーが一致しないためログイン成功が取り消される

認証できなかった際のdeviseのデフォルトの処理によりログイン画面にリダイレクト

taiti101112 commented 1 month ago

おっしゃる通り、current_userメソッドを使用しているのとしていないパターンで検証しておりますのでcurrent_userが認証されないためにログインできないというのは誤りでした。 そのため、他に原因として考えられるのはセッション関連の情報がユーザーに不足しているからだと思います。 つきましてはこのような場合にどのようにして原因の調査を行えば良いのかなどを教えていただけますでしょうか?

また、検証に関してですがUserコントローラーの変更前とあとでそれぞれ検証をしており、ログは変更前・変更後ともに同じものでした。

よろしくお願いいたします。

kenchasonakai commented 1 month ago

まずはエラーが起こる際の処理の流れの推測が違っていたことに気づけたと思うので改めて、どこでエラーが起きているのかを改めて突き止めてください

エラー対応の際にはどこの何でエラーが起きているのかを明確にすることが1番大切です

その上でloginが出来ていないのであれば何を根拠にログインが出来ていないのかを示してください deviseを使っている場合はセッションが存在してなければログインが出来ておらずcurrent_userの値がnilになったり、ログインしているかどうかを判定するSorceryのlogged_inメソッドのようなものがあればviewページに埋め込んで値を確認したりすると出来るでしょう

上記の検証でLogin出来ていないということに対して根拠を示せてはじめてログイン出来ない原因の調査に入れます

開発環境ではログインできて、本番環境でのみログイン出来ないのであればまずは自分が実装した設定に何か問題がないか、参照した公式以外のドキュメントで扱っているgemのバージョンが違いすぎていないか、deviseのGitHubのissueに自分と同じような状況の人が書いたissueがないかを探していくと良いかなと思います

taiti101112 commented 1 month ago

ご返信ありがとうございます。 承知致しました。