Basic Rails OTP Login
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.