Restrict devise routes
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.
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?.