IT

Devise 경로를 제거하여 가입하려면 어떻게해야합니까?

lottoking 2020. 6. 16. 07:58
반응형

Devise 경로를 제거하여 가입하려면 어떻게해야합니까?


Rails 3 앱에서 Devise를 사용하고 있지만이 경우 기존 사용자가 사용자를 생성해야합니다.

이 때문에 나는 원한다 :

  • 사용자가 가입 할 수있는 경로제거 하려면 .
  • 사용자 가 가입 한 후에도 프로필을 편집 (이메일 주소 및 비밀번호 변경) 할 수 있도록 하려면

어떻게해야합니까?

현재 다음을 전에 배치 하여이 경로를 효과적으로 제거하고 있습니다 devise_for :users.

match 'users/sign_up' => redirect('/404.html')

그것은 효과가 있지만 더 좋은 방법이 있다고 생각합니다.

최신 정보

Benoit Garret이 말했듯이, 제 경우 가장 좋은 해결책은 등록 경로 작성을 건너 뛰고 실제로 원하는 것을 작성하는 것입니다.

그렇게하기 위해 먼저을 실행 rake routes한 다음 출력을 사용하여 원하는 것을 다시 작성했습니다. 최종 결과는 다음과 같습니다.

devise_for :users, :skip => [:registrations] 
as :user do
  get 'users/edit' => 'devise/registrations#edit', :as => 'edit_user_registration'
  put 'users' => 'devise/registrations#update', :as => 'user_registration'
end

참고 :

  • 나는 여전히 :registerableUser모델에
  • devise/registrations 이메일 및 비밀번호 업데이트 처리
  • 다른 사용자 속성 (권한 등) 업데이트는 다른 컨트롤러에서 처리합니다.

실제 답변 :

기본 Devise 경로의 경로를 제거하십시오. 즉 :

devise_for :users, path_names: {
  sign_up: ''
}

이 작업도 시도했지만 고안 된 Google 그룹의 스레드 로 인해 정말 깨끗한 솔루션을 찾지 못했습니다.

José Valim (Devise 관리자)을 인용하겠습니다.

간단한 옵션은 없습니다. 패치를 제공하거나 : skip => : registerable을 사용하고 원하는 경로 만 추가 할 수 있습니다.

원래 질문은 :

Rails에서 특정 경로 (삭제 경로)를 제거하는 좋은 방법이 있습니까?


당신은 당신의 모델에서 이것을 할 수 있습니다

# typical devise setup in User.rb
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable

그것을 다음으로 변경하십시오 :

devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable

심볼 :registerable이 제거 되었음을 확인

그게 다야, 다른 것은 필요하지 않습니다. 등록 페이지에 대한 모든 경로와 링크도 마술처럼 제거됩니다.


비슷한 문제 createnew에 대한 devise_invitable 경로 를 제거하려고했습니다 .

전에:

 devise_for :users

갈퀴 길

accept_user_invitation GET    /users/invitation/accept(.:format)           devise/invitations#edit
       user_invitation POST   /users/invitation(.:format)                  devise/invitations#create
   new_user_invitation GET    /users/invitation/new(.:format)              devise/invitations#new
                       PUT    /users/invitation(.:format)                  devise/invitations#update

devise_for :users , :skip => 'invitation'
devise_scope :user do
  get "/users/invitation/accept", :to => "devise/invitations#edit",   :as => 'accept_user_invitation'
  put "/users/invitation",        :to => "devise/invitations#update", :as => nil
end

갈퀴 길

accept_user_invitation GET    /users/invitation/accept(.:format)                 devise/invitations#edit
                       PUT    /users/invitation(.:format)                        devise/invitations#update

참고 1 고안 범위 https://github.com/plataformatec/devise#configuring-routes

참고 2 devise_invitable에 적용하고 있지만 고안 가능한 기능으로 작동합니다.

중요 사항 : devise_scope이 켜져있는 것을 볼 사용 하지 사용자 ? 맞습니다, 이것을 조심하십시오! 이 문제를 일으키는 많은 고통을 유발할 수 있습니다.

Started GET "/users/invitation/accept?invitation_token=xxxxxxx" for 127.0.0.1 
Processing by Devise::InvitationsController#edit as HTML
  Parameters: {"invitation_token"=>"6Fy5CgFHtjWfjsCyr3hG"}
 [Devise] Could not find devise mapping for path "/users/invitation/accept?  invitation_token=6Fy5CgFHtjWfjsCyr3hG".
This may happen for two reasons:

1) You forgot to wrap your route inside the scope block. For example:

  devise_scope :user do
     match "/some/route" => "some_devise_controller"
  end

 2) You are testing a Devise controller bypassing the router.
   If so, you can explicitly tell Devise which mapping to use:

    @request.env["devise.mapping"] = Devise.mappings[:user]

나는 게시물 과 비슷한 다른 게시물을 발견 하고 @ chrisnicola가 준 답변을 공유하고 싶었습니다. 포스트에서 그들은 생산하는 동안 사용자 가입을 차단하려고했습니다.

등록 컨트롤러를 수정할 수도 있습니다. 다음과 같은 것을 사용할 수 있습니다.

