How to structure authenticated routes when using Devise?

前端 未结 2 1550
庸人自扰
庸人自扰 2021-01-16 02:18

In my question How to have root view when user is not logged in rails? max answered that we can use authenticated to make routes available only when someone is

相关标签:
2条回答
  • 2021-01-16 02:52

    Here is the simple way to structure authenticated and unauthenticated routes.

    In app/controllers/application_controller.rb, add "before_action :authenticate_user!".

    My app/controllers/application_controller.rb file:

    class ApplicationController < ActionController::Base
    
    protect_from_forgery with: :exception
    
    before_action :authenticate_user!
    end
    

    My config/routes.rb:

    Rails.application.routes.draw do
      devise_for :users
      root "home#index"
      devise_for :users, controllers: {
                           :sessions => "users/sessions",
                           :registrations => "users/registrations" }
      authenticated :user do
          resources :students
      end
    
    
    
    unauthenticated :user do
      #Some route
      end
    
    end
    
    0 讨论(0)
  • 2021-01-16 02:59

    If you want to limit access to subjects you should do it on the controller layer - not in the routes. Using before_action :authenticate_user! will give a 401 Unauthorized response and redirect to the sign in.

    class ApplicationController
      # secure by default
      before_action :authenticate_user!, unless: :devise_controller?
    end
    
    class SubjectsController < ApplicationController
      # whitelist actions that should not require authentication
      skip_before_action :authenticate_user!, only: [:show, :index]
      # ...
    end
    

    Rails.application.routes.draw do
      devise_for :users
    
      resources :subjects do 
        resources :students
      end
    
      root "home#index"
    end
    

    Using the authenticated and unauthenticated route helpers are useful when you want the have different responses for the same route for authenticated and unauthenticated users but is not how you should structure your application.

    If you simply use authenticated in your routes unauthenticated users will get a 404 Not Found response instead of being prompted to sign in. Which is not helpful.

    Also resources :students, only: [:get] does not generate any routes at all. The onlyoption is for limiting the actions (show, index, edit, update ...) not the HTTP method. Use rake routes to see the routes in your app.

    0 讨论(0)
提交回复
热议问题