# Reading Rodaauth's Sms Confirmation Code

I recently had to implement SMS confirmation codes. Essentially, it is sending an SMS message similar to: Your authentication code is 117940. While figuring out how to implement the verification code I came across Rodaauth (opens new window). I couldn't of course integrate with Rodauth but I learned a lot by reading the code. Here are some highlights:

# Secure Compare

This is something I would have never realized I needed to do until I read thorough Rodaauth's codebase. Here is the actual code:

def timing_safe_eql?(provided, actual)
  provided = provided.to_s
  Rack::Utils.secure_compare(provided.ljust(actual.length), actual) && provided.length == actual.length

Source (opens new window)

Here are two options one using Rack and the other with Rails.

# Rack
Rack::Utils.secure_compare(a, b)

# Rails
ActiveSupport::SecurityUtils.secure_compare(a, b)

A simple string compare is not safe from timing attack; therefore, a more advanced comparison algorithm is required. More details here (opens new window).

# Confirm code

The other thing I liked about Rodauth was how the actual code was generated:

def sms_new_confirm_code
  SecureRandom.random_number(10**sms_confirm_code_length).to_s.rjust(sms_confirm_code_length, "0")

Source (opens new window)

There are several pieces to this:

  1. Using SecureRandom instead of rand()
  2. Converting the number to a string right away
  3. Adding 0 to the right if the generated number is less than the required length. The implementation using rjust is very clean in my opinion.


This was also the first time I came across Sequel::CURRENT_TIMESTAMP.

def sms_set_code(code)
 update_sms(sms_code_column=>code, sms_issued_at_column=>Sequel::CURRENT_TIMESTAMP)

Source (opens new window)

I am still new to Sequel so this is a nifty trick I didn't know about. Sequel also exposes :NOW.sql_function which uses the underlying NOW() method that the database provides.

Beyond that, I just learned a lot from Jermy Evan's style of writing Ruby. In conclusion, reading open-source is extremely beneficial.

Last Modified: 9/21/2020, 12:46:10 PM