Merge pull request #1698 from internetee/add-tara-to-registrant

Expand TARA auth logic to registrant portal
This commit is contained in:
Timo Võhmar 2020-10-15 16:58:12 +03:00 committed by GitHub
commit 7f81883e7b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
22 changed files with 158 additions and 401 deletions

View file

@ -1,81 +1,6 @@
class Registrant::SessionsController < Devise::SessionsController
layout 'registrant/application'
def login_mid
@user = User.new
end
def mid
phone = params[:user][:phone]
endpoint = "#{ENV['sk_digi_doc_service_endpoint']}"
client = Digidoc::Client.new(endpoint)
client.logger = Rails.application.config.logger unless Rails.env.test?
# country_codes = {'+372' => 'EST'}
response = client.authenticate(
phone: "+372#{phone}",
message_to_display: 'Authenticating',
service_name: ENV['sk_digi_doc_service_name'] || 'Testing'
)
if response.faultcode
render json: { message: response.detail.message }, status: :unauthorized
return
end
@user = RegistrantUser.find_or_create_by_mid_data(response)
if @user.persisted?
session[:user_country] = response.user_country
session[:user_id_code] = response.user_id_code
session[:mid_session_code] = client.session_code
render json: {
message: t(:confirmation_sms_was_sent_to_your_phone_verification_code_is, { code: response.challenge_id })
}, status: :ok
else
render json: { message: t(:no_such_user) }, status: :unauthorized
end
end
def mid_status
endpoint = "#{ENV['sk_digi_doc_service_endpoint']}"
client = Digidoc::Client.new(endpoint)
client.logger = Rails.application.config.logger unless Rails.env.test?
client.session_code = session[:mid_session_code]
auth_status = client.authentication_status
case auth_status.status
when 'OUTSTANDING_TRANSACTION'
render json: { message: t(:check_your_phone_for_confirmation_code) }, status: :ok
when 'USER_AUTHENTICATED'
@user = RegistrantUser.find_by(registrant_ident: "#{session[:user_country]}-#{session[:user_id_code]}")
sign_in(:registrant_user, @user)
flash[:notice] = t(:welcome)
flash.keep(:notice)
render js: "window.location = '#{registrant_root_path}'"
when 'NOT_VALID'
render json: { message: t(:user_signature_is_invalid) }, status: :bad_request
when 'EXPIRED_TRANSACTION'
render json: { message: t(:session_timeout) }, status: :bad_request
when 'USER_CANCEL'
render json: { message: t(:user_cancelled) }, status: :bad_request
when 'MID_NOT_READY'
render json: { message: t(:mid_not_ready) }, status: :bad_request
when 'PHONE_ABSENT'
render json: { message: t(:phone_absent) }, status: :bad_request
when 'SENDING_ERROR'
render json: { message: t(:sending_error) }, status: :bad_request
when 'SIM_ERROR'
render json: { message: t(:sim_error) }, status: :bad_request
when 'INTERNAL_ERROR'
render json: { message: t(:internal_error) }, status: :bad_request
else
render json: { message: t(:internal_error) }, status: :bad_request
end
end
private
def after_sign_in_path_for(_resource_or_scope)

View file

@ -1,33 +0,0 @@
class Registrar
class TaraController < ApplicationController
skip_authorization_check
# rubocop:disable Style/AndOr
def callback
session[:omniauth_hash] = user_hash
@api_user = ApiUser.from_omniauth(user_hash)
if @api_user
flash[:notice] = t(:signed_in_successfully)
sign_in_and_redirect(:registrar_user, @api_user)
else
show_error and return
end
end
# rubocop:enable Style/AndOr
def cancel
redirect_to root_path, notice: t(:sign_in_cancelled)
end
def show_error
redirect_to new_registrar_user_session_url, alert: t(:no_such_user)
end
private
def user_hash
request.env['omniauth.auth']
end
end
end

View file

@ -0,0 +1,40 @@
module Sso
class TaraController < ApplicationController
skip_authorization_check
def registrant_callback
user = RegistrantUser.find_or_create_by_omniauth_data(user_hash)
callback(user, registrar: false)
end
def registrar_callback
user = ApiUser.from_omniauth(user_hash)
callback(user, registrar: true)
end
# rubocop:disable Style/AndOr
def callback(user, registrar: true)
session[:omniauth_hash] = user_hash
(show_error(registrar: registrar) and return) unless user
flash[:notice] = t(:signed_in_successfully)
sign_in_and_redirect(registrar ? :registrar_user : :registrant_user, user)
end
# rubocop:enable Style/AndOr
def cancel
redirect_to root_path, notice: t(:sign_in_cancelled)
end
def show_error(registrar: true)
path = registrar ? new_registrar_user_session_url : new_registrant_user_session_url
redirect_to path, alert: t(:no_such_user)
end
private
def user_hash
request.env['omniauth.auth']
end
end
end