에서 "응용 프로그램 / 컨트롤러 / registrations_controller.rb"

class RegistrationsController < Devise::RegistrationsController
  def new
    flash[:info] = 'Registrations are not open.'
    redirect_to root_path
  end

  def create
    flash[:info] = 'Registrations are not open.'
    redirect_to root_path
  end
end

이것은 devise의 컨트롤러를 무시하고 대신 위의 방법을 사용합니다. 그들은 누군가가 어떻게 든 sign_up 페이지에 그것을 만들도록 플래시 메시지를 추가했습니다. 또한 원하는 경로로 경로 재 지정을 변경할 수 있어야합니다.

또한 "config / routes.rb"에서 다음을 추가 할 수 있습니다.

devise_for :users, :controllers => { :registrations => "registrations" }

이렇게 남겨두면 표준 고안을 사용하여 프로필을 편집 할 수 있습니다. 원하는 경우 다음을 포함하여 여전히 프로필 편집 옵션을 무시할 수 있습니다

  def update
  end

에서 "응용 프로그램 / 컨트롤러 / registrations_controller.rb"


"devise_for"앞에 배치하여 "devise_scope"를 대체 할 수 있습니다.

devise_scope :user do
  get "/users/sign_up",  :to => "sites#index"
end

devise_for :users

이것이 가장 좋은 방법인지 확실하지 않지만 현재 내 솔루션은 로그인 페이지로 다시 리디렉션되기 때문입니다.


이것은 오래된 질문이지만 최근에 같은 문제를 해결했으며 다음보다 훨씬 우아한 솔루션을 생각해 냈습니다.

devise_for :users, :skip => [:registrations] 
as :user do
  get 'users/edit' => 'devise/registrations#edit', :as => 'edit_user_registration'
  put 'users' => 'devise/registrations#update', :as => 'user_registration'
end

그리고 cancel_user_registration과도하게 상세하게하지 않고 명명 된 경로 (예 :)의 기본 이름을 제공합니다 .

devise_for :users, skip: [:registrations]

# Recreates the Devise registrations routes
# They act on a singular user (the signed in user)
# Add the actions you want in 'only:'
resource :users,
    only: [:edit, :update, :destroy],
    controller: 'devise/registrations',
    as: :user_registration do
  get 'cancel'
end

rake routes 기본 고안 모듈로 출력 :

                  Prefix Verb   URI Pattern                    Controller#Action
        new_user_session GET    /users/sign_in(.:format)       devise/sessions#new
            user_session POST   /users/sign_in(.:format)       devise/sessions#create
    destroy_user_session DELETE /users/sign_out(.:format)      devise/sessions#destroy
           user_password POST   /users/password(.:format)      devise/passwords#create
       new_user_password GET    /users/password/new(.:format)  devise/passwords#new
      edit_user_password GET    /users/password/edit(.:format) devise/passwords#edit
                         PATCH  /users/password(.:format)      devise/passwords#update
                         PUT    /users/password(.:format)      devise/passwords#update
cancel_user_registration GET    /users/cancel(.:format)        devise/registrations#cancel
  edit_user_registration GET    /users/edit(.:format)          devise/registrations#edit
       user_registration PATCH  /users(.:format)               devise/registrations#update
                         PUT    /users(.:format)               devise/registrations#update
                         DELETE /users(.:format)               devise/registrations#destroy

routes.rb에서이 작업을 수행하십시오.

devise_for :users, :controllers => {:registrations => "registrations"}, :skip => [:registrations]
  as :user do
    get 'users/edit' => 'devise/registrations#edit', :as => 'edit_user_registration'
    put 'users' => 'devise/registrations#update', :as => 'user_registration'
end

  devise_scope :user do
    get "/sign_in",  :to => "devise/sessions#new"
    get "/sign_up",  :to => "devise/registrations#new"
  end

로그인 페이지에서 오류를 수정하여 수정하십시오. app / views / devise / shared / _links.erb에서이 변경을 수행하십시오.

<% if  request.path != "/sign_in" %>
    <%- if devise_mapping.registerable? && controller_name != 'registrations' %>
        <%= link_to "Sign up", new_registration_path(resource_name) %><br />
    <% end -%>
<% end %>

@max의 답변을 좋아 했지만 사용하려고 할 때 devise_mappingnil 때문에 오류가 발생했습니다 .

I modified his solution slightly to one that seems to address the issue. It required wrapping the call to resource inside devise_scope.

devise_for :users, skip: [:registrations]

devise_scope :user do
  resource :users,
           only: [:edit, :update, :destroy],
           controller: 'devise/registrations',
           as: :user_registration do
    get 'cancel'
  end
end

Note that devise_scope expects the singular :user whereas resource expects the plural :users.


I've found this to work well without messing with routes or adding application controller methods. My approach is to override the devise method. Add this to app/controllers/devise/registrations_controller.rb I've omitted the other methods for brevity.

class Devise::RegistrationsController < DeviseController
  ...
  # GET /resource/sign_up
  def new
    redirect_to root_path
  end
  ....
end

Also to remove illusion that this path is still reachable from other views you might also want to remove this code from app/views/devise/shared/_links.erb

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

