# DeviseInvitable
[](http://badge.fury.io/rb/devise_invitable) [
](https://github.com/scambra/devise_invitable/actions/workflows/ci.yml
) [
](https://codeclimate.com/github/scambra/devise_invitable)
It adds support to [Devise](https://github.com/plataformatec/devise) for
sending invitations by email (it requires to be authenticated) and accept the
invitation setting the password.
## Requirements
The latest version of DeviseInvitable works with Devise >= 4.6.
If you want to use devise_invitable with earlier Devise releases (4.0 <= x <
4.6), use version 1.7.5.
## Installation
Install DeviseInvitable gem:
```shell
gem install devise_invitable
```
Add DeviseInvitable to your Gemfile:
```ruby
gem 'devise_invitable', '~> 2.0.0'
```
### Automatic installation
Run the following generator to add DeviseInvitable’s configuration option in
the Devise configuration file (`config/initializers/devise.rb`):
```shell
rails generate devise_invitable:install
```
When you are done, you are ready to add DeviseInvitable to any of your Devise
models using the following generator:
```shell
rails generate devise_invitable MODEL
```
Replace MODEL by the class name you want to add DeviseInvitable, like `User`,
`Admin`, etc. This will add the `:invitable` flag to your model's Devise
modules. The generator will also create a migration file (if your ORM supports
them).
### Manual installation
Follow the walkthrough for Devise and after it's done, follow this
walkthrough.
#### Devise Configuration
Add `:invitable` to the `devise` call in your model (we’re assuming here you
already have a User model with some Devise modules):
```ruby
class User < ActiveRecord::Base
devise :database_authenticatable, :confirmable, :invitable
end
```
#### ActiveRecord Migration
Add `t.invitable` to your Devise model migration:
```ruby
create_table :users do
...
## Invitable
t.string :invitation_token
t.datetime :invitation_created_at
t.datetime :invitation_sent_at
t.datetime :invitation_accepted_at
t.integer :invitation_limit
t.integer :invited_by_id
t.string :invited_by_type
...
end
add_index :users, :invitation_token, unique: true
```
or for a model that already exists, define a migration to add DeviseInvitable
to your model:
```ruby
def change
add_column :users, :invitation_token, :string
add_column :users, :invitation_created_at, :datetime
add_column :users, :invitation_sent_at, :datetime
add_column :users, :invitation_accepted_at, :datetime
add_column :users, :invitation_limit, :integer
add_column :users, :invited_by_id, :integer
add_column :users, :invited_by_type, :string
add_index :users, :invitation_token, unique: true
end
```
If you previously used devise_invitable with a `:limit` on
`:invitation_token`, remove it:
```ruby
def up
change_column :users, :invitation_token, :string, limit: nil
end
def down
change_column :users, :invitation_token, :string, limit: 60
end
```
## Mongoid Field Definitions
If you are using Mongoid, define the following fields and indexes within your
invitable model:
```ruby
field :invitation_token, type: String
field :invitation_created_at, type: Time
field :invitation_sent_at, type: Time
field :invitation_accepted_at, type: Time
field :invitation_limit, type: Integer
index( { invitation_token: 1 }, { background: true} )
index( { invitation_by_id: 1 }, { background: true} )
```
You do not need to define a `belongs_to` relationship, as DeviseInvitable does
this on your behalf:
```ruby
belongs_to :invited_by, polymorphic: true
```
Remember to create indexes within the MongoDB database after deploying your
changes.
```shell
rake db:mongoid:create_indexes
```
## Model configuration
DeviseInvitable adds some new configuration options:
* `invite_for`: The period the generated invitation token is valid. After
this period, the invited resource won't be able to accept the invitation.
When `invite_for` is `0` (the default), the invitation won't expire.
You can set this configuration option in the Devise initializer as follow:
```ruby
# ==> Configuration for :invitable
# The period the generated invitation token is valid.
# After this period, the invited resource won't be able to accept the invitation.
# When invite_for is 0 (the default), the invitation won't expire.
# config.invite_for = 2.weeks
```
or directly as parameters to the `devise` method:
```ruby
devise :database_authenticatable, :confirmable, :invitable, invite_for: 2.weeks
```
* `invitation_limit`: The number of invitations users can send. The default
value of `nil` means users can send as many invites as they want, there is
no limit for any user, `invitation_limit` column is not used. A setting
of `0` means they can't send invitations. A setting `n > 0` means they can
send `n` invitations. You can change `invitation_limit` column for some
users so they can send more or less invitations, even with global
`invitation_limit = 0`.
* `invite_key`: The key to be used to check existing users when sending an
invitation. You can use multiple keys. This value must be a hash with the
invite key as hash keys, and values that respond to the `===` operator
(including procs and regexes). The default value is looking for users by
email and validating with `Devise.email_regexp`.
* `validate_on_invite`: force a record to be valid before being actually
invited.
* `resend_invitation`: resend invitation if user with invited status is
invited again. Enabled by default.
* `invited_by_class_name`: the class name of the inviting model. If this is
`nil`, polymorphic association is used.
* `invited_by_foreign_key`: the foreign key to the inviting model (only used
if `invited_by_class_name` is set, otherwise `:invited_by_id`)
* `invited_by_counter_cache`: the column name used for counter_cache column.
If this is `nil` (default value), the `invited_by` association is declared
without `counter_cache`.
* `allow_insecure_sign_in_after_accept`: automatically sign in the user
after they set a password. Enabled by default.
* `require_password_on_accepting`: require password when user accepts the
invitation. Enabled by default. Disable if you don't want to ask or
enforce to set password while accepting, because is set when user is
invited or it will be set later.
For more details, see `config/initializers/devise.rb` (after you invoked the
`devise_invitable:install` generator described above).
## Configuring views
All the views are packaged inside the gem. If you'd like to customize the
views, invoke the following generator and it will copy all the views to your
application:
```shell
rails generate devise_invitable:views
```
You can also use the generator to generate scoped views:
```shell
rails generate devise_invitable:views users
```
Then turn scoped views on in `config/initializers/devise.rb`:
```ruby
config.scoped_views = true
```
Please refer to [Devise's README](https://github.com/plataformatec/devise) for
more information about views.
## Configuring controllers
To change the controller's behavior, create a controller that inherits from
`Devise::InvitationsController`. The available methods are: `new`, `create`,
`edit`, and `update`. Refer to the [original controllers source](https://github.com/scambra/devise_invitable/blob/master/app/controllers/devise/invitations_controller.rb)
before editing any of these actions. Your
controller might now look something like this:
```ruby
class Users::InvitationsController < Devise::InvitationsController
def update
if some_condition
redirect_to root_path
else
super
end
end
end
```
Now just tell Devise that you want to use your controller, the controller
above is `'users/invitations'`, so our routes.rb would have this line:
```ruby
devise_for :users, controllers: { invitations: 'users/invitations' }
```
be sure that you generate the views and put them into the controller that you
generated, so for this example it would be:
```shell
rails generate devise_invitable:views users
```
To change behaviour of inviting or accepting users, you can simply override
two methods:
```ruby
class Users::InvitationsController < Devise::InvitationsController
private
# This is called when creating invitation.
# It should return an instance of resource class.
def invite_resource
# skip sending emails on invite
super { |user| user.skip_invitation = true }
end
# This is called when accepting invitation.
# It should return an instance of resource class.
def accept_resource
resource = resource_class.accept_invitation!(update_resource_params)
# Report accepting invitation to analytics
Analytics.report('invite.accept', resource.id)
resource
end
end
```
## Strong Parameters
When you customize your own views, you may end up adding new attributes to
forms. Rails 4 moved the parameter sanitization from the model to the
controller, causing DeviseInvitable to handle this concern at the controller
as well. Read about it in [Devise
README](https://github.com/plataformatec/devise#strong-parameters)
There are just two actions in DeviseInvitable that allows any set of
parameters to be passed down to the model, therefore requiring sanitization.
Their names and the permited parameters by default are:
* `invite` (Devise::InvitationsController#create) - Permits only the
authentication keys (like `email`)
* `accept_invitation` (Devise::InvitationsController#update) - Permits
`invitation_token` plus `password` and `password_confirmation`.
Here is an example of the steps needed to add a first_name, last_name and role to invited Users.
Caution: Adding roles requires additional security measures, such as preventing a standard user from inviting an administrator. Implement appropriate access controls to ensure system security.
### Configuring your application controller to accept :first_name, :last_name, and :role for a User
Note: These modifications can be applied directly in the InvitationsController if not needed for other Devise actions.
```ruby
before_action :configure_permitted_parameters, if: :devise_controller?
protected
# Permit the new params here.
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:invite, keys: [:first_name, :last_name, :role])
end
```
### Define your roles in the User model
```ruby
class User < ApplicationRecord
has_many :models
enum role: {Role 1 Name: 0, Role 2 Name: 1, Role 3 Name: 2, etc...}
end
```
### In the Invitation view
```ruby