Basic Rails OTP Login

Kenneth Teh
1 min readAug 19, 2020

I wanted to implement a super simple OTP system to help some of our team members log in more easily (without having to remember a password). I didn’t want to use the legacy system because it was overly complex or include yet another gem.

Be warned: I wouldn’t use this in place of an actual authentication system. For our case, this authentication was for a specific category of users with very limited permissions.

First, I prepared the Otp module, which was in charge of generating a simple 6-digit OTP and storing that temporarily for comparison purposes:

I included it as part of our User class:

class User < ApplicationRecord  include Otp  ...
end

And called it in the controller:

Note:

  • BIG CAVEAT: I used Rails.cache because we’re using Redis as our cache store. If you’re using multiple instances and NOT using a shared cache, this method does not work, and you have to use a different shared storage.
  • I used `SomeError` in place of an actual error you should raise yourself. You can just use a simple`render json: { error: ‘No such user’ }, status: 400` if you prefer.

--

--

Kenneth Teh

Software Engineer primarily working with Rails and Vue.JS... sometimes DevOps and shell stuff too