Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

devise_invitable: Only allow admin to invite users

I am using devise_invitable gem to enable invites in my app along with devise for a rails 3 app. I have a User & Profile model. In User, there is a role column which gives type of user.

Now, I would like to restrict feature of creating new invites only to admin by scoping this scoping route to devise/invitations#new where user.role=='admin' & open rest of the routes to everybody. something like this

MyApp::Application.routes.draw do

devise_for :users, skip: [:registrations, :invitations]

as :user do
 get 'users/edit' => 'devise/registrations#edit', as: 'edit_user_registration'
  put 'users' => 'devise/registrations#update', as: 'user_registration'

# manually define alll devise_invitable routes, except devise/invitations#new

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

# user_invitation POST /users/invitation(.:format) devise/invitations#create

# also the #accept route goes here

end



resource :profile, except: :destroy

authenticated :user, lambda {|u| u.role == "admin"} do

resources :user, controller: "user"

#only allow admin to invite other users

# new_user_invitation GET /users/invitation/new(.:format) devise/invitations#new

end

root to: 'profiles#show'

end

Possible? Also, what the the better ways to do the same thing?

like image 577
CuriousMind Avatar asked Dec 11 '22 19:12

CuriousMind


1 Answers

One simple way is just overwrite the authenticate_inviter! method in side of ApplicationController as follow:

class ApplicationController < ActionController::Base
  ...
  private
  def authenticate_inviter!
    unless user.role=='admin'
      redirect_to root_url, :alert => "Access Denied"
    end
    super
  end
  ...
end

And include DeviseInvitable::Inviter module into your User model:

class User < ActiveRecord::Base
  ...
  include DeviseInvitable::Inviter
  ...
end
like image 134
Steven Yue Avatar answered Dec 26 '22 15:12

Steven Yue