diff --git a/lib/decidim/direct_verifications/authorize_user.rb b/lib/decidim/direct_verifications/authorize_user.rb index fa88402..53bd48f 100644 --- a/lib/decidim/direct_verifications/authorize_user.rb +++ b/lib/decidim/direct_verifications/authorize_user.rb @@ -12,43 +12,48 @@ def initialize(email, data, session, organization, instrumenter) end def call - u = find_user(email) - - if u - auth = authorization(u) - auth.metadata = data + unless user + instrumenter.add_error :authorized, email + return + end - return unless !auth.granted? || auth.expired? + return unless valid_authorization? - Verification::ConfirmUserAuthorization.call(auth, authorize_form(u), session) do - on(:ok) do - instrumenter.add_processed :authorized, email - end - on(:invalid) do - instrumenter.add_error :authorized, email - end + Verification::ConfirmUserAuthorization.call(authorization, form, session) do + on(:ok) do + instrumenter.add_processed :authorized, email + end + on(:invalid) do + instrumenter.add_error :authorized, email end - else - instrumenter.add_error :authorized, email end end private - attr_reader :email, :data, :session, :organization, :instrumenter + attr_reader :email, :data, :session, :organization, :instrumenter, :authorization, :user + + def valid_authorization? + !authorization.granted? || authorization.expired? + end - def find_user(email) - User.find_by(email: email, decidim_organization_id: organization.id) + def user + @user ||= User.find_by(email: email, decidim_organization_id: organization.id) end - def authorization(user) - Authorization.find_or_initialize_by( - user: user, - name: :direct_verifications - ) + def authorization + @authorization ||= + begin + auth = Authorization.find_or_initialize_by( + user: user, + name: :direct_verifications + ) + auth.metadata = data + auth + end end - def authorize_form(user) + def form Verification::DirectVerificationsForm.new(email: user.email, name: user.name) end end