ryusei-tadokoro / Today_fashion

0 stars 0 forks source link

ログイン関係のエラー #116

Closed ryusei-tadokoro closed 4 months ago

ryusei-tadokoro commented 5 months ago

お疲れ様です。 メールアドレスによるログインをすると、CSRF tokenによるエラーが発生しております。 また、Heroku環境でもLineログインを行うと404エラーが発生しているため、ログイン自体ができない状況となっています。 (ユーザー登録は可能です)

メールアドレスによるログイン

ActionController::InvalidAuthenticityToken (Can't verify CSRF token authenticity.):

actionpack (7.1.2) lib/action_controller/metal/request_forgery_protection.rb:293:in `handle_unverified_request'
actionpack (7.1.2) lib/action_controller/metal/request_forgery_protection.rb:388:in `handle_unverified_request'
devise (4.9.3) lib/devise/controllers/helpers.rb:255:in `handle_unverified_request'
actionpack (7.1.2) lib/action_controller/metal/request_forgery_protection.rb:377:in `verify_authenticity_token'
activesupport (7.1.2) lib/active_support/callbacks.rb:403:in `block in make_lambda'
activesupport (7.1.2) lib/active_support/callbacks.rb:202:in `block (2 levels) in halting'
actionpack (7.1.2) lib/abstract_controller/callbacks.rb:34:in `block (2 levels) in <module:Callbacks>'
activesupport (7.1.2) lib/active_support/callbacks.rb:203:in `block in halting'
activesupport (7.1.2) lib/active_support/callbacks.rb:598:in `block in invoke_before'
activesupport (7.1.2) lib/active_support/callbacks.rb:598:in `each'
activesupport (7.1.2) lib/active_support/callbacks.rb:598:in `invoke_before'
activesupport (7.1.2) lib/active_support/callbacks.rb:119:in `block in run_callbacks'
actiontext (7.1.2) lib/action_text/rendering.rb:23:in `with_renderer'
actiontext (7.1.2) lib/action_text/engine.rb:69:in `block (4 levels) in <class:Engine>'
activesupport (7.1.2) lib/active_support/callbacks.rb:130:in `instance_exec'
activesupport (7.1.2) lib/active_support/callbacks.rb:130:in `block in run_callbacks'
activesupport (7.1.2) lib/active_support/callbacks.rb:141:in `run_callbacks'
actionpack (7.1.2) lib/abstract_controller/callbacks.rb:258:in `process_action'
actionpack (7.1.2) lib/action_controller/metal/rescue.rb:25:in `process_action'
actionpack (7.1.2) lib/action_controller/metal/instrumentation.rb:74:in `block in process_action'
activesupport (7.1.2) lib/active_support/notifications.rb:206:in `block in instrument'
activesupport (7.1.2) lib/active_support/notifications/instrumenter.rb:58:in `instrument'
activesupport (7.1.2) lib/active_support/notifications.rb:206:in `instrument'
actionpack (7.1.2) lib/action_controller/metal/instrumentation.rb:73:in `process_action'
actionpack (7.1.2) lib/action_controller/metal/params_wrapper.rb:261:in `process_action'
activerecord (7.1.2) lib/active_record/railties/controller_runtime.rb:32:in `process_action'
actionpack (7.1.2) lib/abstract_controller/base.rb:160:in `process'
actionview (7.1.2) lib/action_view/rendering.rb:40:in `process'
actionpack (7.1.2) lib/action_controller/metal.rb:227:in `dispatch'
actionpack (7.1.2) lib/action_controller/metal.rb:309:in `dispatch'
actionpack (7.1.2) lib/action_dispatch/routing/route_set.rb:49:in `dispatch'
actionpack (7.1.2) lib/action_dispatch/routing/route_set.rb:32:in `serve'
actionpack (7.1.2) lib/action_dispatch/routing/mapper.rb:21:in `block in <class:Constraints>'
actionpack (7.1.2) lib/action_dispatch/routing/mapper.rb:51:in `serve'
actionpack (7.1.2) lib/action_dispatch/journey/router.rb:51:in `block in serve'
actionpack (7.1.2) lib/action_dispatch/journey/router.rb:131:in `block in find_routes'
actionpack (7.1.2) lib/action_dispatch/journey/router.rb:124:in `each'
actionpack (7.1.2) lib/action_dispatch/journey/router.rb:124:in `find_routes'
actionpack (7.1.2) lib/action_dispatch/journey/router.rb:32:in `serve'
actionpack (7.1.2) lib/action_dispatch/routing/route_set.rb:882:in `call'
omniauth (1.9.2) lib/omniauth/strategy.rb:192:in `call!'
omniauth (1.9.2) lib/omniauth/strategy.rb:169:in `call'
warden (1.2.9) lib/warden/manager.rb:36:in `block in call'
warden (1.2.9) lib/warden/manager.rb:34:in `catch'
warden (1.2.9) lib/warden/manager.rb:34:in `call'
rack (2.2.8) lib/rack/tempfile_reaper.rb:15:in `call'
rack (2.2.8) lib/rack/etag.rb:27:in `call'
rack (2.2.8) lib/rack/conditional_get.rb:40:in `call'
rack (2.2.8) lib/rack/head.rb:12:in `call'
actionpack (7.1.2) lib/action_dispatch/http/permissions_policy.rb:36:in `call'
actionpack (7.1.2) lib/action_dispatch/http/content_security_policy.rb:33:in `call'
rack (2.2.8) lib/rack/session/abstract/id.rb:266:in `context'
rack (2.2.8) lib/rack/session/abstract/id.rb:260:in `call'
actionpack (7.1.2) lib/action_dispatch/middleware/cookies.rb:689:in `call'
activerecord (7.1.2) lib/active_record/migration.rb:654:in `call'
actionpack (7.1.2) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
activesupport (7.1.2) lib/active_support/callbacks.rb:101:in `run_callbacks'
actionpack (7.1.2) lib/action_dispatch/middleware/callbacks.rb:28:in `call'
actionpack (7.1.2) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (7.1.2) lib/action_dispatch/middleware/actionable_exceptions.rb:16:in `call'
actionpack (7.1.2) lib/action_dispatch/middleware/debug_exceptions.rb:29:in `call'
web-console (4.2.1) lib/web_console/middleware.rb:132:in `call_app'
web-console (4.2.1) lib/web_console/middleware.rb:28:in `block in call'
web-console (4.2.1) lib/web_console/middleware.rb:17:in `catch'
web-console (4.2.1) lib/web_console/middleware.rb:17:in `call'
actionpack (7.1.2) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'
railties (7.1.2) lib/rails/rack/logger.rb:37:in `call_app'
railties (7.1.2) lib/rails/rack/logger.rb:24:in `block in call'
activesupport (7.1.2) lib/active_support/tagged_logging.rb:135:in `block in tagged'
activesupport (7.1.2) lib/active_support/tagged_logging.rb:39:in `tagged'
activesupport (7.1.2) lib/active_support/tagged_logging.rb:135:in `tagged'
activesupport (7.1.2) lib/active_support/broadcast_logger.rb:240:in `method_missing'
railties (7.1.2) lib/rails/rack/logger.rb:24:in `call'
sprockets-rails (3.4.2) lib/sprockets/rails/quiet_assets.rb:13:in `call'
actionpack (7.1.2) lib/action_dispatch/middleware/remote_ip.rb:92:in `call'
actionpack (7.1.2) lib/action_dispatch/middleware/request_id.rb:28:in `call'
rack (2.2.8) lib/rack/method_override.rb:24:in `call'
rack (2.2.8) lib/rack/runtime.rb:22:in `call'
activesupport (7.1.2) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call'
actionpack (7.1.2) lib/action_dispatch/middleware/server_timing.rb:59:in `block in call'
actionpack (7.1.2) lib/action_dispatch/middleware/server_timing.rb:24:in `collect_events'
actionpack (7.1.2) lib/action_dispatch/middleware/server_timing.rb:58:in `call'
actionpack (7.1.2) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (7.1.2) lib/action_dispatch/middleware/static.rb:25:in `call'
rack (2.2.8) lib/rack/sendfile.rb:110:in `call'
actionpack (7.1.2) lib/action_dispatch/middleware/host_authorization.rb:141:in `call'
railties (7.1.2) lib/rails/engine.rb:529:in `call'
puma (6.4.0) lib/puma/configuration.rb:272:in `call'
puma (6.4.0) lib/puma/request.rb:100:in `block in handle_request'
puma (6.4.0) lib/puma/thread_pool.rb:378:in `with_force_shutdown'
puma (6.4.0) lib/puma/request.rb:99:in `handle_request'
puma (6.4.0) lib/puma/server.rb:443:in `process_client'
puma (6.4.0) lib/puma/server.rb:241:in `block in run'
puma (6.4.0) lib/puma/thread_pool.rb:155:in `block in spawn_thread'

Lineログイン

024-06-23T11:59:55.783488+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=www.todayfashion.jp request_id=3c7dfb9b-df8a-4e1f-962a-6f456b496948 fwd="61.87.59.118" dyno=web.1 connect=1ms service=1ms status=304 bytes=131 protocol=https
2024-06-23T12:00:01.847895+00:00 heroku[router]: at=info method=GET path="/users/sign_in" host=www.todayfashion.jp request_id=cf2aed36-d053-446f-b893-4944c9153ad9 fwd="61.87.59.118" dyno=web.1 connect=1ms service=9ms status=200 bytes=4673 protocol=https
2024-06-23T12:00:01.839967+00:00 app[web.1]: I, [2024-06-23T12:00:01.839867 #15]  INFO -- : [cf2aed36-d053-446f-b893-4944c9153ad9] Started GET "/users/sign_in" for 61.87.59.118 at 2024-06-23 12:00:01 +0000
2024-06-23T12:00:01.840822+00:00 app[web.1]: I, [2024-06-23T12:00:01.840764 #15]  INFO -- : [cf2aed36-d053-446f-b893-4944c9153ad9] Processing by Users::SessionsController#new as HTML
2024-06-23T12:00:01.846643+00:00 app[web.1]: I, [2024-06-23T12:00:01.846575 #15]  INFO -- : [cf2aed36-d053-446f-b893-4944c9153ad9]   Rendered layout layouts/application.html.erb (Duration: 4.6ms | Allocations: 1471)
2024-06-23T12:00:01.846769+00:00 app[web.1]: I, [2024-06-23T12:00:01.846746 #15]  INFO -- : [cf2aed36-d053-446f-b893-4944c9153ad9] Completed 200 OK in 6ms (Views: 5.0ms | ActiveRecord: 0.0ms | Allocations: 2104)
2024-06-23T12:00:07.776424+00:00 heroku[router]: at=info method=GET path="/users/auth/line" host=www.todayfashion.jp request_id=a572393d-f94c-4a71-bbc4-c16812f80564 fwd="61.87.59.118" dyno=web.1 connect=1ms service=3ms status=404 bytes=477 protocol=https
2024-06-23T12:00:07.773876+00:00 app[web.1]: I, [2024-06-23T12:00:07.773742 #15]  INFO -- : [a572393d-f94c-4a71-bbc4-c16812f80564] Started GET "/users/auth/line" for 61.87.59.118 at 2024-06-23 12:00:07 +0000
2024-06-23T12:00:07.774817+00:00 app[web.1]: I, [2024-06-23T12:00:07.774749 #15]  INFO -- : [a572393d-f94c-4a71-bbc4-c16812f80564] Processing by Users::OmniauthCallbacksController#passthru as HTML
2024-06-23T12:00:07.775402+00:00 app[web.1]: I, [2024-06-23T12:00:07.775349 #15]  INFO -- : [a572393d-f94c-4a71-bbc4-c16812f80564] Completed 404 Not Found in 0ms (Views: 0.3ms | ActiveRecord: 0.0ms | Allocations: 126)
2024-06-23T12:00:07.974246+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=www.todayfashion.jp request_id=4776cd8a-5ef9-4579-b186-dff9e479f332 fwd="61.87.59.118" dyno=web.1 connect=2ms service=2ms status=304 bytes=131 protocol=https

ちなみにrails consoleで各種キーは表示されますが、その後にnilが表示されます。

ryuseitadokoro@ryuseinoMacBook-Air today_fashion % rails console

Loading development environment (Rails 7.1.2)
irb(main):001> puts Rails.application.credentials.line[:key]
20・・・・・
=> nil
irb(main):002> puts Rails.application.credentials.line[:secret]
928・・・・・
=> nil

以下2つの記事を参考に行いましたが、エラー改善されませんでした https://midorimici.com/posts/rails-api-csrf https://qiita.com/hackhaku/items/88269643c675fd4ca975

お忙しいところ恐縮ですが、ご教授のほどよろしくお願いいたします。

Tsuchiya2 commented 5 months ago

ローカルでは問題なく挙動する感じでしょうか?

JavaScript部分の問題かもしれませんね。(Webpackerでは上手く動いており、デプロイも出来ていたのなら、esbuidlは使用せず、そちらで進めるのも検討してみてください🙇‍♂)

↑esbuildは入っているけれど、RailsのデフォルトでJavaScriptを使用している部分が上手く動作していないため、POSTメソッドにならずGETメソッドとなってしまっているとかかもしれません。

参考:https://railsguides.jp/working_with_javascript_in_rails.html 参考:https://github.com/rails/jsbundling-rails

リポジトリのGemfileを見たらRails7系のデフォルトのimport mapsを使用しているようなので、そちらではなくjsbundling-railsとesbuild or webpacker を使用する形にする必要がありそうな仮説を立てました。一度参考記事とコードをご確認いただけますでしょうか。

ryusei-tadokoro commented 5 months ago

ローカルでも問題が発生しております。 MVPリリース時ではwebpackを使用していませんでした。 (今回MVPリリースに向けてトップページを作成した際に、無料のテンプレートをダウンロードをし、その時にwebpackを使用した流れです)

一度import mapsではなくjsbundling-railsとesbuild を使用してみたいと思います。

ryusei-tadokoro commented 5 months ago

importmapsを削除後jsbundling-railsとesbuildで行った結果、ローカル環境でも本番環境でも無事にログインすることができました!ありがとうございます。 しかし、Lineログインについてはいまだにログインができません。

2024-06-24T22:08:55.698643+00:00 heroku[router]: at=info method=GET path="/users/auth/line" host=www.todayfashion.jp request_id=75e6274b-7137-4af8-8605-16b5de2f36ee fwd="61.87.59.118" dyno=web.1 connect=0ms service=3ms status=404 bytes=477 protocol=https
2024-06-24T22:08:55.696054+00:00 app[web.1]: I, [2024-06-24T22:08:55.695945 #8]  INFO -- : [75e6274b-7137-4af8-8605-16b5de2f36ee] Started GET "/users/auth/line" for 61.87.59.118 at 2024-06-24 22:08:55 +0000
2024-06-24T22:08:55.697017+00:00 app[web.1]: I, [2024-06-24T22:08:55.696939 #8]  INFO -- : [75e6274b-7137-4af8-8605-16b5de2f36ee] Processing by Users::OmniauthCallbacksController#passthru as HTML
2024-06-24T22:08:55.697805+00:00 app[web.1]: I, [2024-06-24T22:08:55.697743 #8]  INFO -- : [75e6274b-7137-4af8-8605-16b5de2f36ee] Completed 404 Not Found in 1ms (Views: 0.4ms | ActiveRecord: 0.0ms | Allocations: 267)

Image from Gyazo

Lineログインに関連しているコードを記述させていただきます。 Gemfile

# Gemfile

source 'https://rubygems.org'

ruby '3.2.2'

gem 'rails', '~> 7.1.2'
gem 'sprockets-rails'
gem 'puma', '>= 5.0'
gem 'turbo-rails'
gem 'stimulus-rails'
gem 'jbuilder'
gem 'tzinfo-data', platforms: %i[windows jruby]
gem 'bootsnap', require: false

group :development, :test do
  gem 'debug', platforms: %i[mri windows]
  gem 'rubocop', require: false
  gem 'rubocop-rails', require: false
  gem 'sqlite3', '~> 1.4'
end

group :production do
  gem 'pg', '~> 1.5'
end

group :development do
  gem 'web-console'
end

group :test do
  gem 'capybara'
  gem 'selenium-webdriver'
  gem 'simplecov', require: false
end

gem 'active_hash'
gem 'ancestry'
gem 'bootstrap'
gem 'carrierwave'
gem 'devise'
gem 'dotenv-rails'
gem 'enum_help'
gem 'font-awesome-sass'
gem 'google-cloud-vision'
gem 'httparty'
gem 'jquery-rails'
gem 'line-bot-api'
gem 'mini_magick'
gem 'omniauth-line'
gem 'omniauth-rails_csrf_protection'
gem 'rails-i18n'
gem 'sassc-rails'
gem 'whenever', require: false
gem 'dockerfile-rails', '>= 1.6', group: :development
gem 'fog-aws'
gem 'aws-sdk-s3', require: false
gem 'memory_profiler'
gem 'pundit'
gem 'jsbundling-rails'

config/intializers/devise.rb

# frozen_string_literal: true

Devise.setup do |config|
  config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com'
  require 'devise/orm/active_record'
  config.case_insensitive_keys = [:email]
  config.strip_whitespace_keys = [:email]
  config.skip_session_storage = [:http_auth]
  config.clean_up_csrf_token_on_authentication = false
  config.stretches = Rails.env.test? ? 1 : 12
  config.reconfirmable = true
  config.expire_all_remember_me_on_sign_out = true
  config.password_length = 6..128
  config.email_regexp = /\A[^@\s]+@[^@\s]+\z/
  config.reset_password_within = 6.hours
  config.navigational_formats = ['*/*', :html, :turbo_stream]
  config.sign_out_via = [:get, :delete]
  config.responder.error_status = :unprocessable_entity
  config.responder.redirect_status = :see_other
  config.omniauth :line, Rails.application.credentials.line[:key], Rails.application.credentials.line[:secret], scope: 'profile openid email'
end

app/controllers/users/omniauth_callbacks_controller.rb

# frozen_string_literal: true

module Users
  class OmniauthCallbacksController < Devise::OmniauthCallbacksController
    # GET|POST /users/auth/line/callback
    def line
      @user = User.from_omniauth(request.env['omniauth.auth'])

      if @user.persisted?
        sign_in_and_redirect @user, event: :authentication
        set_flash_message(:notice, :success, kind: 'LINE') if is_navigational_format?
      else
        session['devise.line_data'] = request.env['omniauth.auth'].except('extra')
        redirect_to new_user_registration_url
      end
    end

    def failure
      redirect_to root_path
    end
  end
end

app/controllers/omniauth_callbacks_controller.rb

# OmniauthCallbacksController manages the callbacks from various omniauth providers.
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def line
    basic_action
  end

  private

  def basic_action
    @omniauth = request.env['omniauth.auth']

    return if @omniauth.blank?

    @profile = find_or_initialize_user
    set_user_info if @profile.new_record?
    @profile.save! if @profile.changed?

    sign_in_and_redirect
  end

  def find_or_initialize_user
    User.find_or_initialize_by(provider: @omniauth['provider'], uid: @omniauth['uid'])
  end

  def set_user_info
    email = @omniauth['info']['email'].presence || fake_email
    @profile.assign_attributes(email:, name: @omniauth['info']['name'], password: Devise.friendly_token[0, 20])
  end

  def fake_email
    "#{@omniauth['uid']}-#{@omniauth['provider']}@example.com"
  end

  def sign_in_and_redirect
    sign_in(:user, @profile)
    flash[:notice] = I18n.t('devise.omniauth_callbacks.success', kind: 'LINE')
    redirect_to root_path
  end

  def line_client_id
    Rails.application.credentials.dig(:line, :client_id)
  end

  def line_client_secret
    Rails.application.credentials.dig(:line, :client_secret)
  end
end

app/models/user.rb

# frozen_string_literal: true

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable,
         :omniauthable, omniauth_providers: %i[line]

  extend ActiveHash::Associations::ActiveRecordExtensions
  belongs_to :prefecture
  belongs_to :second_prefecture, class_name: 'Prefecture', optional: true
  belongs_to :constitution
  has_many :closets, dependent: :destroy

  validates :password, presence: true, if: :password_required?

  mount_uploader :image, ImageUploader

  def default_image
    ActionController::Base.helpers.asset_path('default_image.png')
  end

  def social_profile(provider)
    social_profiles.select { |sp| sp.provider == provider.to_s }.first
  end

  def set_values(omniauth)
    return if provider.to_s != omniauth['provider'].to_s || uid != omniauth['uid']

    credentials = omniauth['credentials']
    info = omniauth['info']

    credentials['refresh_token']
    credentials['secret']
    credentials.to_json
    info['name']
  end

  def set_values_by_raw_info(raw_info)
    self.raw_info = raw_info.to_json
    save!
  end

  def password_required?
    # 新しいパスワードが存在する場合にのみバリデーションを適用する
    new_record? || password.present? || password_confirmation.present?
  end

  def self.from_omniauth(auth)
    user = where(provider: auth.provider, uid: auth.uid).first_or_initialize
    user.email = auth.info.email || "#{auth.uid}-#{auth.provider}@example.com"
    user.password = Devise.friendly_token[0, 20] if user.new_record?
    user.save
    user
  end
end

config/routes.rb

Rails.application.routes.draw do
  resources :closets do
    get 'subcategories_for_category/:category_id', on: :collection, to: 'closets#subcategories_for_category'
  end
  post '/callback' => 'linebot#callback'

  devise_for :users, controllers: {
    registrations: 'users/registrations',
    sessions: 'users/sessions',
    passwords: 'users/passwords',
    confirmations: 'users/confirmations',
    omniauth_callbacks: 'users/omniauth_callbacks'
  }

  authenticated :user do
    root 'weather#index', as: :authenticated_root
  end

  root 'home#index'

  get 'home/index'
  get 'weather', to: 'weather#index', as: :weather
  get 'weather/show', to: 'weather#show', as: :show_weather
  get 'privacy_policy', to: 'static_pages#privacy_policy', as: :privacy_policy
  get 'terms_of_service', to: 'static_pages#terms_of_service', as: :terms_of_service
  post 'vision_api/upload', to: 'vision_api#upload'

  namespace :public do
    resources :contacts, only: %i[new create index] do
      collection do
        post 'confirm'
        post 'back'
        get 'done'
      end
    end
  end
end

app/views/shared/_links.html.erb

<%- if controller_name != 'sessions' %>
  <%= link_to t('devise_links.log_in'), new_session_path(resource_name) %><br />
<% end %>

<%- if devise_mapping.registerable? && controller_name != 'registrations' %>
  <%= link_to t('devise_links.sign_up'), new_registration_path(resource_name) %><br />
<% end %>

<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %>
  <%= link_to t('devise_links.forgot_password'), new_password_path(resource_name) %><br />
<% end %>

<%- if devise_mapping.confirmable? && controller_name != 'confirmations' %>
  <%= link_to t('devise_links.confirmation_instructions'), new_confirmation_path(resource_name) %><br />
<% end %>

<%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %>
  <%= link_to t('devise_links.unlock_instructions'), new_unlock_path(resource_name) %><br />
<% end %>

<% if devise_mapping.omniauthable? %>
  <% resource_class.omniauth_providers.each do |provider| %>
    <% if provider == :line %>
      <%= link_to omniauth_authorize_path(resource_name, provider), class: 'btn btn-outline-success btn-block', data: { turbo: false } do %>
        <i class="fab fa-line"></i> Lineでログイン
      <% end %>
    <% else %>
      <%= link_to omniauth_authorize_path(resource_name, provider), class: 'btn btn-outline-primary btn-block', data: { turbo: false } do %>
        <%= t('devise_links.sign_in_with', provider: OmniAuth::Utils.camelize(provider)) %>
      <% end %><br />
    <% end %>
  <% end %>
<% end %>

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

Tsuchiya2 commented 5 months ago

ローカル環境でも本番環境でも無事にログインすることができました!ありがとうございます。

良かったです!

Lineログインについてはいまだにログインができません。

こちらに関してですが、Heroku(本番環境)で、Rails.application.credentialの値が期待しているものになっているか、LINE側の設定は本番環境のものに対応しているかなどを確認してみたりはされたでしょうか。もしまだでしたらその辺りから確認してみましょう。

ryusei-tadokoro commented 5 months ago
EDITOR="code --wait" bin/rails credentials:edit

上記コードで確認したところ

line:
  key: 
  secret: 
  channel_secret: 
  channel_token: 
  user_id: 

この5つをLine Developersで確認しましたが、違いはありませんでした。 herokuではrails_master_keyの値でおこなっています。

Image from Gyazo

MVPリリース時にはLine loginは実装しており、エラーが発生するまでコードは変えてません。 1点気になる点としては、https://www.todayfashion.jp/users/auth/line 現在lineログインボタンを押すと上記のURLになりますが、 本来ならhttps://www.todayfashion.jp/users/auth/line/callback のような気がしますが違いますか?

Tsuchiya2 commented 5 months ago

共有ありがとうございます。

MVPリリース時にはLine loginは実装しており、エラーが発生するまでコードは変えてません。 1点気になる点としては、https://www.todayfashion.jp/users/auth/line 現在lineログインボタンを押すと上記のURLになりますが、 本来ならhttps://www.todayfashion.jp/users/auth/line/callback のような気がしますが違いますか?

エラーが発生するまでコードは変えていないということなので、エラーが発生する前に戻せば問題なく動くということでしょうか?Herokuのログだったり、LINE側のログ?を確認して、どこに問題があるかの特定から始めると良いかと思いました。

EDITOR="code --wait" bin/rails credentials:edit

↑で値を確認したとありましたが、ローカルでの操作で合っていますでしょうか?Herokuのサーバー上でRailsコンソールを立ち上げて、Rails.application.credentials を実行して期待している値が返ってくるかをチェックしてみると、問題箇所の可能性を潰せるかと思うので試してみてください。(credentialsを使って環境変数設定している場合)

ryusei-tadokoro commented 5 months ago

ご教授ありがとうございます

ryuseitadokoro@ryuseinoMacBook-Air today_fashion % heroku run rails console                       

 ›   Warning: heroku update available from 8.10.0 to 8.11.5.
Running rails console on ⬢ todayfashion... up, run.7251 (Basic)
Loading production environment (Rails 7.1.2)
irb(main):001> puts Rails.application.credentials.line[:key]
(irb):1:in `<main>': undefined local variable or method `:key' for main:Object (NameError)
irb(main):002> puts Rails.application.credentials.line[:key]
200・・・・
=> nil
irb(main):003> puts Rails.application.credentials.line[:secret]
928・・・・
=> nil

ryuseitadokoro@ryuseinoMacBook-Air today_fashion % heroku config:get RAILS_MASTER_KEY

 ›   Warning: heroku update available from 8.10.0 to 8.11.5.
9b・・・・・

キーの値とnilが返ってきます。 masterkeyはnilはなく数値のみ返ってきます。

2024-06-25T11:11:20.600109+00:00 app[web.1]: I, [2024-06-25T11:11:20.600005 #6]  INFO -- : [6d76b3c4-c2e1-4de6-9cde-0589fa705d78] Started GET "/users/sign_in" for 61.87.59.118 at 2024-06-25 11:11:20 +0000
2024-06-25T11:11:20.633671+00:00 app[web.1]: I, [2024-06-25T11:11:20.633588 #6]  INFO -- : [6d76b3c4-c2e1-4de6-9cde-0589fa705d78] Processing by Users::SessionsController#new as HTML
2024-06-25T11:11:21.106360+00:00 heroku[router]: at=info method=GET path="/users/sign_in" host=www.todayfashion.jp request_id=6d76b3c4-c2e1-4de6-9cde-0589fa705d78 fwd="61.87.59.118" dyno=web.1 connect=1ms service=507ms status=200 bytes=5160 protocol=https
2024-06-25T11:11:21.105044+00:00 app[web.1]: I, [2024-06-25T11:11:21.104936 #6]  INFO -- : [6d76b3c4-c2e1-4de6-9cde-0589fa705d78]   Rendered layout layouts/application.html.erb (Duration: 380.7ms | Allocations: 1578)
2024-06-25T11:11:21.105198+00:00 app[web.1]: I, [2024-06-25T11:11:21.105169 #6]  INFO -- : [6d76b3c4-c2e1-4de6-9cde-0589fa705d78] Completed 200 OK in 471ms (Views: 381.2ms | ActiveRecord: 0.0ms | Allocations: 2040)
2024-06-25T11:11:24.044818+00:00 app[web.1]: I, [2024-06-25T11:11:24.044678 #14]  INFO -- : [da44ead8-6e88-4298-a33a-c65ca1c5e3a7] Started GET "/users/auth/line" for 61.87.59.118 at 2024-06-25 11:11:24 +0000
2024-06-25T11:11:24.076550+00:00 app[web.1]: I, [2024-06-25T11:11:24.076423 #14]  INFO -- : [da44ead8-6e88-4298-a33a-c65ca1c5e3a7] Processing by Users::OmniauthCallbacksController#passthru as HTML
2024-06-25T11:11:24.093978+00:00 app[web.1]: I, [2024-06-25T11:11:24.077014 #14]  INFO -- : [da44ead8-6e88-4298-a33a-c65ca1c5e3a7] Completed 404 Not Found in 0ms (Views: 0.2ms | ActiveRecord: 0.0ms | Allocations: 126)
2024-06-25T11:11:24.102937+00:00 heroku[router]: at=info method=GET path="/users/auth/line" host=www.todayfashion.jp request_id=da44ead8-6e88-4298-a33a-c65ca1c5e3a7 fwd="61.87.59.118" dyno=web.1 connect=0ms service=155ms status=404 bytes=477 protocol=https

herokuのlogではこのような状況です。

lineのログについては確認方法が分かりませんでした。

Tsuchiya2 commented 5 months ago

Rails.application.credentials.line[:secret] Rails.application.credentials.line[:secret]

上記がheroku上ではnilになっていますが、ローカルは期待している値が返ってきますでしょうか。ローカルは正常に動いているとしたら、ローカルと本番環境との差分が生じている箇所を1つ1つ、仮説・検証・分析のサイクルを回して特定&修正のトライ&エラーを回してみましょう。

heroku[router]: at=info method=GET path="/users/auth/line" host=www.todayfashion.jp request_id=da44ead8-6e88-4298-a33a-c65ca1c5e3a7 fwd="61.87.59.118" dyno=web.1 connect=0ms service=155ms status=404 bytes=477 protocol=https

statusコードが404と返ってきているようですので、404ステータスコードはどういったときに出るコードなのかを調べて、どうして404が返ってきてしまうのかを考え、仮説・検証・分析のサイクルを回して特定&修正のトライ&エラーを回してみましょう。

ryusei-tadokoro commented 5 months ago

ローカル環境では値が返ってきます

ryuseitadokoro@ryuseinoMacBook-Air today_fashion % rails c
Loading development environment (Rails 7.1.2)
irb(main):001> Rails.application.credentials.line[:secret]
=> "928・・・"
irb(main):003> Rails.application.credentials.line[:key]
=> "200・・・"

heroku上でmasterkeyが渡せていないか確認したところ Masterkeyも正しく返ってきます

ryuseitadokoro@ryuseinoMacBook-Air today_fashion % heroku config:get RAILS_MASTER_KEY

 ›   Warning: heroku update available from 8.10.0 to 8.11.5.
9bb・・・
ryuseitadokoro@ryuseinoMacBook-Air today_fashion % heroku config

 ›   Warning: heroku update available from 8.10.0 to 8.11.5.
=== todayfashion Config Vars

DATABASE_URL:                   postgres://cjqfwtttuofcmf:c0dda37ddb2c63385b830caca8fc752f99723f4951c1713af73d0c63e558d85d@ec2-44-214-98-128.compute-1.amazonaws.com:5432/dddudmaie02qsc
GOOGLE_APPLICATION_CREDENTIALS: {
  "type": "service_account",
  "project_id": "todayfashion",
  "private_key_id": "08e・・・",
  "private_key": "-----BEGIN PRIVATE KEY-----\nMII・・・",
  "client_email": "todayfashion@todayfashion.iam.gserviceaccount.com",
  "client_id": "113・・・",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/todayfashion%40todayfashion.iam.gserviceaccount.com",
  "universe_domain": "googleapis.com"
}
LANG:                           en_US.UTF-8
RACK_ENV:                       production
RAILS_ENV:                      production
RAILS_LOG_TO_STDOUT:            enabled
RAILS_MASTER_KEY:               9bb・・・
RAILS_SERVE_STATIC_FILES:       enabled
SECRET_KEY_BASE:                c79・・・

もう一度heroku上で.credentialsを確認してみましたが、値とnilが返ってきます。

ryuseitadokoro@ryuseinoMacBook-Air today_fashion % heroku run rails console

 ›   Warning: heroku update available from 8.10.0 to 8.11.5.
Running rails console on ⬢ todayfashion... up, run.3841 (Basic)
Loading production environment (Rails 7.1.2)
irb(main):001> puts Rails.application.credentials.line[:key]
200・・・
=> nil
irb(main):002> puts Rails.application.credentials.line[:secret]
928・・・
=> nil