Ask A Question

Notifications

You’re not receiving notifications from this thread.

Restrict devise routes

Christian Herber Santos asked in General

Hi,

How can I restrict access to the devise sign_up route to logged in users only?

Controller:

# frozen_string_literal: true

class Users::RegistrationsController < Devise::RegistrationsController
  # before_action :configure_sign_up_params, only: [:create]
  # before_action :configure_account_update_params, only: [:update]
  before_action :authenticate_user!

  # GET /resource/sign_up
  def new
    super
  end

  # POST /resource
  def create
    super
  end

But doesn't work.

Reply

To restrict access to the Devise sign-up route for only logged-in users, you can override the new action in the Users::RegistrationsController. Here's an example of how you can modify the controller to achieve this:

ruby
class Users::RegistrationsController < Devise::RegistrationsController
before_action :authenticate_user!, except: [:new]

def new
if user_signed_in?
redirect_to root_path, alert: "You are already signed in."
else
super
end
end

# ...
end
In this updated code, the before_action is used to authenticate the user for all actions except the new action. Within the new action, you can check if the user is already signed in using user_signed_in?.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 87,400+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.