Jerome
Jerome

Reputation: 6189

Admin creating users under devise

Rials 4.2 application with devise 3.5 where user creation limited to two types of users (identified by boolean values). Pundit is used for authorization, but NOT invoked the User class.

Routes defines

devise_for :users, :controllers => { registrations: 'registrations' }
resources :users do
  collection do
    get :index_context
  end
end

A registrations_controller sets up private methods to define sign_up_params and account_update_params => params.require(:user).permit( ...

Applications_controller authenticates from token

def authenticate_user_from_token!
  user_email = request.headers["X-API-EMAIL"].presence
  user_auth_token = request.headers["X-API-TOKEN"].presence
  user = user_email && User.find_by_email(user_email)

  if user && Devise.secure_compare(user.authentication_token, user_auth_token)
    sign_in(user, store: false)
  end
end

Given the context, the attempt is to override devise by having a sessions_controller

class SessionsController < Devise::SessionsController
    skip_before_filter :authenticate_user!, :only => [:create, :new]
    skip_authorization_check only: [:create, :failure, :show_current_user, :options, :new]

But when a user that is enabled to create users submits the record

Started POST "/users" for [...]
Filter chain halted as :require_no_authentication rendered or redirected

just as if the user would go to address /users/sign_in

Thus somehow the request is being captured by Devise's handling, notwithstanding the session controller's before filter. How can this be overcome?

Upvotes: 2

Views: 249

Answers (1)

Jerome
Jerome

Reputation: 6189

After perusing various options like overriding the RegistrationsController, but simply creating a separate action, with relevant authorization, like Pundit,

  def admin_new
    @local_user = User.new
  end

  def admin_create
    @local_user = User.new(user_params)
    @local_user.save
    respond_with(@local_user)
  end

where form states:

<%= form_for(@local_user, :url => admin_create_users_path) do |f| %>

actaully bypasses devise and allows an admin (or any other role) to create users.

Upvotes: 1

Related Questions