vp-login 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: c4ae09a37c684fabb1ad0785244543d06f2dedd5677c082326e98cf4dfaca76b
4
+ data.tar.gz: 95ffa6c00de23343793deca3cc8d22c3205ba6686d41f35727b7aa8290ea8444
5
+ SHA512:
6
+ metadata.gz: 8e30bffd9319f637b6e780e52858edb1becc44029e2a9d40e62c4d9a4d3405a63db236c260ef205e07952ea6f3813d72a2ee06a95b62ea0eb03ee3abc922b077
7
+ data.tar.gz: 6742ac424b91f9fb5f03cd2d023d0461874e61f818314a3e7aaca18c84bb64b6c8e3bc1e337497034f7970e3b3aa980136e8084be024ad838bd6cbcfffd82c76
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Volopay
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,109 @@
1
+ # vp-login
2
+
3
+ App-side integration for **vpLogin**, Volopay's identity provider: the OIDC sign-in with PKCE and
4
+ ID-token checks, Rails login endpoints, and the vpLogin admin API. Used by volo-be and oxo-global-be.
5
+
6
+ ## Install
7
+
8
+ ```ruby
9
+ gem 'vp-login', '~> 0.3', require: 'vplogin'
10
+ ```
11
+
12
+ It needs Ruby >= 3.1 and jwt 2.5–3.x; the controller needs Rails >= 7. It's published on
13
+ rubygems.org, so builds need no credentials.
14
+
15
+ ## Configuration
16
+
17
+ It's read from the environment:
18
+
19
+ - `VPLOGIN_ISSUER_URL`: `https://<host>/application/o/<app-slug>/`
20
+ - `VPLOGIN_CLIENT_ID`, `VPLOGIN_CLIENT_SECRET`, `VPLOGIN_REDIRECT_URL`
21
+ - `VPLOGIN_FRONTEND_URL`: the frontend's `/vplogin-login` handoff and `/login` pages
22
+ - `VPLOGIN_ADMIN_API_URL`, `VPLOGIN_API_TOKEN`: admin API only
23
+ - `VPLOGIN_PROVISION_EMAIL_MFA`: `true` to give provisioned identities an email MFA factor
24
+ (default off: vpLogin's flow decides)
25
+
26
+ Override anything with `VpLogin.configure { |c| ... }`. Login state is kept in `Rails.cache`,
27
+ which must be shared across processes.
28
+
29
+ ## Rails login (devise_token_auth)
30
+
31
+ ```ruby
32
+ # routes: GET login, GET callback, POST verify
33
+ vplogin_routes controller: 'auth/vplogin', path: 'auth/vplogin'
34
+
35
+ class Auth::VploginController < ApplicationController
36
+ include VpLogin::DeviseTokenAuthController
37
+
38
+ private
39
+
40
+ # optional: refuse or prepare the user before a token is issued
41
+ def vplogin_before_sign_in(user, _claims, _data)
42
+ render json: { errors: ['Blocked'] }, status: :unauthorized if user.blocked?
43
+ end
44
+
45
+ # optional: the success body. claims.mfa? says whether the vpLogin sign-in included MFA;
46
+ # vplogin_client is the client of the token just issued.
47
+ def vplogin_session_response(user, claims, _data)
48
+ { success: true, data: user.token_validation_response, mfa_done: claims.mfa? }
49
+ end
50
+ end
51
+ ```
52
+
53
+ It finds the user by the verified email and issues the devise_token_auth session. For other
54
+ auth setups, include `VpLogin::Controller` and implement `vplogin_resolve_user` and
55
+ `vplogin_sign_in`.
56
+
57
+ Two more modules need the admin API and do nothing without it:
58
+
59
+ ```ruby
60
+ class Auth::SessionsController < DeviseTokenAuth::SessionsController
61
+ include VpLogin::DeviseTokenAuthLogout # sign-out also ends this browser's vpLogin session
62
+ end
63
+
64
+ class User < ApplicationRecord
65
+ include VpLogin::DeviseUser # copies every password change to vpLogin
66
+ end
67
+
68
+ user.vplogin_provision_later # on invite: create the vpLogin identity
69
+ ```
70
+
71
+ Both run as ActiveJob jobs on `config.job_queue`. Override `vplogin_name` /
72
+ `vplogin_password_set?` on the model where the defaults don't fit.
73
+
74
+ ## Without the controller
75
+
76
+ ```ruby
77
+ oidc = VpLogin::Oidc.new
78
+ start = oidc.start(data: { tenant: 'acme' }) # start.url
79
+ cb = oidc.callback(state: params[:state], code: params[:code])
80
+ attempt = oidc.redeem(cb.handoff_code)
81
+ claims = oidc.exchange(code: attempt[:code], code_verifier: attempt[:code_verifier], nonce: attempt[:nonce])
82
+ ```
83
+
84
+ ## Admin API
85
+
86
+ ```ruby
87
+ admin = VpLogin::Admin.new
88
+ # invite or migration: create or find; group and email MFA factor (new identities) are optional
89
+ result = admin.provision_user!(email:, name:, group: 'acme', email_mfa: true) { |identity, created| save(identity['pk']) }
90
+ result.created; result.pk; result.mfa_error
91
+ admin.add_user_to_group!(id, group_name: 'acme')
92
+ admin.sync_bcrypt_password!(email:, bcrypt_hash: user.encrypted_password)
93
+ admin.end_session!(id, sid: claims['sid']) # one browser; needs vpLogin's end_session API
94
+ admin.revoke_sessions_for!(email:) # every device
95
+ ```
96
+
97
+ Errors are `VpLogin::Error` subclasses with a `#code`.
98
+
99
+ ## Releasing
100
+
101
+ Bump `lib/vplogin/version.rb`, tag `vX.Y.Z`, then
102
+ `gem build vplogin.gemspec && gem push vp-login-X.Y.Z.gem`. In each app, run
103
+ `bundle update vp-login` and restart it.
104
+
105
+ ## Development
106
+
107
+ ```bash
108
+ bundle install && bundle exec rspec
109
+ ```
@@ -0,0 +1,223 @@
1
+ # frozen_string_literal: true
2
+
3
+ module VpLogin
4
+ # vpLogin admin API (needs `api_token`). Group membership is how an identity is linked to a
5
+ # tenant/workspace: one group per tenant, named by the app.
6
+ class Admin
7
+ DEVICE_ENDPOINTS = {
8
+ 'authentik_stages_authenticator_sms.SMSDevice' => 'sms',
9
+ 'authentik_stages_authenticator_totp.TOTPDevice' => 'totp',
10
+ 'authentik_stages_authenticator_email.EmailDevice' => 'email'
11
+ }.freeze
12
+
13
+ def initialize(config: VpLogin.configuration, http: nil)
14
+ @config = config
15
+ @http = http || Http.new(config)
16
+ end
17
+
18
+ # Users
19
+
20
+ # vpLogin requires a unique username; the email is used for it. Returns nil if it already exists.
21
+ def create_user!(email:, name:)
22
+ request!(:post, '/core/users/', { username: email, name:, email:, is_active: true })
23
+ rescue HttpError => e
24
+ raise unless e.status == 400 && e.body.to_s.include?('unique')
25
+
26
+ nil
27
+ end
28
+
29
+ Provisioned = Struct.new(:identity, :created, :mfa_error, keyword_init: true) do
30
+ def pk = identity['pk']
31
+ end
32
+
33
+ # Brings a person into vpLogin for an invite or a migration: creates the identity (or finds the
34
+ # existing one), links it to `group`, and for a new identity adds an email MFA factor so nobody
35
+ # is ever factor-less. The block runs before the group link, so the caller can store the pk
36
+ # first - a retry after a failed link then finds the identity instead of losing it.
37
+ # An email-factor failure doesn't stop provisioning; it comes back as `mfa_error`.
38
+ def provision_user!(email:, name:, group: nil, email_mfa: false)
39
+ created = create_user!(email:, name:)
40
+ identity = created || find_user(email:)
41
+ raise ProvisioningError, "vpLogin reports #{email} exists but it could not be found" if identity.nil?
42
+
43
+ yield identity, !created.nil? if block_given?
44
+ add_user_to_group!(identity['pk'], group_name: group) if group
45
+
46
+ mfa_error = nil
47
+ if email_mfa && created
48
+ begin
49
+ import_mfa_devices!(identity['pk'], email_device: true)
50
+ rescue HttpError => e
51
+ logger.error("[VpLogin::Admin] email MFA factor for #{identity['pk']} failed: #{e.message}")
52
+ mfa_error = e
53
+ end
54
+ end
55
+
56
+ Provisioned.new(identity:, created: !created.nil?, mfa_error:)
57
+ end
58
+
59
+ def find_user(email:)
60
+ results(get('/core/users/', username: email)).first
61
+ end
62
+
63
+ def find_user_by_id(user_id)
64
+ get("/core/users/#{Integer(user_id)}/")
65
+ end
66
+
67
+ # Exact, case-insensitive email matches. Re-checked locally rather than trusting the filter.
68
+ def identities_for(email:)
69
+ results(get('/core/users/', email:)).select { |u| u['email'].to_s.casecmp?(email.to_s) }
70
+ end
71
+
72
+ def set_password!(user_id, password:)
73
+ request!(:post, "/core/users/#{Integer(user_id)}/set_password/", { password: })
74
+ end
75
+
76
+ def set_password_hash!(user_id, password_hash:)
77
+ request!(:post, "/core/users/#{Integer(user_id)}/set_password_hash/", { password: password_hash })
78
+ end
79
+
80
+ # Copies a Devise (bcrypt) password hash onto the identity with this email, so a password
81
+ # changed in the app also works in vpLogin without the plaintext leaving the request.
82
+ # Returns false when vpLogin has no identity for the email.
83
+ def sync_bcrypt_password!(email:, bcrypt_hash:)
84
+ identity = find_user(email:)
85
+ return false if identity.nil?
86
+
87
+ set_password_hash!(identity['pk'], password_hash: "bcrypt$#{bcrypt_hash}")
88
+ true
89
+ end
90
+
91
+ # Fails open (true) when vpLogin can't be read, so a transient error doesn't hide password login.
92
+ def password_set?(user_id)
93
+ find_user_by_id(user_id)['has_usable_password'] != false
94
+ rescue HttpError => e
95
+ logger.error("[VpLogin::Admin] could not read password state for #{user_id}: #{e.message}")
96
+ true
97
+ end
98
+
99
+ def user_attributes(user_id)
100
+ (find_user_by_id(user_id) || {})['attributes'] || {}
101
+ end
102
+
103
+ # vpLogin's PATCH replaces `attributes` wholesale, so pass the complete hash.
104
+ def replace_user_attributes!(user_id, attributes)
105
+ request!(:patch, "/core/users/#{Integer(user_id)}/", { attributes: })
106
+ end
107
+
108
+ def merge_user_attributes!(user_id, changes)
109
+ replace_user_attributes!(user_id, user_attributes(user_id).merge(changes.transform_keys(&:to_s)))
110
+ end
111
+
112
+ # MFA devices
113
+
114
+ def import_mfa_devices!(user_id, phone_number: nil, totp_secret_base32: nil, email_device: false)
115
+ payload = { email_device:, phone_number:, totp_secret_base32: }.compact
116
+ response = request!(:post, "/core/users/#{Integer(user_id)}/import_mfa_devices/", payload)
117
+ response.is_a?(Hash) ? response['created'] : []
118
+ end
119
+
120
+ def mfa_devices(user_id)
121
+ results(get('/authenticators/admin/all/', user: Integer(user_id))).map do |device|
122
+ { id: device['pk'], type: device['type'], endpoint: DEVICE_ENDPOINTS[device['type']] }
123
+ end
124
+ end
125
+
126
+ def delete_mfa_device!(endpoint:, device_id:)
127
+ raise ArgumentError, "unknown device endpoint #{endpoint.inspect}" unless DEVICE_ENDPOINTS.value?(endpoint)
128
+
129
+ request!(:delete, "/authenticators/admin/#{endpoint}/#{Integer(device_id)}/")
130
+ end
131
+
132
+ # Groups (tenant links)
133
+
134
+ def group_names(user_id)
135
+ Array((find_user_by_id(user_id) || {})['groups_obj']).map { |g| g['name'] }.compact
136
+ end
137
+
138
+ def find_group(name:)
139
+ results(get('/core/groups/', name:)).first
140
+ end
141
+
142
+ def add_user_to_group!(user_id, group_name:)
143
+ group = find_group(name: group_name) || create_group!(group_name)
144
+
145
+ # Every member would inherit these; a tenant group must never carry them.
146
+ raise GroupPermissionsCompromised.new(group: group_name, user_id:) if group['is_superuser'] || !Array(group['roles']).empty?
147
+ return true if Array(group['users']).include?(Integer(user_id))
148
+
149
+ request!(:post, "/core/groups/#{group['pk']}/add_user/", { pk: Integer(user_id) })
150
+ true
151
+ end
152
+
153
+ def remove_user_from_group!(user_id, group_name:)
154
+ group = find_group(name: group_name)
155
+ return false if group.nil?
156
+
157
+ request!(:post, "/core/groups/#{group['pk']}/remove_user/", { pk: Integer(user_id) })
158
+ true
159
+ end
160
+
161
+ # Sessions
162
+
163
+ # Filtered by `user__username`: vpLogin silently ignores a `user=` filter and returns every
164
+ # session in the instance. Rows are re-checked against the identity's pk for the same reason.
165
+ def sessions(email:)
166
+ identities_for(email:).flat_map do |identity|
167
+ results(get('/core/authenticated_sessions/', user__username: identity['username']))
168
+ .select { |row| row['user'] == identity['pk'] }
169
+ end
170
+ end
171
+
172
+ def revoke_session!(session_uuid)
173
+ request!(:delete, "/core/authenticated_sessions/#{URI.encode_www_form_component(session_uuid.to_s)}/")
174
+ end
175
+
176
+ # Ends only the session an ID token's `sid` names - one browser, not every device. Needs the
177
+ # vpLogin `end_session` user action. Returns whether a live session was found and ended.
178
+ def end_session!(user_id, sid:)
179
+ response = request!(:post, "/core/users/#{Integer(user_id)}/end_session/", { sid: sid.to_s })
180
+ response.is_a?(Hash) && response['ended'] == true
181
+ end
182
+
183
+ def revoke_sessions_for!(email:)
184
+ sessions(email:).each { |row| revoke_session!(row['uuid'] || row['pk']) }
185
+ end
186
+
187
+ private
188
+
189
+ # Concurrent callers can both miss find_group and race to create it.
190
+ def create_group!(name)
191
+ request!(:post, '/core/groups/', { name:, is_superuser: false })
192
+ rescue HttpError => e
193
+ raise unless e.status == 400 && e.body.to_s.include?('already exists')
194
+
195
+ find_group(name:) || raise
196
+ end
197
+
198
+ def get(path, query = nil)
199
+ @http.get_json!(url(path), query:, headers: auth_headers)
200
+ end
201
+
202
+ def request!(method, path, payload = nil)
203
+ @http.send_json!(method, url(path), payload, headers: auth_headers)
204
+ end
205
+
206
+ def results(response)
207
+ return Array(response) unless response.is_a?(Hash)
208
+
209
+ response['results'] || []
210
+ end
211
+
212
+ def url(path)
213
+ "#{@config.admin_base_url}#{path}"
214
+ end
215
+
216
+ def auth_headers
217
+ @config.require!(:api_token)
218
+ { 'Authorization' => "Bearer #{@config.api_token}" }
219
+ end
220
+
221
+ def logger = @config.logger
222
+ end
223
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module VpLogin
4
+ # Verified ID token claims. Any claim is readable with `claims['name']`.
5
+ class Claims
6
+ attr_reader :raw
7
+
8
+ def initialize(raw)
9
+ @raw = raw.transform_keys(&:to_s).freeze
10
+ end
11
+
12
+ def [](key)
13
+ raw[key.to_s]
14
+ end
15
+
16
+ def sub = raw['sub']
17
+ def email = raw['email']
18
+
19
+ # Authentication methods of the vpLogin sign-in ("pwd", "mfa", ...). The session keeps them,
20
+ # so a silent sign-in reports how the user originally authenticated.
21
+ def amr = Array(raw['amr'])
22
+ def mfa? = amr.include?('mfa')
23
+
24
+ # Case and surrounding whitespace are ignored: a login_hint is whatever the person typed.
25
+ def email_matches?(other)
26
+ !email.to_s.strip.empty? && email.to_s.strip.casecmp?(other.to_s.strip)
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ module VpLogin
4
+ class Configuration
5
+ # Settings an app normally supplies through the environment. Anything set explicitly in
6
+ # `VpLogin.configure` wins; otherwise the env var is read on each access.
7
+ ENV_KEYS = {
8
+ issuer_url: 'VPLOGIN_ISSUER_URL',
9
+ client_id: 'VPLOGIN_CLIENT_ID',
10
+ client_secret: 'VPLOGIN_CLIENT_SECRET',
11
+ redirect_uri: 'VPLOGIN_REDIRECT_URL',
12
+ admin_api_url: 'VPLOGIN_ADMIN_API_URL',
13
+ api_token: 'VPLOGIN_API_TOKEN',
14
+ frontend_url: 'VPLOGIN_FRONTEND_URL'
15
+ }.freeze
16
+
17
+ ENV_KEYS.each do |key, env_name|
18
+ attr_writer key
19
+
20
+ define_method(key) do
21
+ explicit = instance_variable_get("@#{key}")
22
+ explicit.to_s.empty? ? ENV.fetch(env_name, nil) : explicit
23
+ end
24
+ end
25
+
26
+ attr_accessor :scopes, :password_check_flow
27
+
28
+ # Frontend pages the Rails controller redirects to (relative to frontend_url).
29
+ attr_accessor :frontend_callback_path, :frontend_login_path
30
+
31
+ # Model DeviseTokenAuthController looks users up in, by email.
32
+ attr_accessor :user_model
33
+
34
+ # Seconds
35
+ attr_accessor :state_ttl, :handoff_ttl, :metadata_ttl, :jwks_refresh_cooldown, :clock_skew,
36
+ :open_timeout, :read_timeout
37
+
38
+ attr_accessor :id_token_algorithms
39
+
40
+ # ActiveJob queue for the DeviseUser jobs.
41
+ attr_accessor :job_queue
42
+
43
+ # Whether VpLogin::ProvisionJob gives a new identity an email MFA factor. Off unless the app
44
+ # sets it (or VPLOGIN_PROVISION_EMAIL_MFA=true); otherwise MFA is left to vpLogin's flow.
45
+ attr_writer :provision_email_mfa
46
+
47
+ attr_writer :cache, :logger, :cache_namespace
48
+
49
+ def initialize
50
+ @scopes = 'openid email profile vp_auth_source'
51
+ @frontend_callback_path = '/vplogin-login'
52
+ @frontend_login_path = '/login'
53
+ @user_model = 'User'
54
+ @state_ttl = 600
55
+ @handoff_ttl = 300
56
+ @metadata_ttl = 3600
57
+ @jwks_refresh_cooldown = 300
58
+ @clock_skew = 30
59
+ @open_timeout = 5
60
+ @read_timeout = 15
61
+ @id_token_algorithms = ['RS256']
62
+ @job_queue = :default
63
+ end
64
+
65
+ def provision_email_mfa
66
+ return @provision_email_mfa unless @provision_email_mfa.nil?
67
+
68
+ ENV.fetch('VPLOGIN_PROVISION_EMAIL_MFA', '').strip.casecmp?('true')
69
+ end
70
+
71
+ # Per client_id by default, so apps sharing one cache never read each other's login state.
72
+ def cache_namespace
73
+ @cache_namespace || ['vplogin', client_id].compact.join(':')
74
+ end
75
+
76
+ # Resolved lazily: Rails.cache is nil until the app has booted.
77
+ def cache
78
+ @cache || rails_value(:cache) || (@fallback_cache ||= MemoryCache.new)
79
+ end
80
+
81
+ def logger
82
+ @logger || rails_value(:logger) || (@fallback_logger ||= Logger.new($stdout))
83
+ end
84
+
85
+ def discovery_url
86
+ require!(:issuer_url)
87
+ "#{issuer_url.to_s.chomp('/')}/.well-known/openid-configuration"
88
+ end
89
+
90
+ # Whether the admin API (VPLOGIN_ADMIN_API_URL / VPLOGIN_API_TOKEN) is set up; the admin-side
91
+ # Rails helpers do nothing without it.
92
+ def admin_api?
93
+ !admin_api_url.to_s.empty? && !api_token.to_s.empty?
94
+ end
95
+
96
+ def admin_base_url
97
+ require!(:admin_api_url)
98
+ "#{admin_api_url.to_s.chomp('/')}/api/v3"
99
+ end
100
+
101
+ def require!(*keys)
102
+ missing = keys.select { |key| public_send(key).to_s.strip.empty? }
103
+ return if missing.empty?
104
+
105
+ raise ConfigurationError, "VpLogin is missing configuration: #{missing.join(', ')}"
106
+ end
107
+
108
+ private
109
+
110
+ def rails_value(name)
111
+ return nil unless defined?(::Rails) && ::Rails.respond_to?(name)
112
+
113
+ ::Rails.public_send(name)
114
+ end
115
+ end
116
+ end
@@ -0,0 +1,147 @@
1
+ # frozen_string_literal: true
2
+
3
+ module VpLogin
4
+ # Login endpoints for a Rails controller. Include it (or DeviseTokenAuthController, which
5
+ # implements the sign-in for devise_token_auth apps) and draw the routes with
6
+ # `vplogin_routes controller: '...'`.
7
+ #
8
+ # GET login -> redirect to vpLogin (or `{ url: }` for XHR)
9
+ # GET callback -> redirect to the frontend with a one-time `code`
10
+ # POST verify -> frontend posts that `code` (+ `app_verifier` for native apps); signs in
11
+ #
12
+ # Required hooks:
13
+ # vplogin_resolve_user(claims, data) -> local user, or nil
14
+ # vplogin_sign_in(user, claims, data) -> create the app's session and render
15
+ #
16
+ # Optional hooks (defaults below): vplogin_frontend_url, vplogin_handoff_url, vplogin_state_data,
17
+ # vplogin_state_prefix, vplogin_login_hint, vplogin_prompt, vplogin_before_verify,
18
+ # vplogin_user_not_found, vplogin_callback_failed, vplogin_verify_failed. Any hook may
19
+ # render/redirect; the action stops if it has.
20
+ module Controller
21
+ EMAIL_FORMAT = /\A[^@\s]+@[^@\s]+\z/
22
+
23
+ def vplogin_start
24
+ data = vplogin_state_data
25
+ return if performed?
26
+
27
+ start = vplogin_oidc.start(
28
+ data:,
29
+ login_hint: vplogin_login_hint,
30
+ prompt: vplogin_prompt,
31
+ state_prefix: vplogin_state_prefix,
32
+ app_challenge: params[:app_challenge].presence
33
+ )
34
+
35
+ if vplogin_browser_navigation?
36
+ redirect_to start.url, allow_other_host: true
37
+ else
38
+ render json: { url: start.url }
39
+ end
40
+ end
41
+
42
+ def vplogin_callback
43
+ result = vplogin_oidc.callback(
44
+ state: params[:state], code: params[:code],
45
+ error: params[:error].presence, error_description: params[:error_description].presence
46
+ )
47
+ redirect_to vplogin_handoff_url(result.handoff_code, result.attempt[:data] || {}), allow_other_host: true
48
+ rescue VpLogin::Error => e
49
+ vplogin_callback_failed(e, VpLogin::Oidc.state_prefix(params[:state]))
50
+ end
51
+
52
+ def vplogin_verify
53
+ attempt = vplogin_oidc.redeem(params[:code], app_verifier: params[:app_verifier])
54
+ data = attempt[:data] || {}
55
+
56
+ vplogin_before_verify(data)
57
+ return if performed?
58
+
59
+ claims = vplogin_oidc.exchange(code: attempt[:code], code_verifier: attempt[:code_verifier], nonce: attempt[:nonce])
60
+ if attempt[:login_hint] && !claims.email_matches?(attempt[:login_hint])
61
+ raise VpLogin::IdentityMismatch, 'signed-in identity does not match login_hint'
62
+ end
63
+
64
+ user = vplogin_resolve_user(claims, data)
65
+ return if performed?
66
+ return vplogin_user_not_found(claims, data) if user.nil?
67
+
68
+ vplogin_sign_in(user, claims, data)
69
+ rescue VpLogin::Error => e
70
+ vplogin_verify_failed(e)
71
+ end
72
+
73
+ private
74
+
75
+ def vplogin_oidc
76
+ @vplogin_oidc ||= VpLogin::Oidc.new
77
+ end
78
+
79
+ def vplogin_frontend_url
80
+ VpLogin.configuration.frontend_url
81
+ end
82
+
83
+ def vplogin_handoff_url(handoff_code, _data)
84
+ vplogin_frontend_page(VpLogin.configuration.frontend_callback_path, code: handoff_code) ||
85
+ raise(VpLogin::ConfigurationError,
86
+ "set frontend_url (VPLOGIN_FRONTEND_URL) or implement #{self.class}#vplogin_handoff_url")
87
+ end
88
+
89
+ def vplogin_resolve_user(_claims, _data)
90
+ raise NotImplementedError, "#{self.class} must implement vplogin_resolve_user"
91
+ end
92
+
93
+ def vplogin_sign_in(_user, _claims, _data)
94
+ raise NotImplementedError, "#{self.class} must implement vplogin_sign_in"
95
+ end
96
+
97
+ def vplogin_state_data = {}
98
+ def vplogin_state_prefix = nil
99
+ def vplogin_before_verify(_data) = nil
100
+
101
+ def vplogin_login_hint
102
+ email = params[:email].to_s
103
+ email if email.length <= 254 && email.match?(EMAIL_FORMAT)
104
+ end
105
+
106
+ def vplogin_prompt
107
+ prompt = params[:prompt].to_s
108
+ prompt if VpLogin::Oidc::PROMPTS.include?(prompt)
109
+ end
110
+
111
+ def vplogin_user_not_found(claims, _data)
112
+ vplogin_render_error('No account found for this login.', 'USER_NOT_FOUND', :unauthorized, email: claims.email)
113
+ end
114
+
115
+ # The callback is a browser navigation from vpLogin, so with a frontend configured a failure
116
+ # goes back to its login page instead of rendering JSON at the user.
117
+ def vplogin_callback_failed(error, _state_prefix)
118
+ VpLogin.configuration.logger.info("[VpLogin] callback failed: #{error.class}: #{error.message}")
119
+ login_page = vplogin_frontend_page(VpLogin.configuration.frontend_login_path, sso_error: error.code)
120
+ return redirect_to(login_page, allow_other_host: true) if login_page
121
+
122
+ vplogin_render_error('Invalid login attempt', error.code, :bad_request)
123
+ end
124
+
125
+ def vplogin_verify_failed(error)
126
+ VpLogin.configuration.logger.warn("[VpLogin] verify failed: #{error.class}: #{error.message}")
127
+ vplogin_render_error('Login failed. Please try again', error.code, :unauthorized)
128
+ end
129
+
130
+ # Same envelope devise_token_auth uses for its own failures.
131
+ def vplogin_render_error(message, code, status, **extra)
132
+ render json: { success: false, errors: [message], code: }.merge(extra), status:
133
+ end
134
+
135
+ def vplogin_frontend_page(path, query)
136
+ base = vplogin_frontend_url.to_s.chomp('/')
137
+ return nil if base.empty?
138
+
139
+ "#{base}#{path}?#{URI.encode_www_form(query)}"
140
+ end
141
+
142
+ # Accept rather than a param: a link in an email or a redirect has no say in what it sends.
143
+ def vplogin_browser_navigation?
144
+ request.format.html? || request.headers['Accept'].to_s.include?('text/html')
145
+ end
146
+ end
147
+ end