For others in my case.
With devise (3.5.2).
I successfully removed the routes to signup, but kept the ones to edit the profile, with the following code.

#routes.rb
devise_for :users, skip: [:registrations]
as :user do
  get 'users/edit' => 'devise/registrations#edit', :as => 'edit_user_registration'
  put '/users(.:format)' => 'devise/registrations#update', as: 'user_registration'
  patch '/users(.:format)' => 'devise/registrations#update'
end

Here's the slightly different route I went. It makes it so you don't have to override the devise/shared/_links.html.erb view.

In app/models/user.rb:

devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable

In config/routes.rb:

devise_for :users
devise_scope :user do
  put 'users' => 'devise/registrations#update', as: 'user_registration'
  get 'users/edit' => 'devise/registrations#edit', as: 'edit_user_registration'
  delete 'users' => 'devise/registrations#destroy', as: 'registration'
end

Before:

$ rake routes | grep devise
           new_user_session GET    /users/sign_in(.:format)                    devise/sessions#new
               user_session POST   /users/sign_in(.:format)                    devise/sessions#create
       destroy_user_session DELETE /users/sign_out(.:format)                   devise/sessions#destroy
              user_password POST   /users/password(.:format)                   devise/passwords#create
          new_user_password GET    /users/password/new(.:format)               devise/passwords#new
         edit_user_password GET    /users/password/edit(.:format)              devise/passwords#edit
                            PATCH  /users/password(.:format)                   devise/passwords#update
                            PUT    /users/password(.:format)                   devise/passwords#update
   cancel_user_registration GET    /users/cancel(.:format)                     devise/registrations#cancel
          user_registration POST   /users(.:format)                            devise/registrations#create
      new_user_registration GET    /users/sign_up(.:format)                    devise/registrations#new
     edit_user_registration GET    /users/edit(.:format)                       devise/registrations#edit
                            PATCH  /users(.:format)                            devise/registrations#update
                            PUT    /users(.:format)                            devise/registrations#update
                            DELETE /users(.:format)                            devise/registrations#destroy

After:

$ rake routes | grep devise
           new_user_session GET    /users/sign_in(.:format)                    devise/sessions#new
               user_session POST   /users/sign_in(.:format)                    devise/sessions#create
       destroy_user_session DELETE /users/sign_out(.:format)                   devise/sessions#destroy
              user_password POST   /users/password(.:format)                   devise/passwords#create
          new_user_password GET    /users/password/new(.:format)               devise/passwords#new
         edit_user_password GET    /users/password/edit(.:format)              devise/passwords#edit
                            PATCH  /users/password(.:format)                   devise/passwords#update
                            PUT    /users/password(.:format)                   devise/passwords#update
          user_registration PUT    /users(.:format)                            devise/registrations#update
     edit_user_registration GET    /users/edit(.:format)                       devise/registrations#edit
               registration DELETE /users(.:format)                            devise/registrations#destroy

I had the same issue and I found it a bit bad practise to redirect users from the registration page. So my solution is basically is not using :registrable at all.

What I did was to create a similar page like edit user details which looked like:

<%= form_tag(update_user_update_path, method: :post) do %>  
    <br>
    <%= label_tag(:currPassword, 'Current password:') %> <%= password_field_tag(:currPassword) %> <br>
    <%= label_tag(:newPassword, 'New password:') %> <%= password_field_tag(:newPassword) %> <br>
    <%= label_tag(:newPasswordConfirm, 'Confirm new password:') %> <%= password_field_tag(:newPasswordConfirm) %> <br>
    <%= submit_tag('Update') %>
<% end %>

So this form submits into a new post end point that updates the password, which looks like:

  def update
    currPass = params['currPassword']
    newPass1 = params['newPassword']
    newPass2 = params['newPasswordConfirm']
    currentUserParams = Hash.new()
    currentUserParams[:current_password] = currPass
    currentUserParams[:password] = newPass1
    currentUserParams[:password_confirmation] = newPass2
    @result = current_user.update_with_password(currentUserParams)
  end

Later on you can use the @result in your view to tell the user whether the password is updated or not.


By changing the routes there are a whole bunch of other problems that come with that. The easiest method I have found is to do the following.

ApplicationController < ActionController::Base
  before_action :dont_allow_user_self_registration

  private

  def dont_allow_user_self_registration
    if ['devise/registrations','devise_invitable/registrations'].include?(params[:controller]) && ['new','create'].include?(params[:action])
      redirect_to root_path
    end
  end
end

You could modify the devise gem itself. First, run this command to find the installed location of using:

gem which devise

Let's suppose the path is: /usr/local/lib/ruby/gems/1.9.1/gems/devise-1.4.2/lib/devise

Then go to

/usr/local/lib/ruby/gems/1.9.1/gems/devise-1.4.2/lib/devise/lib/devise/rails and edit routes.rb in that directory. There is a method called def devise_registration(mapping, controllers) which you can modify to get rid of the new action. You can also completely remove the mappings for devise_registration

참고URL : https://stackoverflow.com/questions/6734323/how-do-i-remove-the-devise-route-to-sign-up

반응형