一种设计邀请策略
It adds support to Devise for sending invitations by email (it requires to be authenticated) and accept the invitation setting the password.
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.
Install DeviseInvitable gem:
gem install devise_invitable
Add DeviseInvitable to your Gemfile:
gem 'devise_invitable', '~> 2.0.0'
Run the following generator to add DeviseInvitable’s configuration option in
the Devise configuration file (config/initializers/devise.rb):
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:
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).
Follow the walkthrough for Devise and after it's done, follow this walkthrough.
Add :invitable to the devise call in your model (we’re assuming here you
already have a User model with some Devise modules):
class User < ActiveRecord::Base
devise :database_authenticatable, :confirmable, :invitable
end
Add t.invitable to your Devise model migration:
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:
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:
def up
change_column :users, :invitation_token, :string, limit: nil
end
def down
change_column :users, :invitation_token, :string, limit: 60
end
If you are using Mongoid, define the following fields and indexes within your invitable model:
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:
belongs_to :invited_by, polymorphic: true
Remember to create indexes within the MongoDB database after deploying your changes.
rake db:mongoid:create_indexes
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:
# ==> 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:
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).
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:
rails generate devise_invitable:views
You can also use the generator to generate scoped views:
rails generate devise_invitable:views users
Then turn scoped views on in config/initializers/devise.rb:
config.scoped_views = true
Please refer to Devise's README for more information about views.
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
before editing any of these actions. Your
controller might now look something like this:
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:
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:
rails generate devise_invitable:views users
To change behaviour of inviting or accepting users, you can simply override two methods:
…
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
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.
Note: These modifications can be applied directly in the InvitationsController if not needed for other Devise actions.
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
class User < ApplicationRecord
has_many :models
enum role: {Role 1 Name: 0, Role 2 Name: 1, Role 3 Name: 2, etc...}
end
<h2><%= t "devise.invitations.new.header" %></h2>
<%= form_for(resource, as: resource_name, url: invitation_path(resource_name), html: { method: :post }) do |f| %>
<%= render "devise/shared/error_messages", resource: resource %>
<% resource.class.invite_key_fields.each do |field| -%>
<% end %>
<% end %>
To send an invitation to a user, use the invite! class method. Note: This
will create a user, and send an email for the invite. :email must be
present in the parameters hash. You can also include other attributes in the
hash. The record will not be validated.
User.invite!(email: '[email protected]', name: 'John Doe')
# => an invitation email will be sent to [email protected]
If you want to create the invitation but not send it, you can set
skip_invitation to true.
user = User.invite!(email: '[email protected]', name: 'John Doe') do |u|
u.skip_invitation = true
end
# => the record will be created, but the invitation email will not be sent
When generating the accept_user_invitation_url yourself, you must use the
raw_invitation_token. This value is temporarily available when you invite a
user and will be decrypted when received.
accept_user_invitation_url(invitation_token: user.raw_invitation_token)
When skip_invitation is used, you must also then set the
invitation_sent_at field when the user is sent their token. Failure to do so
will yield "Invalid invitation token" error when the user attempts to accept
the invite. You can set the column, or call deliver_invitation to send the
invitation and set the column:
user.deliver_invitation
You can add :skip_invitation to attributes hash if skip_invitation is
added to attr_accessible.
User.invite!(email: '[email protected]', name: 'John Doe', skip_invitation: true)
# => the record will be created, but the invitation email will not be sent
skip_invitation skips sending the email, but sets invitation_token, so
invited_to_sign_up? on the re
暂无开放 Issues,或尚未同步最近议题。