Module: Parse::MFA

Defined in:
lib/parse/two_factor_auth.rb,
lib/parse/two_factor_auth/user_extension.rb

Overview

Multi-Factor Authentication (MFA) support for Parse Server.

This module interfaces with Parse Server's built-in MFA adapter which supports TOTP (Time-based One-Time Password) and SMS-based authentication.

== Parse Server Configuration

MFA must be enabled in your Parse Server configuration:

{ auth: { mfa: { enabled: true, options: ["TOTP"], // or ["SMS", "TOTP"] digits: 6, period: 30, algorithm: "SHA1" } } }

== TOTP Setup Flow

  1. Generate a secret client-side using MFA.generate_secret
  2. Display QR code to user using MFA.provisioning_uri or MFA.qr_code
  3. User scans QR with authenticator app (Google Authenticator, Authy, etc.)
  4. User enters the 6-digit code from their app
  5. Call UserExtension#setup_mfa! with secret and token to enable MFA
  6. Store the recovery codes returned - user needs these for account recovery!

== Enforcement Boundary

MFA.verify, MFA.verify_timestamp and the SDK's self-disable flow (User#disable_mfa!) are client-side checks. They are not the enforcement boundary. Parse Server's MFA adapter enforces MFA at login, and that is the boundary.

Disabling MFA is an ordinary user update (authData: { mfa: nil }). Anyone holding the user's session token can send that REST update directly without going through the SDK. Protect it server-side, for example with a beforeSave trigger on _User or a Cloud Code function that refuses to clear authData.mfa unless a fresh code was verified on the server for that request.

Examples:

Enable TOTP MFA for a user

# Step 1: Generate secret
secret = Parse::MFA.generate_secret

# Step 2: Show QR code to user
qr_svg = Parse::MFA.qr_code(secret, user.email, issuer: "MyApp")
# render qr_svg in your UI

# Step 3-4: User scans and enters code
token = params[:totp_code]  # "123456" from authenticator app

# Step 5: Enable MFA
recovery_codes = user.setup_mfa!(secret: secret, token: token)
# => "ABC123DEF456..., XYZ789..."

# Step 6: Show recovery codes to user (one time only!)

Login with MFA

user = Parse::User.("username", "password", "123456")

See Also:

Defined Under Namespace

Modules: UserExtension Classes: AlreadyEnabledError, DependencyError, ForbiddenError, NotEnabledError, RequiredError, VerificationError

Constant Summary collapse

DEFAULT_CONFIG =

Default configuration

{
  issuer: "Parse App",
  digits: 6,
  period: 30,
  algorithm: "SHA1",
  secret_length: 20,  # Minimum required by Parse Server
}.freeze

Class Method Summary collapse

Class Method Details

.build_login_auth_data(token:) ⇒ Hash

Build authData hash for MFA login.

Parameters:

  • token (String) —

    TOTP code or recovery code

Returns:

  • (Hash) —

    authData for Parse Server



341
342
343
344
345
346
347
# File 'lib/parse/two_factor_auth.rb', line 341

def (token:)
  {
    mfa: {
      token: token,
    },
  }
end

.build_setup_auth_data(secret:, token:) ⇒ Hash

Build authData hash for MFA setup.

Parameters:

  • secret (String) —

    Base32-encoded TOTP secret

  • token (String) —

    Current TOTP code for verification

Returns:

  • (Hash) —

    authData for Parse Server



328
329
330
331
332
333
334
335
# File 'lib/parse/two_factor_auth.rb', line 328

def build_setup_auth_data(secret:, token:)
  {
    mfa: {
      secret: secret,
      token: token,
    },
  }
end

.build_sms_confirm_auth_data(mobile:, token:) ⇒ Hash

Build authData hash for SMS MFA confirmation.

Parameters:

  • mobile (String) —

    Phone number

  • token (String) —

    SMS code received

Returns:

  • (Hash) —

    authData for Parse Server



366
367
368
369
370
371
372
373
# File 'lib/parse/two_factor_auth.rb', line 366

def build_sms_confirm_auth_data(mobile:, token:)
  {
    mfa: {
      mobile: mobile,
      token: token,
    },
  }
end

.build_sms_setup_auth_data(mobile:) ⇒ Hash

Build authData hash for SMS MFA setup.

Parameters:

  • mobile (String) —

    Phone number in E.164 format

Returns:

  • (Hash) —

    authData for Parse Server



353
354
355
356
357
358
359
# File 'lib/parse/two_factor_auth.rb', line 353

def build_sms_setup_auth_data(mobile:)
  {
    mfa: {
      mobile: mobile,
    },
  }
end

.config ⇒ Hash

Global MFA configuration

Returns:



132
133
134
# File 'lib/parse/two_factor_auth.rb', line 132

def config
  @config ||= DEFAULT_CONFIG.dup
end

.configure {|config| ... } ⇒ Object

Configure MFA settings

Examples:

Parse::MFA.configure do |config|
  config[:issuer] = "My App"
end

Yields:

  • (config) —

    Configuration hash



142
143
144
145
# File 'lib/parse/two_factor_auth.rb', line 142

def configure
  yield config if block_given?
  config
end

.current_code(secret) ⇒ String

Get the current TOTP code (for testing/debugging).

Parameters:

  • secret (String) —

    Base32-encoded secret

Returns:

  • (String) —

    Current 6-digit code



270
271
272
273
# File 'lib/parse/two_factor_auth.rb', line 270

def current_code(secret)
  ensure_rotp!
  totp(secret).now
end

.generate_secret(length: nil) ⇒ String

Generate a new TOTP secret for MFA setup. The secret must be at least 20 characters (Parse Server requirement).

Examples:

secret = Parse::MFA.generate_secret
# => "JBSWY3DPEHPK3PXP4QFAZJ7K"

Parameters:

  • length (Integer) (defaults to: nil) —

    Secret length (minimum 20)

Returns:

  • (String) —

    Base32-encoded secret



174
175
176
177
178
179
# File 'lib/parse/two_factor_auth.rb', line 174

def generate_secret(length: nil)
  ensure_rotp!
  length ||= config[:secret_length]
  length = [length, 20].max  # Parse Server requires minimum 20
  ROTP::Base32.random(length)
end

.provisioning_uri(secret, account_name, issuer: nil) ⇒ String

Generate provisioning URI for authenticator apps.

Examples:

uri = Parse::MFA.provisioning_uri(secret, "user@example.com", issuer: "MyApp")
# => "otpauth://totp/MyApp:user@example.com?secret=ABC123&issuer=MyApp"

Parameters:

  • secret (String) —

    Base32-encoded secret

  • account_name (String) —

    User identifier (email or username)

  • issuer (String) (defaults to: nil) —

    Optional issuer override

Returns:



285
286
287
288
# File 'lib/parse/two_factor_auth.rb', line 285

def provisioning_uri(secret, , issuer: nil)
  ensure_rotp!
  totp(secret, issuer: issuer).provisioning_uri()
end

.qr_code(secret, account_name, issuer: nil, format: :svg) ⇒ String

Generate a QR code for the authenticator app.

Examples:

svg = Parse::MFA.qr_code(secret, user.email, issuer: "MyApp")
# Render in HTML: <%= raw svg %>

Parameters:

  • secret (String) —

    Base32-encoded secret

  • account_name (String) —

    User identifier

  • issuer (String) (defaults to: nil) —

    Optional issuer name

  • format (Symbol) (defaults to: :svg) —

    Output format (:svg, :png, :ascii)

Returns:

  • (String) —

    QR code in specified format



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/parse/two_factor_auth.rb', line 301

def qr_code(secret, , issuer: nil, format: :svg)
  ensure_rqrcode!
  uri = provisioning_uri(secret, , issuer: issuer)
  qr = RQRCode::QRCode.new(uri)

  case format
  when :svg
    qr.as_svg(
      color: "000",
      shape_rendering: "crispEdges",
      module_size: 4,
      standalone: true,
    )
  when :png
    qr.as_png(size: 300)
  when :ascii
    qr.as_ansi
  else
    qr.as_svg
  end
end

.rotp_available? ⇒ Boolean

Check if rotp gem is available

Returns:

  • (Boolean)


149
150
151
152
153
154
# File 'lib/parse/two_factor_auth.rb', line 149

def rotp_available?
  require "rotp"
  true
rescue LoadError
  false
end

.rqrcode_available? ⇒ Boolean

Check if rqrcode gem is available

Returns:

  • (Boolean)


158
159
160
161
162
163
# File 'lib/parse/two_factor_auth.rb', line 158

def rqrcode_available?
  require "rqrcode"
  true
rescue LoadError
  false
end

.totp(secret, issuer: nil) ⇒ ROTP::TOTP

Create a TOTP instance for verification.

Parameters:

  • secret (String) —

    Base32-encoded secret

  • issuer (String) (defaults to: nil) —

    Optional issuer name

Returns:

  • (ROTP::TOTP)


186
187
188
189
190
191
192
193
194
# File 'lib/parse/two_factor_auth.rb', line 186

def totp(secret, issuer: nil)
  ensure_rotp!
  ROTP::TOTP.new(
    secret,
    issuer: issuer || config[:issuer],
    interval: config[:period],
    digits: config[:digits],
  )
end

.verify(secret, code, after: nil) ⇒ Boolean

Verify a TOTP code locally (for testing/validation before sending to server).

A code stays valid for its whole time step plus one step of drift on each side, so without after: the same code verifies repeatedly for roughly 90 seconds. That is fine for checking a code before sending it to Parse Server, which tracks reuse itself. An application that uses this method as its own second factor must store the timestamp of the last accepted code per user (see verify_timestamp) and pass it back as after: on the next attempt, or a captured code can be replayed.

Reading the stored timestamp, calling this method, and then writing the new timestamp is not enough on its own: two concurrent requests with the same code can both read the old value and both succeed. Update the stored value atomically, as a compare-and-set keyed on the previous timestamp (a conditional update that only matches when the stored value still equals the one passed as after:), or record each accepted step under a database unique constraint on user and time step. Treat the code as accepted only when that write succeeds.

This method is a client-side check. Parse Server's MFA adapter, which enforces MFA at login, is the enforcement boundary (see Parse::MFA).

Examples:

if Parse::MFA.verify(secret, "123456")
  puts "Code is valid!"
end

Rejecting reuse

ok = Parse::MFA.verify(secret, code, after: user_record.mfa_last_used_at)

Parameters:

  • secret (String) —

    Base32-encoded secret

  • code (String) —

    The 6-digit code to verify

  • after (Integer, Time, nil) (defaults to: nil) —

    reject codes from this time step and earlier. Pass the value returned by verify_timestamp for the last accepted code. nil (the default) applies no replay check.

Returns:

  • (Boolean) —

    True if valid



232
233
234
# File 'lib/parse/two_factor_auth.rb', line 232

def verify(secret, code, after: nil)
  !verify_timestamp(secret, code, after: after).nil?
end

.verify_timestamp(secret, code, after: nil) ⇒ Integer?

Verify a TOTP code and return the start of the matching time step.

Store the returned value after a successful login and pass it as after: on the next call to verify or verify_timestamp; codes from that step or earlier are then refused. The store must be atomic (compare-and-set on the previous value, or a unique constraint on user and time step) so concurrent requests with the same code cannot both succeed. See verify.

Examples:

ts = Parse::MFA.verify_timestamp(secret, code, after: last_used_at)
if ts
  last_used_at = ts # persist per user
end

Parameters:

  • secret (String) —

    Base32-encoded secret

  • code (String) —

    The 6-digit code to verify

  • after (Integer, Time, nil) (defaults to: nil) —

    reject codes from this time step and earlier

Returns:

  • (Integer, nil) —

    Unix timestamp of the matching step, or nil when the code is invalid or was already used



256
257
258
259
260
261
262
263
264
# File 'lib/parse/two_factor_auth.rb', line 256

def verify_timestamp(secret, code, after: nil)
  return nil if secret.blank? || code.blank?

  ensure_rotp!
  after = normalize_after(after)
  drift_seconds = config[:period]
  totp(secret).verify(code.to_s, drift_behind: drift_seconds,
                                 drift_ahead: drift_seconds, after: after)
end