View file

@ -47,12 +47,6 @@ class ApiUser < User
self.active = true unless saved_change_to_active?
end
class << self
def find_by_id_card(id_card)
find_by(identity_code: id_card.personal_code)
end
end
def to_s
username
end

View file

@ -1,6 +0,0 @@
class IdCard
attr_accessor :first_name
attr_accessor :last_name
attr_accessor :personal_code
attr_accessor :country_code
end

View file

@ -1,7 +1,7 @@
class RegistrantUser < User
attr_accessor :idc_data
devise :trackable, :timeoutable, :id_card_authenticatable
devise :trackable, :timeoutable
def ability
@ability ||= Ability.new(self)
@ -66,23 +66,19 @@ class RegistrantUser < User
find_or_create_by_user_data(user_data)
end
def find_or_create_by_mid_data(response)
user_data = { first_name: response.user_givenname, last_name: response.user_surname,
ident: response.user_id_code, country_code: response.user_country }
def find_or_create_by_omniauth_data(omniauth_hash)
uid = omniauth_hash['uid']
identity_code = uid.slice(2..-1)
country_code = uid.slice(0..1)
first_name = omniauth_hash.dig('info', 'first_name')
last_name = omniauth_hash.dig('info', 'last_name')
user_data = { first_name: first_name, last_name: last_name,
ident: identity_code, country_code: country_code }
find_or_create_by_user_data(user_data)
end
def find_by_id_card(id_card)
registrant_ident = "#{id_card.country_code}-#{id_card.personal_code}"
username = [id_card.first_name, id_card.last_name].join("\s")
user = find_or_initialize_by(registrant_ident: registrant_ident)
user.username = username
user.save!
user
end
private
def find_or_create_by_user_data(user_data = {})

View file

@ -1,40 +0,0 @@
.row
.form-signin.col-md-4.center-block.text-center
%h2.form-signin-heading.text-center= t '.header'
%hr
= form_for @user, url: registrant_mid_path, html: {class: 'form-signin'} do |f|
= f.text_field :phone, class: 'form-control',
placeholder: t(:phone_no), autocomplete: 'off', required: true
%button.btn.btn-lg.btn-primary.btn-block.js-login{:type => 'submit'}= t '.submit_btn'
- if ['development', 'alpha'].include?(Rails.env)
%div.text-center
00007, 60000007, 00000766
:coffee
load_listener = ->
$('.js-login').attr('disabled', false)
status_interval = null
mid_status = () ->
status_interval = setInterval((->
$.post('/registrant/login/mid_status').fail((data) ->
clearInterval(status_interval)
flash_alert(data.responseJSON.message)
$('.js-login').attr('disabled', false)
)
), 1000)
$('.js-login').on 'click', (e) ->
e.preventDefault();
$(this).attr('disabled', true)
$.post($('form').attr('action'), $('form').serialize()).done((data) ->
if data.message
flash_notice(data.message)
mid_status()
).fail((data) ->
flash_alert(data.responseJSON.message)
$('.js-login').attr('disabled', false)
)
window.addEventListener 'load', load_listener

View file

@ -8,11 +8,6 @@
<%= t '.hint' %>
</div>
<br/>
<%= link_to '/registrant/login/mid' do %>
<%= image_tag 'mid.gif' %>
<% end %>
<%= link_to registrant_id_card_sign_in_path, method: :post do %>
<%= image_tag 'id_card.gif' %>
<% end %>
<%= link_to t(:sign_in), "/auth/rant_tara", method: :post, class: 'btn btn-lg btn-primary btn-block' %>
</div>
</div>
</div>

View file

@ -1,40 +0,0 @@
.row
.form-signin.col-md-4.center-block.text-center
%h2.form-signin-heading.text-center= t '.header'
%hr
= form_for @user, url: registrar_mid_path, html: {class: 'form-signin'} do |f|
= f.text_field :phone, class: 'form-control',
placeholder: t(:phone_no), autocomplete: 'off', required: true
%button.btn.btn-lg.btn-primary.btn-block.js-login{:type => 'submit'}= t '.submit_btn'
- if ['development', 'alpha'].include?(Rails.env)
%div.text-center
00007, 60000007, 00000766
:coffee
load_listener = ->
$('.js-login').attr('disabled', false)
status_interval = null
mid_status = () ->
status_interval = setInterval((->
$.post('/registrar/login/mid_status').fail((data) ->
clearInterval(status_interval)
flash_alert(data.responseJSON.message)
$('.js-login').attr('disabled', false)
)
), 1000)
$('.js-login').on 'click', (e) ->
e.preventDefault();
$(this).attr('disabled', true)
$.post($('form').attr('action'), $('form').serialize()).done((data) ->
if data.message
flash_notice(data.message)
mid_status()
).fail((data) ->
flash_alert(data.responseJSON.message)
$('.js-login').attr('disabled', false)
)
window.addEventListener 'load', load_listener

View file

@ -163,9 +163,13 @@ tara_secret: 'secret'
tara_redirect_uri: 'redirect_url'
tara_keys: "{\"kty\":\"RSA\",\"kid\":\"de6cc4\",\"n\":\"jWwAjT_03ypme9ZWeSe7c-jY26NO50Wo5I1LBnPW2JLc0dPMj8v7y4ehiRpClYNTaSWcLd4DJmlKXDXXudEUWwXa7TtjBFJfzlZ-1u0tDvJ-H9zv9MzO7UhUFytztUEMTrtStdhGbzkzdEZZCgFYeo2i33eXxzIR1nGvI05d9Y-e_LHnNE2ZKTa89BC7ZiCXq5nfAaCgQna_knh4kFAX-KgiPRAtsiDHcAWKcBY3qUVcb-5XAX8p668MlGLukzsh5tFkQCbJVyNtmlbIHdbGvVHPb8C0H3oLYciv1Fjy_tS1lO7OT_cb3GVp6Ql-CG0uED_8pkpVtfsGRviub4_ElQ\",\"e\":\"AQAB\"}"
# Email validation setting for Truemail gem. Possible values: 'regex', 'mx', 'smtp'
tara_rant_identifier: 'identifier'
tara_rant_secret: 'secret'
tara_rant_redirect_uri: 'redirect_uri'
default_email_validation_type: 'regex'
# Since the keys for staging are absent from the repo, we need to supply them separate for testing.
test:
payments_seb_bank_certificate: 'test/fixtures/files/seb_bank_cert.pem'

View file

@ -280,10 +280,4 @@ Devise.setup do |config|
# When using OmniAuth, Devise cannot automatically set OmniAuth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
require 'devise/models/id_card_authenticatable'
require 'devise/strategies/id_card_authenticatable'
routes = [nil, :new, :destroy]
config.add_module :id_card_authenticatable, strategy: true, route: { session: routes }
end

View file

@ -16,6 +16,10 @@ identifier = ENV['tara_identifier']
secret = ENV['tara_secret']
redirect_uri = ENV['tara_redirect_uri']
registrant_identifier = ENV['tara_rant_identifier']
registrant_secret = ENV['tara_rant_secret']
registrant_redirect_uri = ENV['tara_rant_redirect_uri']
Rails.application.config.middleware.use OmniAuth::Builder do
provider "tara", {
callback_path: '/registrar/open_id/callback',
@ -43,4 +47,30 @@ Rails.application.config.middleware.use OmniAuth::Builder do
redirect_uri: redirect_uri,
},
}
provider "tara", {
callback_path: '/registrant/open_id/callback',
name: 'rant_tara',
scope: ['openid'],
client_signing_alg: :RS256,
client_jwk_signing_key: signing_keys,
send_scope_to_token_endpoint: false,
send_nonce: true,
issuer: issuer,
client_options: {
scheme: 'https',
host: host,
authorization_endpoint: '/oidc/authorize',
token_endpoint: '/oidc/token',
userinfo_endpoint: nil, # Not implemented
jwks_uri: '/oidc/jwks',
# Registry
identifier: registrant_identifier,
secret: registrant_secret,
redirect_uri: registrant_redirect_uri,
},
}
end

View file

@ -2,11 +2,7 @@ en:
registrant:
sessions:
new:
header: Log in
header: Sign in with identity document
hint: >-
Access currently available only to Estonian citizens and e-residents with Estonian ID-card
or Mobile-ID.
login_mid:
header: Log in with mobile-id
submit_btn: Login
Sign in using Estonian (incl. e-residents) ID card, mobile ID,
Bank link or other EU citizen's electronic ID supported by EIDAS.

