We've moved discussions to Discord

Can you create a shareable invite link?

Chinmay Kulkarni
Some account owners with my app don't want to type out everyone's name and email in the invite UI, and instead just want a link that they can share via Slack or a mailing list. Is there a way to create such non-one-time use invite links?

(Sorry if I am missing something obvious!)
Tiago Casanova
I gave it a go for that feature, AFAIK you need custom code. Here's my approach:

- add has_secure_token to Account

- add a migration

class AddSecureTokenToAccount < ActiveRecord::Migration[6.1]  
  def change    
    add_column :accounts, :token, :string    
    add_column :accounts, :token_updated_at, :datetime
# Update all existing accounts Account.all.each do |account| account.regenerate_token account.update(token_updated_at: Time.current) end end end


- add a generic route, for example

resources :accounts do    
  member do      
    patch :switch      
    
    get "generic_invitation/:token", to: "accounts#generic_invitation", as: :generic_invitation   <=====
  end  
end

- use the AccountsController to setup the invite to the correct URL

class AccountsController < Accounts::BaseController  
  before_action :authenticate_user_with_invite!, only: [:generic_invitation]

def authenticate_user_with_invite! @account = Account.find(params[:id]) unless user_signed_in? store_location_for(:user, request.fullpath) redirect_to new_user_registration_path(invite: @account.token), alert: t(".authenticate") end end

- at app/controllers/users/registrations_controller.rb

if params[:invite] && (invite = AccountInvitation.find_by(token: params[:invite]) || Account.find_by(token: params[:invite]))

- Edit the HTML at app/views/devise/registrations/new.html.erb as you see fit, to show the invitation details, and check for the following 

<% if @account_invitation.instance_of?(AccountInvitation) %>

- add an invite link somewhere in your Account view!

<%= tag.button t(".invite_link"), class: "btn btn-link", data: { controller: "clipboard", clipboard_text: generic_invitation_account_url(@account, @account.token) }


As a final optional note, you can (should!) regenerate the secure token in the Account model every once in a while in a background job, that's why I added the timestamp for token_updated_at, but that's entirely up to you.

Hope this helps!

Chinmay Kulkarni
Thank you Tiago Casanova this is very helpful! I'll probably modify this code to have a 30 day expiration window using the `token_updated_at` attributes. Thanks again!

adrien nhem
That's so good thank you! You also need to define an accept! method on Account
Notifications
You’re not receiving notifications from this thread.