Skip to content

Instantly share code, notes, and snippets.

@stevepolitodesign
Last active April 19, 2021 11:37
Show Gist options
  • Save stevepolitodesign/35bb6444733e8954a6e4a69ed04e23e5 to your computer and use it in GitHub Desktop.
Save stevepolitodesign/35bb6444733e8954a6e4a69ed04e23e5 to your computer and use it in GitHub Desktop.
Create a guest user in Rails
# [1]
class AddGuestToUsers < ActiveRecord::Migration[6.0]
def change
add_column :users, :guest, :boolean, default: false, null: false
end
end
# [2]
module GuestUser
extend ActiveSupport::Concern
private
# [2.1]
def create_guest_user
# [2.1.1]
user = User.new(email: "#{SecureRandom.uuid}@#{SecureRandom.uuid}.com", guest: true)
# [2.1.2]
user.save!(validate: false)
# [2.1.3]
session[:guest_user_id] = user.id
# [2.1.4]
user
end
# [2.1]
def destroy_guest_user_session
session[:guest_user_id] = nil
end
# [2.3]
def set_guest_user
# [2.3.1]
User.find_by(id: session[:guest_user_id]).present? ? User.find_by(id: session[:guest_user_id]) : create_guest_user
end
end
# [3]
class PostsController < ApplicationController
# [3.1]
include GuestUser
# [3.2]
before_action :set_guest_user, only: :create
end
# [4]
class Users::SessionsController < Devise::SessionsController
# [4.1]
include GuestUser
# [4.2]
def create
super
destroy_guest_user_session
end
end
########
# Notes
########
# [1]: Add a `guest` column to your `users` table. This will allow you to identify user records created as guests. Useful for running a script to delete old records.
# [2]: Create a Concern to hold shared logic between Controllers.
# [2.1]: Add a private method that create a guest user.
# [2.1.1]: Use `SecureRandom.uuid` to ensure the email is unique, and set `guest` to `true`.
# [2.1.2]: Save the record without having it validated. This is necessary to avoid setting a password.
# [2.1.3]: Create a new session key set to the id of the user created. This is necessary for looking up the guest user.
# [2.1.4]: Make sure to return the user from this method.
# [2.2]: Add a private method that queries for the guest user.
# [2.3]: TODO
# [2.3.1]: TOD:
# [3.1]: Include the Concern in any Controller where you need a guest user.
# [3.2]: Query for the guest user on specific controller actions.
# [4.1]: TODO
# [4.2]: TODO
##########
# Gotchas
##########
# This specific apprach only works if you're not requiring user authentication on a particular controller#action. You'll notice in step 3 there's not before_action :authenticate_user!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment