Search code examples
ruby-on-railsdevise

Setting up a demo user that expires after X days with devise


I made an app where a user can store data specific to its personal use case/environment. I currently set up my user with the devise gem. A user has a enum role: [:owner, :admin, :employee]

Now I would to create the possibility where a user can have 30 days access to the app (e.g. for a demo), where:

  • a demo_user can just log into the platform without the application having to invite him/her
  • the demo_user and all related data will be deleted after the demo expires (30 days after creation).

Question

How to best set this up (in a Rails way)?

I though about just adding a role and creating the logic for deletion etc. in my model, but this does not seem the most neat way to do it.


Solution

  • If you haven't generated the devise sessions controller, then run:

    rails generate devise:controllers users -c=sessions

    And in your config/routes.rb file, add:

    devise_for :users, controllers: { sessions: 'users/sessions' }

    That tells Devise to use the new controller you just generated. Then in your User model, add a method that tells you whether the user is expired or not:

    ## app/models/user.rb
    
    class User < ApplicationRecord
      ROLES = %i[owner admin employee].freeze
      ...
      ...
    
      def expired?
        return false if ROLES.include? role
        (Time.now..30.days.ago) === created_at
      end
    end
    

    I'm assuming you check for demo users by checking their role, and if they're an admin owner or employee they're not a demo user.

    Finally in your new sessions controller, you can remove all the methods (this will tell rails to use the devise standard ones), and insert the new create method:

    class Users::SessionsController < Devise::SessionsController
      def create
        if resource.expired?
          flash[:error] = "Your account has expired"
          return redirect_to new_user_session_path
        end
        super
      end
    end