Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ gem 'xml-simple'
gem 'compact_index', '~> 0.11.0'
gem 'sprockets-rails'
gem 'rack-attack'
gem 'rqrcode'
gem 'rotp'

# Logging
gem 'lograge'
Expand Down
6 changes: 6 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ GEM
celluloid-supervision (0.20.6)
timers (>= 4.1.1)
choice (0.2.0)
chunky_png (1.3.10)
clearance (1.16.1)
bcrypt
email_validator (~> 1.4)
Expand Down Expand Up @@ -254,6 +255,9 @@ GEM
http-cookie (>= 1.0.2, < 2.0)
mime-types (>= 1.16, < 4.0)
netrc (~> 0.8)
rotp (3.3.1)
rqrcode (0.10.1)
chunky_png (~> 1.0)
rubocop (0.49.1)
parallel (~> 1.10)
parser (>= 2.3.3.1, < 3.0)
Expand Down Expand Up @@ -361,6 +365,8 @@ DEPENDENCIES
rbtrace (~> 0.4.8)
rdoc
rest-client
rotp
rqrcode
rubocop
sass
shoryuken (~> 2.1.0)
Expand Down
2 changes: 1 addition & 1 deletion app/assets/stylesheets/modules/button.css
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@

.form__submit {
margin-top: 42px;
margin-bottom: 150px;
margin-bottom: 80px;
width: 100%;
max-width: 320px;
background-color: #e9573f;
Expand Down
4 changes: 4 additions & 0 deletions app/controllers/application_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,8 @@ def append_info_to_payload(payload)
payload[:dest_host] = request.host
payload[:request_id] = request.uuid
end

def mfa_enabled?
cookies.permanent[:mfa_feature] == 'true'
end
end
61 changes: 61 additions & 0 deletions app/controllers/multifactor_auths_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
class MultifactorAuthsController < ApplicationController
before_action :check_feature_flag
before_action :redirect_to_root, unless: :signed_in?
before_action :require_mfa_disabled, only: %i[new create]
before_action :require_mfa_enabled, only: :destroy
helper_method :issuer

def new
@seed = ROTP::Base32.random_base32
session[:mfa_seed] = @seed
text = ROTP::TOTP.new(@seed, issuer: issuer).provisioning_uri(current_user.email)
@qrcode_svg = RQRCode::QRCode.new(text, level: :l).as_svg
end

def create
seed = session[:mfa_seed]
session.delete(:mfa_seed)
totp = ROTP::TOTP.new(seed, issuer: issuer)
if totp.verify(params[:otp])
current_user.enable_mfa!(seed, :mfa_login_only)
current_user.update!(last_otp_at: Time.current)
flash[:success] = t('.success')
render :recovery
else
flash[:error] = t('multifactor_auths.incorrect_otp')
redirect_to edit_profile_url
end
end

def destroy
if current_user.otp_verified?(params[:otp])
flash[:success] = t('.success')
current_user.disable_mfa!
else
flash[:error] = t('multifactor_auths.incorrect_otp')
end
redirect_to edit_profile_url
end

private

def issuer
request.host || 'rubygems.org'
end

def require_mfa_disabled
return unless current_user.mfa_enabled?
flash[:error] = t('multifactor_auths.require_mfa_disabled')
redirect_to edit_profile_path
end

def require_mfa_enabled
return if current_user.mfa_enabled?
flash[:error] = t('multifactor_auths.require_mfa_enabled')
redirect_to edit_profile_path
end

def check_feature_flag
redirect_to edit_profile_path unless mfa_enabled?
end
end
1 change: 1 addition & 0 deletions app/controllers/profiles_controller.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
class ProfilesController < ApplicationController
before_action :redirect_to_root, unless: :signed_in?, except: :show
before_action :verify_password, only: %i[update destroy]
helper_method :mfa_enabled?

def edit
@user = current_user
Expand Down
32 changes: 28 additions & 4 deletions app/controllers/sessions_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,43 @@ class SessionsController < Clearance::SessionsController
def create
@user = find_user(params.require(:session))

if mfa_enabled? && @user&.mfa_enabled?
session[:mfa_user] = @user.handle
render 'sessions/otp_prompt'
else
do_login
end
end
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This if else logic could be simpler if 'sessions/otp_prompt' made request to a new method like mfa_create.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah. and in mfa_create check session[:mfa_user] seems can achieve the same functionality


def mfa_create
@user = User.find_by_name(session[:mfa_user])
session.delete(:mfa_user)

if @user&.mfa_enabled? && @user&.otp_verified?(params[:otp])
do_login
else
login_failure(t('multifactor_auths.incorrect_otp'))
end
end

private

def do_login
sign_in(@user) do |status|
if status.success?
StatsD.increment 'login.success'
redirect_back_or(url_after_create)
else
StatsD.increment 'login.failure'
flash.now.notice = status.failure_message
render template: 'sessions/new', status: :unauthorized
login_failure(status.failure_message)
end
end
end

private
def login_failure(message)
StatsD.increment 'login.failure'
flash.now.notice = message
render template: 'sessions/new', status: :unauthorized
end

def find_user(session)
who = session[:who].is_a?(String) && session.fetch(:who)
Expand Down
38 changes: 38 additions & 0 deletions app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ class User < ApplicationRecord
validates :password, length: { within: 10..200 }, allow_nil: true, unless: :skip_password_validation?
validate :unconfirmed_email_uniqueness

enum mfa_level: { no_mfa: 0, mfa_login_only: 1, mfa_login_and_write: 2 }

def self.authenticate(who, password)
user = find_by(email: who.downcase) || find_by(handle: who)
user if user && user.authenticated?(password)
Expand Down Expand Up @@ -162,8 +164,44 @@ def remember_me?
remember_token_expires_at && remember_token_expires_at > Time.zone.now
end

def mfa_enabled?
!no_mfa?
end

def disable_mfa!
no_mfa!
self.mfa_seed = ''
self.mfa_recovery_codes = []
self.last_otp_at = nil
save!(validate: false)
end

def enable_mfa!(seed, level)
self.mfa_level = level
self.mfa_seed = seed
self.mfa_recovery_codes = Array.new(10).map { SecureRandom.hex(6) }
save!(validate: false)
end

def otp_verified?(otp)
return true if verify_digit_otp(otp)

return false unless mfa_recovery_codes.include? otp
mfa_recovery_codes.delete(otp)
save!(validate: false)
end

private

def verify_digit_otp(otp)
totp = ROTP::TOTP.new(mfa_seed)
last_success = totp.verify_with_drift_and_prior(otp, 30, last_otp_at)
return false unless last_success

self.last_otp_at = Time.at(last_success).utc.to_datetime
save!(validate: false)
end

def update_email!
self.attributes = { email: unconfirmed_email, unconfirmed_email: nil }
save!(validate: false)
Expand Down
24 changes: 24 additions & 0 deletions app/views/multifactor_auths/new.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<% @title = t('.title') %>

<div class="t-body l-overflow">
<div class="l-half--l">
<%= raw @qrcode_svg %>
</div>
<div>
<p><%= t('.scan_prompt') %></p>
<p>
<span id="mfa-account"><%= t('.account', :account => "#{issuer}:#{current_user.email}") %></span><br>
<span id="mfa-key"><%= t('.key', :key => @seed.chars.each_slice(4).map(&:join).join(' ')) %></span><br>
<span id="mfa-type"><%= t('.time_based') %></span>
</p>
</div>
</div>

<%= form_tag multifactor_auth_path, :method => :post do %>
<div class="text_field">
<%= label_tag :otp, 'OTP code', :class => 'form__label' %>
<p class='form__field__instructions'><%= t '.otp_prompt' %></p>
<%= text_field_tag :otp, '', :class => 'form__input' %>
</div>
<%= submit_tag t('.enable'), :class => 'form__submit' %>
<% end %>
11 changes: 11 additions & 0 deletions app/views/multifactor_auths/recovery.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<% @title = t('.title') %>

<div class="t-body">
<ul id="recovery-code-list">
<% current_user.mfa_recovery_codes.each do |code| %>
<li><%= code %></li>
<% end %>
</ul>
<p><%= t '.note' %></p>
<%= link_to t('.continue'), edit_profile_path %>
</div>
18 changes: 18 additions & 0 deletions app/views/profiles/edit.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,24 @@

<%= button_to t('.api_access.reset'), reset_api_v1_api_key_path, :method => :put, :data => {:confirm => t('.api_access.confirm_reset')}, :class => 'form__submit' %>

<% if mfa_enabled? %>
<div class="t-body">
<h2><%= t '.mfa.multifactor_auth' %></h2>
<% if @user.mfa_enabled? %>
<p><%= t '.mfa.enabled' %></p>
<%= form_tag multifactor_auth_path, :method => :delete do %>
<%= text_field_tag :otp, '', :class => 'form__input' %>
<%= submit_tag t('.mfa.disable'), :class => 'form__submit' %>
<% end %>
<% else %>
<p>
<%= t '.mfa.disabled' %>
<%= button_to t('.mfa.go_settings'), new_multifactor_auth_path, :method => 'get', :class => 'form__submit' %>
</p>
<% end %>
</div>
<% end %>

<div class="t-body">
<h2><%= t '.delete.delete_profile' %></h2>
<p><%= t '.delete.warning' %></p>
Expand Down
11 changes: 11 additions & 0 deletions app/views/sessions/otp_prompt.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<% @title = t('multifactor_authentication') %>

<%= form_tag mfa_create_session_path, :method => :post do %>
<div class="text_field">
<%= label_tag :otp, t('multifactor_auths.otp_code'), :class => 'form__label' %>
<%= text_field_tag :otp, '', :class => 'form__input', :autofocus => true %>
</div>
<div class="form_bottom">
<%= submit_tag t('sign_in'), :data => {:disable_with => t('form_disable_with')}, :class => 'form__submit' %>
</div>
<% end %>
29 changes: 29 additions & 0 deletions config/locales/de.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ de:
please_sign_up: Zugriff verweigert. Bitte melden Sie sich unter https://rubygems.org mit einem Konto an
sign_in: Anmelden
sign_up: Registrieren
multifactor_authentication:
subtitle: Ihre Community des Gem-Hostingservices
this_rubygem_could_not_be_found: Dieses Ruby Gem konnte nicht gefunden werden.
time_ago: seit %{duration}
Expand Down Expand Up @@ -135,6 +136,28 @@ de:
submit: Zurücksetzen des Passworts
title: Ändere dein Passwort
will_email_notice: Wir senden dir einen Link damit du dein Passwort ändern kannst.
multifactor_auths:
incorrect_otp:
otp_code:
require_mfa_disabled:
require_mfa_enabled:
new:
title:
scan_prompt:
otp_prompt:
confirm:
enable:
account:
key:
time_based:
create:
success:
recovery:
continue:
title:
note:
destroy:
success:
profiles:
edit:
email_awaiting_confirmation:
Expand All @@ -157,6 +180,12 @@ de:
delete:
delete_profile:
warning:
mfa:
multifactor_auth:
disabled:
go_settings:
enabled:
disable:
delete:
title:
confirm:
Expand Down
29 changes: 29 additions & 0 deletions config/locales/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ en:
please_sign_up: Access Denied. Please sign up for an account at https://rubygems.org
sign_in: Sign in
sign_up: Sign up
multifactor_authentication: Multifactor authentication
subtitle: your community gem host
this_rubygem_could_not_be_found: This rubygem could not be found.
time_ago: "%{duration} ago"
Expand Down Expand Up @@ -135,6 +136,28 @@ en:
submit: Reset password
title: Change your password
will_email_notice: We will email you a link to change your password.
multifactor_auths:
incorrect_otp: Your OTP code is incorrect.
otp_code: OTP code
require_mfa_disabled: Your multifactor authentication has been enabled. You have to disable it first.
require_mfa_enabled: Your multifactor authentication has not been enabled. You have to enable it first.
new:
title: Enabling multifactor auth
scan_prompt: Please scan the qr-code with your authenticator app. If you cannot scan the code, add information below into your app manually.
otp_prompt: Type digit code from auth app to continue.
confirm: I have kept my recovery codes safe.
enable: Enable
account: "Account: %{account}"
key: "Key: %{key}"
time_based: "Time based: Yes"
create:
success: You have successfully enabled multifactor authentication.
recovery:
continue: Continue
title: Recovery codes
note: "You MUST keep the recovery codes safe to prevent losing your account. Each of the code can be used once if you lose your authenticator."
destroy:
success: You have successfully disabled multifactor authentication.
profiles:
edit:
email_awaiting_confirmation: Please confirm your new email address %{unconfirmed_email}
Expand All @@ -157,6 +180,12 @@ en:
delete: Delete
delete_profile: Delete Profile
warning: Deleting your profile is an irreversible action. This can't be undone by contacting support. Please be certain!
mfa:
multifactor_auth: Multifactor authentication
disabled: You have not yet enabled multifactor authentication.
go_settings: Register a new device
enabled: You have enabled multifactor authentication. Please input your OTP from your authenticator or one of your active recovery codes to disable it.
disable: Disable
delete:
title: Delete profile
confirm: Confirm
Expand Down
Loading