View file

@ -78,12 +78,6 @@ Rails.application.routes.draw do
devise_for :users, path: '', class_name: 'ApiUser', skip: %i[sessions]
devise_scope :registrar_user do
match '/open_id/callback', via: %i[get post], to: 'tara#callback', as: :tara_callback
match '/open_id/cancel', via: %i[get post delete], to: 'tara#cancel',
as: :tara_cancel
end
resources :invoices, except: %i[new create edit update destroy] do
resource :delivery, controller: 'invoices/delivery', only: %i[new create]
@ -160,6 +154,22 @@ Rails.application.routes.draw do
post 'sessions', to: 'registrar/sessions#create', as: :registrar_user_session
delete 'sign_out', to: 'registrar/sessions#destroy', as: :destroy_registrar_user_session
# TARA
match '/open_id/callback', via: %i[get post], to: 'sso/tara#registrar_callback'
match '/open_id/cancel', via: %i[get post delete], to: 'sso/tara#cancel'
end
end
scope :registrant do
devise_scope :registrant_user do
get 'sign_in', to: 'registrant/sessions#new', as: :new_registrant_user_session
post 'sessions', to: 'registrant/sessions#create', as: :registrant_user_session
delete 'sign_out', to: 'registrant/sessions#destroy', as: :destroy_registrant_user_session
# TARA
match '/open_id/callback', via: %i[get post], to: 'sso/tara#registrant_callback'
match '/open_id/cancel', via: %i[get post delete], to: 'sso/tara#cancel'
end
end
@ -168,17 +178,6 @@ Rails.application.routes.draw do
# POST /registrant/sign_in is not used
devise_for :users, path: '', class_name: 'RegistrantUser'
devise_scope :registrant_user do
get 'login/mid' => 'sessions#login_mid'
post 'login/mid' => 'sessions#mid'
post 'login/mid_status' => 'sessions#mid_status'
post 'mid' => 'sessions#mid'
# /registrant/id path is hardcoded in Apache config for authentication with Estonian ID-card
# Client certificate is asked only on login form submission, therefore the path must be different from the one in
# `new_registrant_user_session_path` route, in case some other auth type will be implemented
post 'id' => 'sessions#create', as: :id_card_sign_in
end
resources :registrars, only: :show
# resources :companies, only: :index

View file

@ -1,7 +0,0 @@
module Devise
module Models
# Devise fails without this module (and model: false does not help)
module IdCardAuthenticatable
end
end
end

View file

@ -1,49 +0,0 @@
module Devise
module Strategies
class IdCardAuthenticatable < Devise::Strategies::Authenticatable
def valid?
env['SSL_CLIENT_S_DN_CN'].present?
end
def authenticate!
resource = mapping.to
user = resource.find_by_id_card(id_card)
if user
success!(user)
else
fail
end
end
private
def id_card
id_card = IdCard.new
id_card.first_name = first_name
id_card.last_name = last_name
id_card.personal_code = personal_code
id_card.country_code = country_code
id_card
end
def first_name
env['SSL_CLIENT_S_DN_CN'].split(',').second.force_encoding('utf-8')
end
def last_name
env['SSL_CLIENT_S_DN_CN'].split(',').first.force_encoding('utf-8')
end
def personal_code
env['SSL_CLIENT_S_DN_CN'].split(',').last
end
def country_code
env['SSL_CLIENT_I_DN_C']
end
end
end
end
Warden::Strategies.add(:id_card_authenticatable, Devise::Strategies::IdCardAuthenticatable)

View file

@ -1,31 +0,0 @@
require 'test_helper'
class RegistrantAreaIdCardSignInTest < ApplicationIntegrationTest
setup do
allow_business_registry_component_reach_server
end
def test_succeeds
post registrant_id_card_sign_in_path, headers: { 'SSL_CLIENT_S_DN_CN' => 'DOE,JOHN,1234',
'SSL_CLIENT_I_DN_C' => 'US' }
follow_redirect!
assert_response :ok
assert_equal registrant_root_path, path
assert_not_nil controller.current_registrant_user
end
def test_fails_when_certificate_is_absent
post registrant_id_card_sign_in_path, headers: { 'SSL_CLIENT_S_DN_CN' => '' }
assert_response :ok
assert_equal registrant_id_card_sign_in_path, path
assert_nil controller.current_registrant_user
end
private
def allow_business_registry_component_reach_server
WebMock.allow_net_connect!
end
end

