백로그
0할 일
0진행 중
0리뷰
0완료 (전체)
2[Auth-1] 인증 코어 교체 + Devise 제거 + DB 마이그레이션
## 목표 Devise를 제거하고 session[:user_id] 기반 직접 인증으로 전환. Gem/설정 제거 + DB 마이그레이션까지 완료. ## 작업 순서 (반드시 이 순서대로) ### Phase 1: 코어 교체 1. **ApplicationController 수정** (`app/controllers/application_controller.rb`) - `before_action :authenticate_user!` 유지 (자체 구현으로 대체) - private 메서드 추가: ```ruby def current_user @current_user ||= User.find_by(id: session[:user_id]) end helper_method :current_user def user_signed_in? current_user.present? end helper_method :user_signed_in? def authenticate_user! unless user_signed_in? redirect_to login_path, alert: "로그인이 필요합니다." end end ``` - `layout_by_resource` 메서드와 `layout :layout_by_resource` 제거 (devise_controller? 참조 없앰) 2. **SessionsController 생성** (`app/controllers/sessions_controller.rb`) ```ruby class SessionsController < ApplicationController skip_before_action :authenticate_user!, only: [:new] layout "devise" def new redirect_to root_path if user_signed_in? end def destroy reset_session redirect_to login_path, notice: "로그아웃되었습니다." end end ``` 3. **OmniauthController 수정** (`app/controllers/omniauth_controller.rb` - 새 위치) - `app/controllers/users/omniauth_callbacks_controller.rb`를 `app/controllers/omniauth_controller.rb`로 이동 - Devise 상속 제거: ```ruby class OmniauthController < ApplicationController skip_before_action :authenticate_user! def google_oauth2 handle_auth("Google") end def kakao handle_auth("Kakao") end def failure redirect_to login_path, alert: "로그인에 실패했습니다. 다시 시도해주세요." end private def handle_auth(kind) @user = User.from_omniauth(request.env["omniauth.auth"]) if @user.persisted? session[:user_id] = @user.id redirect_to root_path, notice: "#{kind}로 로그인되었습니다." else redirect_to login_path, alert: "#{kind} 로그인에 실패했습니다." end end end ``` 4. **라우트 수정** (`config/routes.rb`) - `devise_for :users, ...` 제거 - 자체 라우트 추가: ```ruby # 인증 get "login", to: "sessions#new", as: :login delete "logout", to: "sessions#destroy", as: :logout # OmniAuth 콜백 get "auth/:provider/callback", to: "omniauth#google_oauth2", constraints: { provider: "google_oauth2" } get "auth/:provider/callback", to: "omniauth#kakao", constraints: { provider: "kakao" } post "auth/:provider/callback", to: "omniauth#google_oauth2", constraints: { provider: "google_oauth2" } post "auth/:provider/callback", to: "omniauth#kakao", constraints: { provider: "kakao" } get "auth/failure", to: "omniauth#failure" ``` 5. **User 모델 수정** (`app/models/user.rb`) - `devise :database_authenticatable, :omniauthable, ...` 줄 전체 삭제 - `from_omniauth`에서 `Devise.friendly_token` 제거 (password 할당 불필요): ```ruby def self.from_omniauth(auth) where(provider: auth.provider, provider_id: auth.uid).first_or_create do |user| user.email = auth.info.email user.nickname = auth.info.name || auth.info.email.split("@").first user.profile_image = auth.info.image end end ``` 6. **뷰 이동** - `app/views/devise/sessions/new.html.erb` → `app/views/sessions/new.html.erb` - 뷰 내용에서 Devise 경로 수정: - `user_google_oauth2_omniauth_authorize_path` → `/auth/google_oauth2` - `user_kakao_omniauth_authorize_path` → `/auth/kakao` - `new_user_session_path` → `login_path` 7. **사이드바 수정** - 로그아웃 링크 경로 확인 - `destroy_user_session_path` → `logout_path` - method: :delete 유지 ### Phase 2: OmniAuth 설정 이전 8. **OmniAuth 이니셜라이저 생성** (`config/initializers/omniauth.rb`) ```ruby Rails.application.config.middleware.use OmniAuth::Builder do provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"], scope: "email,profile" require_relative "../../lib/omniauth/strategies/kakao" provider :kakao, ENV["KAKAO_CLIENT_ID"], ENV["KAKAO_CLIENT_SECRET"] end OmniAuth.config.allowed_request_methods = [:post, :get] OmniAuth.config.silence_get_warning = true ``` ### Phase 3: Devise 제거 9. **Gemfile에서 devise 제거** + `bundle install` 10. **config/initializers/devise.rb 삭제** 11. **app/views/devise/ 디렉토리 삭제** (views 이동 완료 후) 12. **app/controllers/users/ 디렉토리 삭제** (controller 이동 완료 후) ### Phase 4: DB 마이그레이션 13. **마이그레이션 생성** - Devise 전용 컬럼 제거: ```ruby class RemoveDeviseColumnsFromUsers < ActiveRecord::Migration[8.1] def change remove_index :users, :reset_password_token remove_column :users, :encrypted_password, :string remove_column :users, :reset_password_token, :string remove_column :users, :reset_password_sent_at, :datetime remove_column :users, :remember_created_at, :datetime end end ``` 14. `bin/rails db:migrate` 실행 ## 주의사항 - UUID PK 사용 (`before_create :set_uuid` in ApplicationRecord) - ERB 멀티라인 주석 안에 ERB 태그 금지 (SystemStackError) - 모든 변경 후 서버가 기동 가능한지 확인 - test/ 디렉토리는 auth-test-dev가 담당 - 건드리지 말 것 - `bundle install` 실행 후 Gemfile.lock 업데이트 확인
[Auth-2] 테스트 수정 - Devise 헬퍼 → 자체 sign_in 헬퍼
## 목표 Devise::Test::IntegrationHelpers를 제거하고 session[:user_id] 기반 자체 테스트 헬퍼로 전환. 전체 테스트 통과 확인. ## 작업 내용 ### 1. test_helper.rb 수정 - `include Devise::Test::IntegrationHelpers` 제거 - 자체 sign_in 헬퍼 추가: ```ruby class ActionDispatch::IntegrationTest private def sign_in(user) post "/auth/google_oauth2/callback", env: { "omniauth.auth" => OmniAuth::AuthHash.new( provider: user.provider || "google_oauth2", uid: user.provider_id || "test_uid_#{user.id}", info: { email: user.email, name: user.nickname, image: user.profile_image } ) } end end ``` **주의**: 위 sign_in 구현이 실제 OmniAuth 콜백 라우트와 맞지 않을 수 있습니다. auth-app-dev가 라우트를 변경하므로, 실제 라우트 파일(`config/routes.rb`)을 먼저 확인하세요. 대안적 접근 (더 단순): ```ruby def sign_in(user) # OmniAuth 테스트 모드가 아닌 직접 세션 설정 # Integration 테스트에서는 직접 세션 설정이 어려우므로 OmniAuth mock 사용 OmniAuth.config.test_mode = true OmniAuth.config.mock_auth[:google_oauth2] = OmniAuth::AuthHash.new( provider: "google_oauth2", uid: user.provider_id || "test_uid", info: { email: user.email, name: user.nickname, image: user.profile_image } ) get "/auth/google_oauth2/callback" end ``` 또는 가장 단순한 방식: ```ruby def sign_in(user) post login_path, params: {}, env: { "rack.session" => { user_id: user.id } } end ``` **실제 구현 시**: auth-app-dev의 코어 교체 결과(routes, controllers)를 확인한 후 가장 적합한 방식을 선택하세요. ### 2. 전체 테스트 파일 확인 - `test/` 디렉토리의 모든 테스트 파일에서 `sign_in` 호출이 새 헬퍼로 작동하는지 확인 - Devise 관련 참조가 남아있지 않은지 확인 (grep으로 검색) ### 3. OmniAuth 테스트 모드 설정 - test_helper.rb에 OmniAuth 테스트 모드 설정 추가: ```ruby OmniAuth.config.test_mode = true ``` ### 4. 전체 테스트 실행 - `bin/rails test` 실행 - 모든 테스트 통과 확인 (430+ tests, 0 failures 기대) ## 주의사항 - auth-app-dev가 app/ 코드를 변경하므로, 그 변경이 완료된 후에 테스트를 실행해야 합니다 - 하지만 test_helper.rb 수정과 테스트 분석은 먼저 시작 가능 - test/ 디렉토리만 수정 - app/ 코드는 건드리지 말 것 - `parallelize(workers: 1)` 유지 필수 (SQLite) - fixture UUID PK → `.to_s` 비교 필요한 곳 있음 - 통합 테스트에서 RecordNotFound → `assert_response :not_found` 패턴 사용