View file

@ -1,13 +0,0 @@
require 'test_helper'
class IdCardAuthenticatableTest < ActiveSupport::TestCase
def test_valid_when_id_card_data_is_present_in_env
strategy = Devise::Strategies::IdCardAuthenticatable.new({ 'SSL_CLIENT_S_DN_CN' => 'some' })
assert strategy.valid?
end
def test_not_valid_when_id_card_data_is_absent_in_env
strategy = Devise::Strategies::IdCardAuthenticatable.new({})
assert_not strategy.valid?
end
end

View file

@ -52,17 +52,6 @@ class ApiUserTest < ActiveSupport::TestCase
assert ApiUser.new.active?
end
def test_finds_user_by_id_card
id_card = IdCard.new
id_card.personal_code = 'one'
@user.update!(identity_code: 'one')
assert_equal @user, ApiUser.find_by_id_card(id_card)
@user.update!(identity_code: 'another')
assert_nil ApiUser.find_by_id_card(id_card)
end
def test_verifies_pki_status
certificate = certificates(:api)

View file

@ -26,13 +26,4 @@ class RegistrantUserCreationTest < ActiveSupport::TestCase
user = User.find_by(registrant_ident: 'EE-37710100070')
assert_equal('JOHN SMITH', user.username)
end
def test_find_or_create_by_mid_data_creates_a_user
user_data = OpenStruct.new(user_country: 'EE', user_id_code: '37710100070',
user_givenname: 'JOHN', user_surname: 'SMITH')
RegistrantUser.find_or_create_by_mid_data(user_data)
user = User.find_by(registrant_ident: 'EE-37710100070')
assert_equal('JOHN SMITH', user.username)
end
end

View file

@ -30,34 +30,6 @@ class RegistrantUserTest < ActiveSupport::TestCase
assert_equal Country.new('US'), user.country
end
def test_finding_by_id_card_creates_new_user_upon_first_sign_in
assert_not_equal 'US-5555', @user.registrant_ident
id_card = IdCard.new
id_card.first_name = 'John'
id_card.last_name = 'Doe'
id_card.personal_code = '5555'
id_card.country_code = 'US'
assert_difference 'RegistrantUser.count' do
RegistrantUser.find_by_id_card(id_card)
end
user = RegistrantUser.last
assert_equal 'US-5555', user.registrant_ident
assert_equal 'John Doe', user.username
end
def test_finding_by_id_card_reuses_existing_user_upon_subsequent_id_card_sign_ins
@user.update!(registrant_ident: 'US-5555')
id_card = IdCard.new
id_card.personal_code = '5555'
id_card.country_code = 'US'
assert_no_difference 'RegistrantUser.count' do
RegistrantUser.find_by_id_card(id_card)
end
end
def test_queries_company_register_for_associated_companies
assert_equal 'US-1234', @user.registrant_ident
@ -92,4 +64,4 @@ class RegistrantUserTest < ActiveSupport::TestCase
assert_equal %w(shop airport), @user.administered_domains
end
end
end
end

View file

@ -0,0 +1,51 @@
require 'application_system_test_case'
class RegistrantAreaTaraUsersTest < ApplicationSystemTestCase
def setup
super
OmniAuth.config.test_mode = true
@registrant = users(:registrant)
@existing_user_hash = {
'provider' => 'rant_tara',
'uid' => "US1234",
'info': { 'first_name': 'Registrant', 'last_name': 'User' }
}
@new_user_hash = {
'provider' => 'rant_tara',
'uid' => 'EE51007050604',
'info': { 'first_name': 'New Registrant', 'last_name': 'User'}
}
end
def teardown
super
OmniAuth.config.test_mode = false
OmniAuth.config.mock_auth['rant_tara'] = nil
end
def test_existing_user_gets_signed_in
OmniAuth.config.mock_auth[:rant_tara] = OmniAuth::AuthHash.new(@existing_user_hash)
visit new_registrant_user_session_path
click_link('Sign in')
assert_text('Signed in successfully')
end
def test_new_user_is_created_and_signed_in
OmniAuth.config.mock_auth[:rant_tara] = OmniAuth::AuthHash.new(@new_user_hash)
assert_difference 'RegistrantUser.count' do
visit new_registrant_user_session_path
click_link('Sign in')
assert_equal 'New Registrant User', RegistrantUser.last.username
assert_equal 'EE-51007050604', RegistrantUser.last.registrant_ident
assert_text('Signed in successfully')
end
end
end